moved getDeletionUpdates to Content interface
[lhc/web/wiklou.git] / includes / Content.php
1 <?php
2 /**
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.
5 *
6 * @since 1.WD
7 */
8 interface Content {
9
10 /**
11 * @since WD.1
12 *
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.
16 *
17 * @todo: test that this actually works
18 * @todo: make sure this also works with LuceneSearch / WikiSearch
19 */
20 public function getTextForSearchIndex( );
21
22 /**
23 * @since WD.1
24 *
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.
27 *
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?!
33 */
34 public function getWikitextForTransclusion( );
35
36 /**
37 * Returns a textual representation of the content suitable for use in edit
38 * summaries and log messages.
39 *
40 * @since WD.1
41 *
42 * @param $maxlength int Maximum length of the summary text
43 * @return The summary text
44 */
45 public function getTextForSummary( $maxlength = 250 );
46
47 /**
48 * Returns native representation of the data. Interpretation depends on
49 * the data model used, as given by getDataModel().
50 *
51 * @since WD.1
52 *
53 * @return mixed The native representation of the content. Could be a
54 * string, a nested array structure, an object, a binary blob...
55 * anything, really.
56 *
57 * @NOTE: review all calls carefully, caller must be aware of content model!
58 */
59 public function getNativeData( );
60
61 /**
62 * Returns the content's nominal size in bogo-bytes.
63 *
64 * @return int
65 */
66 public function getSize( );
67
68 /**
69 * Returns the ID of the content model used by this Content object.
70 * Corresponds to the CONTENT_MODEL_XXX constants.
71 *
72 * @since WD.1
73 *
74 * @return String The model id
75 */
76 public function getModel();
77
78 /**
79 * Convenience method that returns the ContentHandler singleton for handling
80 * the content model that this Content object uses.
81 *
82 * Shorthand for ContentHandler::getForContent( $this )
83 *
84 * @since WD.1
85 *
86 * @return ContentHandler
87 */
88 public function getContentHandler();
89
90 /**
91 * Convenience method that returns the default serialization format for the
92 * content model that this Content object uses.
93 *
94 * Shorthand for $this->getContentHandler()->getDefaultFormat()
95 *
96 * @since WD.1
97 *
98 * @return String
99 */
100 public function getDefaultFormat();
101
102 /**
103 * Convenience method that returns the list of serialization formats
104 * supported for the content model that this Content object uses.
105 *
106 * Shorthand for $this->getContentHandler()->getSupportedFormats()
107 *
108 * @since WD.1
109 *
110 * @return Array of supported serialization formats
111 */
112 public function getSupportedFormats();
113
114 /**
115 * Returns true if $format is a supported serialization format for this
116 * Content object, false if it isn't.
117 *
118 * Note that this should always return true if $format is null, because null
119 * stands for the default serialization.
120 *
121 * Shorthand for $this->getContentHandler()->isSupportedFormat( $format )
122 *
123 * @since WD.1
124 *
125 * @param $format string The format to check
126 * @return bool Whether the format is supported
127 */
128 public function isSupportedFormat( $format );
129
130 /**
131 * Convenience method for serializing this Content object.
132 *
133 * Shorthand for $this->getContentHandler()->serializeContent( $this, $format )
134 *
135 * @since WD.1
136 *
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
140 */
141 public function serialize( $format = null );
142
143 /**
144 * Returns true if this Content object represents empty content.
145 *
146 * @since WD.1
147 *
148 * @return bool Whether this Content object is empty
149 */
150 public function isEmpty();
151
152 /**
153 * Returns whether the content is valid. This is intended for local validity
154 * checks, not considering global consistency.
155 *
156 * Content needs to be valid before it can be saved.
157 *
158 * This default implementation always returns true.
159 *
160 * @since WD.1
161 *
162 * @return boolean
163 */
164 public function isValid();
165
166 /**
167 * Returns true if this Content objects is conceptually equivalent to the
168 * given Content object.
169 *
170 * Contract:
171 *
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.
177 *
178 * Implementations should be careful to make equals() transitive and reflexive:
179 *
180 * - $a->equals( $b ) <=> $b->equals( $a )
181 * - $a->equals( $b ) && $b->equals( $c ) ==> $a->equals( $c )
182 *
183 * @since WD.1
184 *
185 * @param $that Content The Content object to compare to
186 * @return bool True if this Content object is equal to $that, false otherwise.
187 */
188 public function equals( Content $that = null );
189
190 /**
191 * Return a copy of this Content object. The following must be true for the
192 * object returned:
193 *
194 * if $copy = $original->copy()
195 *
196 * - get_class($original) === get_class($copy)
197 * - $original->getModel() === $copy->getModel()
198 * - $original->equals( $copy )
199 *
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.
203 *
204 * @since WD.1
205 *
206 * @return Content. A copy of this object
207 */
208 public function copy( );
209
210 /**
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
213 * main namespace).
214 *
215 * @since WD.1
216 *
217 * @param $hasLinks Bool: If it is known whether this content contains
218 * links, provide this information here, to avoid redundant parsing to
219 * find out.
220 * @return boolean
221 */
222 public function isCountable( $hasLinks = null ) ;
223
224 /**
225 * Convenience method, shorthand for
226 * $this->getContentHandler()->getParserOutput( $this, $title, $revId, $options, $generateHtml )
227 *
228 * @note: subclasses should NOT override this to provide custom rendering.
229 * Override ContentHandler::getParserOutput() instead!
230 *
231 * @param $title Title
232 * @param $revId null
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.
237 *
238 * @since WD.1
239 *
240 * @return ParserOutput
241 */
242 public function getParserOutput( Title $title, $revId = null, ParserOptions $options = null,
243 $generateHtml = true );
244
245 /**
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).
250 *
251 * @since WD.1
252 *
253 * @return Array of Titles, with the destination last
254 */
255 public function getRedirectChain();
256
257 /**
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.
262 *
263 * @since WD.1
264 *
265 * @return Title: The corresponding Title
266 */
267 public function getRedirectTarget();
268
269 /**
270 * Construct the redirect destination from this content and return the
271 * Title, or null if this content doesn't represent a redirect.
272 *
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.
276 *
277 * There is usually no need to override the default behaviour, subclasses that
278 * want to implement redirects should override getRedirectTarget().
279 *
280 * @since WD.1
281 *
282 * @return Title
283 */
284 public function getUltimateRedirectTarget();
285
286 /**
287 * Returns whether this Content represents a redirect.
288 * Shorthand for getRedirectTarget() !== null.
289 *
290 * @since WD.1
291 *
292 * @return bool
293 */
294 public function isRedirect();
295
296 /**
297 * Returns the section with the given ID.
298 *
299 * @since WD.1
300 *
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
304 * (excluded), etc.
305 * @return Content|Boolean|null The section, or false if no such section
306 * exist, or null if sections are not supported.
307 */
308 public function getSection( $sectionId );
309
310 /**
311 * Replaces a section of the content and returns a Content object with the
312 * section replaced.
313 *
314 * @since WD.1
315 *
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
320 */
321 public function replaceSection( $section, Content $with, $sectionTitle = '' );
322
323 /**
324 * Returns a Content object with pre-save transformations applied (or this
325 * object if no transformations apply).
326 *
327 * @since WD.1
328 *
329 * @param $title Title
330 * @param $user User
331 * @param $popts null|ParserOptions
332 * @return Content
333 */
334 public function preSaveTransform( Title $title, User $user, ParserOptions $popts );
335
336 /**
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.
340 *
341 * @since WD.1
342 *
343 * @param $header string
344 * @return Content
345 */
346 public function addSectionHeader( $header );
347
348 /**
349 * Returns a Content object with preload transformations applied (or this
350 * object if no transformations apply).
351 *
352 * @since WD.1
353 *
354 * @param $title Title
355 * @param $popts null|ParserOptions
356 * @return Content
357 */
358 public function preloadTransform( Title $title, ParserOptions $popts );
359
360 /**
361 * Prepare Content for saving. Called before Content is saved by WikiPage::doEditContent().
362 * This may be used to store additional information in the database, or check the content's
363 * consistency with global state.
364 *
365 * Note that this method will be called inside the same transaction bracket that will be used
366 * to save the new revision.
367 *
368 * @param WikiPage $page The page to be saved.
369 * @param int $flags bitfield for use with EDIT_XXX constants, see WikiPage::doEditContent()
370 * @param int $baseRevId the ID of the current revision
371 * @param User $user
372 *
373 * @return Status A status object indicating whether the content was successfully prepared for saving.
374 * If the returned status indicates an error, a rollback will be performed and the
375 * transaction aborted.
376 *
377 * @see see WikiPage::doEditContent()
378 */
379 public function prepareSave( WikiPage $page, $flags, $baseRevId, User $user );
380
381 /**
382 * Returns a list of updates to perform when this content is deleted.
383 * The necessary updates may be taken from the Content object, or depend on
384 * the current state of the database.
385 *
386 * @since WD.1
387 *
388 * @param $title \Title the title of the deleted page
389 * @param $parserOutput null|\ParserOutput optional parser output object
390 * for efficient access to meta-information about the content object.
391 * Provide if you have one handy.
392 *
393 * @return array A list of DataUpdate instances that will clean up the
394 * database after deletion.
395 */
396 public function getDeletionUpdates( Title $title,
397 ParserOutput $parserOutput = null );
398
399 # TODO: handle ImagePage and CategoryPage
400 # TODO: make sure we cover lucene search / wikisearch.
401 # TODO: make sure ReplaceTemplates still works
402 # FUTURE: nice&sane integration of GeSHi syntax highlighting
403 # [11:59] <vvv> Hooks are ugly; make CodeHighlighter interface and a
404 # config to set the class which handles syntax highlighting
405 # [12:00] <vvv> And default it to a DummyHighlighter
406
407 # TODO: make sure we cover the external editor interface (does anyone actually use that?!)
408
409 # TODO: tie into API to provide contentModel for Revisions
410 # TODO: tie into API to provide serialized version and contentFormat for Revisions
411 # TODO: tie into API edit interface
412 # FUTURE: make EditForm plugin for EditPage
413
414 # FUTURE: special type for redirects?!
415 # FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
416 # FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
417 }
418
419
420 /**
421 * A content object represents page content, e.g. the text to show on a page.
422 * Content objects have no knowledge about how they relate to Wiki pages.
423 *
424 * @since 1.WD
425 */
426 abstract class AbstractContent implements Content {
427
428 /**
429 * Name of the content model this Content object represents.
430 * Use with CONTENT_MODEL_XXX constants
431 *
432 * @var string $model_id
433 */
434 protected $model_id;
435
436 /**
437 * @param String $model_id
438 */
439 public function __construct( $model_id = null ) {
440 $this->model_id = $model_id;
441 }
442
443 /**
444 * @see Content::getModel()
445 */
446 public function getModel() {
447 return $this->model_id;
448 }
449
450 /**
451 * Throws an MWException if $model_id is not the id of the content model
452 * supported by this Content object.
453 *
454 * @param $model_id int the model to check
455 *
456 * @throws MWException
457 */
458 protected function checkModelID( $model_id ) {
459 if ( $model_id !== $this->model_id ) {
460 throw new MWException( "Bad content model: " .
461 "expected {$this->model_id} " .
462 "but got $model_id." );
463 }
464 }
465
466 /**
467 * @see Content::getContentHandler()
468 */
469 public function getContentHandler() {
470 return ContentHandler::getForContent( $this );
471 }
472
473 /**
474 * @see Content::getDefaultFormat()
475 */
476 public function getDefaultFormat() {
477 return $this->getContentHandler()->getDefaultFormat();
478 }
479
480 /**
481 * @see Content::getSupportedFormats()
482 */
483 public function getSupportedFormats() {
484 return $this->getContentHandler()->getSupportedFormats();
485 }
486
487 /**
488 * @see Content::isSupportedFormat()
489 */
490 public function isSupportedFormat( $format ) {
491 if ( !$format ) {
492 return true; // this means "use the default"
493 }
494
495 return $this->getContentHandler()->isSupportedFormat( $format );
496 }
497
498 /**
499 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't
500 * return true.
501 *
502 * @param $format
503 * @throws MWException
504 */
505 protected function checkFormat( $format ) {
506 if ( !$this->isSupportedFormat( $format ) ) {
507 throw new MWException( "Format $format is not supported for content model " .
508 $this->getModel() );
509 }
510 }
511
512 /**
513 * @see Content::serialize
514 */
515 public function serialize( $format = null ) {
516 return $this->getContentHandler()->serializeContent( $this, $format );
517 }
518
519 /**
520 * @see Content::isEmpty()
521 */
522 public function isEmpty() {
523 return $this->getSize() == 0;
524 }
525
526 /**
527 * @see Content::isValid()
528 */
529 public function isValid() {
530 return true;
531 }
532
533 /**
534 * @see Content::equals()
535 */
536 public function equals( Content $that = null ) {
537 if ( is_null( $that ) ) {
538 return false;
539 }
540
541 if ( $that === $this ) {
542 return true;
543 }
544
545 if ( $that->getModel() !== $this->getModel() ) {
546 return false;
547 }
548
549 return $this->getNativeData() === $that->getNativeData();
550 }
551
552 /**
553 * @see Content::getParserOutput()
554 */
555 public function getParserOutput( Title $title, $revId = null, ParserOptions $options = null,
556 $generateHtml = true )
557 {
558 return $this->getContentHandler()->getParserOutput(
559 $this, $title, $revId, $options, $generateHtml );
560 }
561
562 /**
563 * @see Content::getRedirectChain()
564 */
565 public function getRedirectChain() {
566 global $wgMaxRedirects;
567 $title = $this->getRedirectTarget();
568 if ( is_null( $title ) ) {
569 return null;
570 }
571 // recursive check to follow double redirects
572 $recurse = $wgMaxRedirects;
573 $titles = array( $title );
574 while ( --$recurse > 0 ) {
575 if ( $title->isRedirect() ) {
576 $page = WikiPage::factory( $title );
577 $newtitle = $page->getRedirectTarget();
578 } else {
579 break;
580 }
581 // Redirects to some special pages are not permitted
582 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
583 // The new title passes the checks, so make that our current
584 // title so that further recursion can be checked
585 $title = $newtitle;
586 $titles[] = $newtitle;
587 } else {
588 break;
589 }
590 }
591 return $titles;
592 }
593
594 /**
595 * @see Content::getRedirectTarget()
596 */
597 public function getRedirectTarget() {
598 return null;
599 }
600
601 /**
602 * @see Content::getUltimateRedirectTarget()
603 * @note: migrated here from Title::newFromRedirectRecurse
604 */
605 public function getUltimateRedirectTarget() {
606 $titles = $this->getRedirectChain();
607 return $titles ? array_pop( $titles ) : null;
608 }
609
610 /**
611 * @since WD.1
612 *
613 * @return bool
614 */
615 public function isRedirect() {
616 return $this->getRedirectTarget() !== null;
617 }
618
619 /**
620 * @see Content::getSection()
621 */
622 public function getSection( $sectionId ) {
623 return null;
624 }
625
626 /**
627 * @see Content::replaceSection()
628 */
629 public function replaceSection( $section, Content $with, $sectionTitle = '' ) {
630 return null;
631 }
632
633 /**
634 * @see Content::preSaveTransform()
635 */
636 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
637 return $this;
638 }
639
640 /**
641 * @see Content::addSectionHeader()
642 */
643 public function addSectionHeader( $header ) {
644 return $this;
645 }
646
647 /**
648 * @see Content::preloadTransform()
649 */
650 public function preloadTransform( Title $title, ParserOptions $popts ) {
651 return $this;
652 }
653
654 /**
655 * @see Content::prepareSave()
656 */
657 public function prepareSave( WikiPage $page, $flags, $baseRevId, User $user ) {
658 if ( $this->isValid() ) {
659 return Status::newGood();
660 } else {
661 return Status::newFatal( "invalid-content-data" );
662 }
663 }
664
665 /**
666 * Returns a list of updates to perform when this content is deleted.
667 * The necessary updates may be taken from the Content object, or depend on
668 * the current state of the database.
669 *
670 * @since WD.1
671 *
672 * @param $title \Title the title of the deleted page
673 * @param $parserOutput null|\ParserOutput optional parser output object
674 * for efficient access to meta-information about the content object.
675 * Provide if you have one handy.
676 *
677 * @return array A list of DataUpdate instances that will clean up the
678 * database after deletion.
679 */
680 public function getDeletionUpdates( Title $title,
681 ParserOutput $parserOutput = null )
682 {
683 return array(
684 new LinksDeletionUpdate( $title ),
685 );
686 }
687 }
688
689 /**
690 * Content object implementation for representing flat text.
691 *
692 * TextContent instances are immutable
693 *
694 * @since WD.1
695 */
696 abstract class TextContent extends AbstractContent {
697
698 public function __construct( $text, $model_id = null ) {
699 parent::__construct( $model_id );
700
701 $this->mText = $text;
702 }
703
704 public function copy() {
705 return $this; # NOTE: this is ok since TextContent are immutable.
706 }
707
708 public function getTextForSummary( $maxlength = 250 ) {
709 global $wgContLang;
710
711 $text = $this->getNativeData();
712
713 $truncatedtext = $wgContLang->truncate(
714 preg_replace( "/[\n\r]/", ' ', $text ),
715 max( 0, $maxlength ) );
716
717 return $truncatedtext;
718 }
719
720 /**
721 * returns the text's size in bytes.
722 *
723 * @return int The size
724 */
725 public function getSize( ) {
726 $text = $this->getNativeData( );
727 return strlen( $text );
728 }
729
730 /**
731 * Returns true if this content is not a redirect, and $wgArticleCountMethod
732 * is "any".
733 *
734 * @param $hasLinks Bool: if it is known whether this content contains links,
735 * provide this information here, to avoid redundant parsing to find out.
736 *
737 * @return bool True if the content is countable
738 */
739 public function isCountable( $hasLinks = null ) {
740 global $wgArticleCountMethod;
741
742 if ( $this->isRedirect( ) ) {
743 return false;
744 }
745
746 if ( $wgArticleCountMethod === 'any' ) {
747 return true;
748 }
749
750 return false;
751 }
752
753 /**
754 * Returns the text represented by this Content object, as a string.
755 *
756 * @param the raw text
757 */
758 public function getNativeData( ) {
759 $text = $this->mText;
760 return $text;
761 }
762
763 /**
764 * Returns the text represented by this Content object, as a string.
765 *
766 * @param the raw text
767 */
768 public function getTextForSearchIndex( ) {
769 return $this->getNativeData();
770 }
771
772 /**
773 * Returns the text represented by this Content object, as a string.
774 *
775 * @param the raw text
776 */
777 public function getWikitextForTransclusion( ) {
778 return $this->getNativeData();
779 }
780
781 /**
782 * Diff this content object with another content object..
783 *
784 * @since WD.diff
785 *
786 * @param $that Content the other content object to compare this content object to
787 * @param $lang Language the language object to use for text segmentation.
788 * If not given, $wgContentLang is used.
789 *
790 * @return DiffResult a diff representing the changes that would have to be
791 * made to this content object to make it equal to $that.
792 */
793 public function diff( Content $that, Language $lang = null ) {
794 global $wgContLang;
795
796 $this->checkModelID( $that->getModel() );
797
798 # @todo: could implement this in DifferenceEngine and just delegate here?
799
800 if ( !$lang ) $lang = $wgContLang;
801
802 $otext = $this->getNativeData();
803 $ntext = $this->getNativeData();
804
805 # Note: Use native PHP diff, external engines don't give us abstract output
806 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
807 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
808
809 $diff = new Diff( $ota, $nta );
810 return $diff;
811 }
812
813 }
814
815 /**
816 * @since WD.1
817 */
818 class WikitextContent extends TextContent {
819
820 public function __construct( $text ) {
821 parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
822 }
823
824 /**
825 * @see Content::getSection()
826 */
827 public function getSection( $section ) {
828 global $wgParser;
829
830 $text = $this->getNativeData();
831 $sect = $wgParser->getSection( $text, $section, false );
832
833 return new WikitextContent( $sect );
834 }
835
836 /**
837 * @see Content::replaceSection()
838 */
839 public function replaceSection( $section, Content $with, $sectionTitle = '' ) {
840 wfProfileIn( __METHOD__ );
841
842 $myModelId = $this->getModel();
843 $sectionModelId = $with->getModel();
844
845 if ( $sectionModelId != $myModelId ) {
846 throw new MWException( "Incompatible content model for section: " .
847 "document uses $myModelId but " .
848 "section uses $sectionModelId." );
849 }
850
851 $oldtext = $this->getNativeData();
852 $text = $with->getNativeData();
853
854 if ( $section === '' ) {
855 return $with; # XXX: copy first?
856 } if ( $section == 'new' ) {
857 # Inserting a new section
858 if ( $sectionTitle ) {
859 $subject = wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n";
860 } else {
861 $subject = '';
862 }
863 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
864 $text = strlen( trim( $oldtext ) ) > 0
865 ? "{$oldtext}\n\n{$subject}{$text}"
866 : "{$subject}{$text}";
867 }
868 } else {
869 # Replacing an existing section; roll out the big guns
870 global $wgParser;
871
872 $text = $wgParser->replaceSection( $oldtext, $section, $text );
873 }
874
875 $newContent = new WikitextContent( $text );
876
877 wfProfileOut( __METHOD__ );
878 return $newContent;
879 }
880
881 /**
882 * Returns a new WikitextContent object with the given section heading
883 * prepended.
884 *
885 * @param $header string
886 * @return Content
887 */
888 public function addSectionHeader( $header ) {
889 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $header ) . "\n\n" .
890 $this->getNativeData();
891
892 return new WikitextContent( $text );
893 }
894
895 /**
896 * Returns a Content object with pre-save transformations applied using
897 * Parser::preSaveTransform().
898 *
899 * @param $title Title
900 * @param $user User
901 * @param $popts ParserOptions
902 * @return Content
903 */
904 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
905 global $wgParser;
906
907 $text = $this->getNativeData();
908 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
909
910 return new WikitextContent( $pst );
911 }
912
913 /**
914 * Returns a Content object with preload transformations applied (or this
915 * object if no transformations apply).
916 *
917 * @param $title Title
918 * @param $popts ParserOptions
919 * @return Content
920 */
921 public function preloadTransform( Title $title, ParserOptions $popts ) {
922 global $wgParser;
923
924 $text = $this->getNativeData();
925 $plt = $wgParser->getPreloadText( $text, $title, $popts );
926
927 return new WikitextContent( $plt );
928 }
929
930 /**
931 * Implement redirect extraction for wikitext.
932 *
933 * @return null|Title
934 *
935 * @note: migrated here from Title::newFromRedirectInternal()
936 *
937 * @see Content::getRedirectTarget
938 * @see AbstractContent::getRedirectTarget
939 */
940 public function getRedirectTarget() {
941 global $wgMaxRedirects;
942 if ( $wgMaxRedirects < 1 ) {
943 // redirects are disabled, so quit early
944 return null;
945 }
946 $redir = MagicWord::get( 'redirect' );
947 $text = trim( $this->getNativeData() );
948 if ( $redir->matchStartAndRemove( $text ) ) {
949 // Extract the first link and see if it's usable
950 // Ensure that it really does come directly after #REDIRECT
951 // Some older redirects included a colon, so don't freak about that!
952 $m = array();
953 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
954 // Strip preceding colon used to "escape" categories, etc.
955 // and URL-decode links
956 if ( strpos( $m[1], '%' ) !== false ) {
957 // Match behavior of inline link parsing here;
958 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
959 }
960 $title = Title::newFromText( $m[1] );
961 // If the title is a redirect to bad special pages or is invalid, return null
962 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
963 return null;
964 }
965 return $title;
966 }
967 }
968 return null;
969 }
970
971 /**
972 * Returns true if this content is not a redirect, and this content's text
973 * is countable according to the criteria defined by $wgArticleCountMethod.
974 *
975 * @param $hasLinks Bool if it is known whether this content contains
976 * links, provide this information here, to avoid redundant parsing to
977 * find out.
978 * @param $title null|\Title
979 *
980 * @internal param \IContextSource $context context for parsing if necessary
981 *
982 * @return bool True if the content is countable
983 */
984 public function isCountable( $hasLinks = null, Title $title = null ) {
985 global $wgArticleCountMethod;
986
987 if ( $this->isRedirect( ) ) {
988 return false;
989 }
990
991 $text = $this->getNativeData();
992
993 switch ( $wgArticleCountMethod ) {
994 case 'any':
995 return true;
996 case 'comma':
997 return strpos( $text, ',' ) !== false;
998 case 'link':
999 if ( $hasLinks === null ) { # not known, find out
1000 if ( !$title ) {
1001 $context = RequestContext::getMain();
1002 $title = $context->getTitle();
1003 }
1004
1005 $po = $this->getParserOutput( $title, null, null, false );
1006 $links = $po->getLinks();
1007 $hasLinks = !empty( $links );
1008 }
1009
1010 return $hasLinks;
1011 }
1012
1013 return false;
1014 }
1015
1016 public function getTextForSummary( $maxlength = 250 ) {
1017 $truncatedtext = parent::getTextForSummary( $maxlength );
1018
1019 # clean up unfinished links
1020 # XXX: make this optional? wasn't there in autosummary, but required for
1021 # deletion summary.
1022 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
1023
1024 return $truncatedtext;
1025 }
1026
1027 }
1028
1029 /**
1030 * @since WD.1
1031 */
1032 class MessageContent extends TextContent {
1033 public function __construct( $msg_key, $params = null, $options = null ) {
1034 # XXX: messages may be wikitext, html or plain text! and maybe even
1035 # something else entirely.
1036 parent::__construct( null, CONTENT_MODEL_WIKITEXT );
1037
1038 $this->mMessageKey = $msg_key;
1039
1040 $this->mParameters = $params;
1041
1042 if ( is_null( $options ) ) {
1043 $options = array();
1044 }
1045 elseif ( is_string( $options ) ) {
1046 $options = array( $options );
1047 }
1048
1049 $this->mOptions = $options;
1050 }
1051
1052 /**
1053 * Returns the message as rendered HTML, using the options supplied to the
1054 * constructor plus "parse".
1055 * @param the message text, parsed
1056 */
1057 public function getHtml( ) {
1058 $opt = array_merge( $this->mOptions, array( 'parse' ) );
1059
1060 return wfMsgExt( $this->mMessageKey, $this->mParameters, $opt );
1061 }
1062
1063
1064 /**
1065 * Returns the message as raw text, using the options supplied to the
1066 * constructor minus "parse" and "parseinline".
1067 *
1068 * @param the message text, unparsed.
1069 */
1070 public function getNativeData( ) {
1071 $opt = array_diff( $this->mOptions, array( 'parse', 'parseinline' ) );
1072
1073 return wfMsgExt( $this->mMessageKey, $this->mParameters, $opt );
1074 }
1075
1076 }
1077
1078 /**
1079 * @since WD.1
1080 */
1081 class JavaScriptContent extends TextContent {
1082 public function __construct( $text ) {
1083 parent::__construct( $text, CONTENT_MODEL_JAVASCRIPT );
1084 }
1085
1086 /**
1087 * Returns a Content object with pre-save transformations applied using
1088 * Parser::preSaveTransform().
1089 *
1090 * @param Title $title
1091 * @param User $user
1092 * @param ParserOptions $popts
1093 * @return Content
1094 */
1095 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
1096 global $wgParser;
1097 // @todo: make pre-save transformation optional for script pages
1098 // See bug #32858
1099
1100 $text = $this->getNativeData();
1101 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
1102
1103 return new JavaScriptContent( $pst );
1104 }
1105
1106 }
1107
1108 /**
1109 * @since WD.1
1110 */
1111 class CssContent extends TextContent {
1112 public function __construct( $text ) {
1113 parent::__construct( $text, CONTENT_MODEL_CSS );
1114 }
1115
1116 /**
1117 * Returns a Content object with pre-save transformations applied using
1118 * Parser::preSaveTransform().
1119 *
1120 * @param $title Title
1121 * @param $user User
1122 * @param $popts ParserOptions
1123 * @return Content
1124 */
1125 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
1126 global $wgParser;
1127 // @todo: make pre-save transformation optional for script pages
1128
1129 $text = $this->getNativeData();
1130 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
1131
1132 return new CssContent( $pst );
1133 }
1134
1135 }