Check prepareSave() before undeleting.
[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 /**
226 * Parse the Content object and generate a ParserOutput from the result.
227 * $result->getText() can be used to obtain the generated HTML. If no HTML
228 * is needed, $generateHtml can be set to false; in that case,
229 * $result->getText() may return null.
230 *
231 * @param $title Title The page title to use as a context for rendering
232 * @param $revId null|int The revision being rendered (optional)
233 * @param $options null|ParserOptions Any parser options
234 * @param $generateHtml Boolean Whether to generate HTML (default: true). If false,
235 * the result of calling getText() on the ParserOutput object returned by
236 * this method is undefined.
237 *
238 * @since WD.1
239 *
240 * @return ParserOutput
241 */
242 public function getParserOutput( Title $title,
243 $revId = null,
244 ParserOptions $options = null, $generateHtml = true );
245 # TODO: make RenderOutput and RenderOptions base classes
246
247 /**
248 * Returns a list of DataUpdate objects for recording information about this
249 * Content in some secondary data store. If the optional second argument,
250 * $old, is given, the updates may model only the changes that need to be
251 * made to replace information about the old content with information about
252 * the new content.
253 *
254 * This default implementation calls
255 * $this->getParserOutput( $content, $title, null, null, false ),
256 * and then calls getSecondaryDataUpdates( $title, $recursive ) on the
257 * resulting ParserOutput object.
258 *
259 * Subclasses may implement this to determine the necessary updates more
260 * efficiently, or make use of information about the old content.
261 *
262 * @param $title Title The context for determining the necessary updates
263 * @param $old Content|null An optional Content object representing the
264 * previous content, i.e. the content being replaced by this Content
265 * object.
266 * @param $recursive boolean Whether to include recursive updates (default:
267 * false).
268 * @param $parserOutput ParserOutput|null Optional ParserOutput object.
269 * Provide if you have one handy, to avoid re-parsing of the content.
270 *
271 * @return Array. A list of DataUpdate objects for putting information
272 * about this content object somewhere.
273 *
274 * @since WD.1
275 */
276 public function getSecondaryDataUpdates( Title $title,
277 Content $old = null,
278 $recursive = true, ParserOutput $parserOutput = null
279 );
280
281 /**
282 * Construct the redirect destination from this content and return an
283 * array of Titles, or null if this content doesn't represent a redirect.
284 * The last element in the array is the final destination after all redirects
285 * have been resolved (up to $wgMaxRedirects times).
286 *
287 * @since WD.1
288 *
289 * @return Array of Titles, with the destination last
290 */
291 public function getRedirectChain();
292
293 /**
294 * Construct the redirect destination from this content and return a Title,
295 * or null if this content doesn't represent a redirect.
296 * This will only return the immediate redirect target, useful for
297 * the redirect table and other checks that don't need full recursion.
298 *
299 * @since WD.1
300 *
301 * @return Title: The corresponding Title
302 */
303 public function getRedirectTarget();
304
305 /**
306 * Construct the redirect destination from this content and return the
307 * Title, or null if this content doesn't represent a redirect.
308 *
309 * This will recurse down $wgMaxRedirects times or until a non-redirect
310 * target is hit in order to provide (hopefully) the Title of the final
311 * destination instead of another redirect.
312 *
313 * There is usually no need to override the default behaviour, subclasses that
314 * want to implement redirects should override getRedirectTarget().
315 *
316 * @since WD.1
317 *
318 * @return Title
319 */
320 public function getUltimateRedirectTarget();
321
322 /**
323 * Returns whether this Content represents a redirect.
324 * Shorthand for getRedirectTarget() !== null.
325 *
326 * @since WD.1
327 *
328 * @return bool
329 */
330 public function isRedirect();
331
332 /**
333 * Returns the section with the given ID.
334 *
335 * @since WD.1
336 *
337 * @param $sectionId string The section's ID, given as a numeric string.
338 * The ID "0" retrieves the section before the first heading, "1" the
339 * text between the first heading (included) and the second heading
340 * (excluded), etc.
341 * @return Content|Boolean|null The section, or false if no such section
342 * exist, or null if sections are not supported.
343 */
344 public function getSection( $sectionId );
345
346 /**
347 * Replaces a section of the content and returns a Content object with the
348 * section replaced.
349 *
350 * @since WD.1
351 *
352 * @param $section Empty/null/false or a section number (0, 1, 2, T1, T2...), or "new"
353 * @param $with Content: new content of the section
354 * @param $sectionTitle String: new section's subject, only if $section is 'new'
355 * @return string Complete article text, or null if error
356 */
357 public function replaceSection( $section, Content $with, $sectionTitle = '' );
358
359 /**
360 * Returns a Content object with pre-save transformations applied (or this
361 * object if no transformations apply).
362 *
363 * @since WD.1
364 *
365 * @param $title Title
366 * @param $user User
367 * @param $popts null|ParserOptions
368 * @return Content
369 */
370 public function preSaveTransform( Title $title, User $user, ParserOptions $popts );
371
372 /**
373 * Returns a new WikitextContent object with the given section heading
374 * prepended, if supported. The default implementation just returns this
375 * Content object unmodified, ignoring the section header.
376 *
377 * @since WD.1
378 *
379 * @param $header string
380 * @return Content
381 */
382 public function addSectionHeader( $header );
383
384 /**
385 * Returns a Content object with preload transformations applied (or this
386 * object if no transformations apply).
387 *
388 * @since WD.1
389 *
390 * @param $title Title
391 * @param $popts null|ParserOptions
392 * @return Content
393 */
394 public function preloadTransform( Title $title, ParserOptions $popts );
395
396 /**
397 * Prepare Content for saving. Called before Content is saved by WikiPage::doEditContent() and in
398 * similar places.
399 *
400 * This may be used to check the content's consistency with global state. This function should
401 * NOT write any information to the database.
402 *
403 * Note that this method will usually be called inside the same transaction bracket that will be used
404 * to save the new revision.
405 *
406 * Note that this method is called before any update to the page table is performed. This means that
407 * $page may not yet know a page ID.
408 *
409 * @param WikiPage $page The page to be saved.
410 * @param int $flags bitfield for use with EDIT_XXX constants, see WikiPage::doEditContent()
411 * @param int $baseRevId the ID of the current revision
412 * @param User $user
413 *
414 * @return Status A status object indicating whether the content was successfully prepared for saving.
415 * If the returned status indicates an error, a rollback will be performed and the
416 * transaction aborted.
417 *
418 * @see see WikiPage::doEditContent()
419 */
420 public function prepareSave( WikiPage $page, $flags, $baseRevId, User $user );
421
422 /**
423 * Returns a list of updates to perform when this content is deleted.
424 * The necessary updates may be taken from the Content object, or depend on
425 * the current state of the database.
426 *
427 * @since WD.1
428 *
429 * @param $title \Title the title of the deleted page
430 * @param $parserOutput null|\ParserOutput optional parser output object
431 * for efficient access to meta-information about the content object.
432 * Provide if you have one handy.
433 *
434 * @return array A list of DataUpdate instances that will clean up the
435 * database after deletion.
436 */
437 public function getDeletionUpdates( Title $title,
438 ParserOutput $parserOutput = null );
439
440 # TODO: handle ImagePage and CategoryPage
441 # TODO: make sure we cover lucene search / wikisearch.
442 # TODO: make sure ReplaceTemplates still works
443 # FUTURE: nice&sane integration of GeSHi syntax highlighting
444 # [11:59] <vvv> Hooks are ugly; make CodeHighlighter interface and a
445 # config to set the class which handles syntax highlighting
446 # [12:00] <vvv> And default it to a DummyHighlighter
447
448 # TODO: make sure we cover the external editor interface (does anyone actually use that?!)
449
450 # TODO: tie into API to provide contentModel for Revisions
451 # TODO: tie into API to provide serialized version and contentFormat for Revisions
452 # TODO: tie into API edit interface
453 # FUTURE: make EditForm plugin for EditPage
454
455 # FUTURE: special type for redirects?!
456 # FUTURE: MultipartMultipart < WikipageContent (Main + Links + X)
457 # FUTURE: LinksContent < LanguageLinksContent, CategoriesContent
458 }
459
460
461 /**
462 * A content object represents page content, e.g. the text to show on a page.
463 * Content objects have no knowledge about how they relate to Wiki pages.
464 *
465 * @since 1.WD
466 */
467 abstract class AbstractContent implements Content {
468
469 /**
470 * Name of the content model this Content object represents.
471 * Use with CONTENT_MODEL_XXX constants
472 *
473 * @var string $model_id
474 */
475 protected $model_id;
476
477 /**
478 * @param String $model_id
479 */
480 public function __construct( $model_id = null ) {
481 $this->model_id = $model_id;
482 }
483
484 /**
485 * @see Content::getModel()
486 */
487 public function getModel() {
488 return $this->model_id;
489 }
490
491 /**
492 * Throws an MWException if $model_id is not the id of the content model
493 * supported by this Content object.
494 *
495 * @param $model_id int the model to check
496 *
497 * @throws MWException
498 */
499 protected function checkModelID( $model_id ) {
500 if ( $model_id !== $this->model_id ) {
501 throw new MWException( "Bad content model: " .
502 "expected {$this->model_id} " .
503 "but got $model_id." );
504 }
505 }
506
507 /**
508 * @see Content::getContentHandler()
509 */
510 public function getContentHandler() {
511 return ContentHandler::getForContent( $this );
512 }
513
514 /**
515 * @see Content::getDefaultFormat()
516 */
517 public function getDefaultFormat() {
518 return $this->getContentHandler()->getDefaultFormat();
519 }
520
521 /**
522 * @see Content::getSupportedFormats()
523 */
524 public function getSupportedFormats() {
525 return $this->getContentHandler()->getSupportedFormats();
526 }
527
528 /**
529 * @see Content::isSupportedFormat()
530 */
531 public function isSupportedFormat( $format ) {
532 if ( !$format ) {
533 return true; // this means "use the default"
534 }
535
536 return $this->getContentHandler()->isSupportedFormat( $format );
537 }
538
539 /**
540 * Throws an MWException if $this->isSupportedFormat( $format ) doesn't
541 * return true.
542 *
543 * @param $format
544 * @throws MWException
545 */
546 protected function checkFormat( $format ) {
547 if ( !$this->isSupportedFormat( $format ) ) {
548 throw new MWException( "Format $format is not supported for content model " .
549 $this->getModel() );
550 }
551 }
552
553 /**
554 * @see Content::serialize
555 */
556 public function serialize( $format = null ) {
557 return $this->getContentHandler()->serializeContent( $this, $format );
558 }
559
560 /**
561 * @see Content::isEmpty()
562 */
563 public function isEmpty() {
564 return $this->getSize() == 0;
565 }
566
567 /**
568 * @see Content::isValid()
569 */
570 public function isValid() {
571 return true;
572 }
573
574 /**
575 * @see Content::equals()
576 */
577 public function equals( Content $that = null ) {
578 if ( is_null( $that ) ) {
579 return false;
580 }
581
582 if ( $that === $this ) {
583 return true;
584 }
585
586 if ( $that->getModel() !== $this->getModel() ) {
587 return false;
588 }
589
590 return $this->getNativeData() === $that->getNativeData();
591 }
592
593
594 /**
595 * Returns a list of DataUpdate objects for recording information about this
596 * Content in some secondary data store.
597 *
598 * This default implementation calls
599 * $this->getParserOutput( $content, $title, null, null, false ),
600 * and then calls getSecondaryDataUpdates( $title, $recursive ) on the
601 * resulting ParserOutput object.
602 *
603 * Subclasses may override this to determine the secondary data updates more
604 * efficiently, preferrably without the need to generate a parser output object.
605 *
606 * @see Content::getSecondaryDataUpdates()
607 *
608 * @param $title Title The context for determining the necessary updates
609 * @param $old Content|null An optional Content object representing the
610 * previous content, i.e. the content being replaced by this Content
611 * object.
612 * @param $recursive boolean Whether to include recursive updates (default:
613 * false).
614 * @param $parserOutput ParserOutput|null Optional ParserOutput object.
615 * Provide if you have one handy, to avoid re-parsing of the content.
616 *
617 * @return Array. A list of DataUpdate objects for putting information
618 * about this content object somewhere.
619 *
620 * @since WD.1
621 */
622 public function getSecondaryDataUpdates( Title $title,
623 Content $old = null,
624 $recursive = true, ParserOutput $parserOutput = null
625 ) {
626 if ( !$parserOutput ) {
627 $parserOutput = $this->getParserOutput( $title, null, null, false );
628 }
629
630 return $parserOutput->getSecondaryDataUpdates( $title, $recursive );
631 }
632
633
634 /**
635 * @see Content::getRedirectChain()
636 */
637 public function getRedirectChain() {
638 global $wgMaxRedirects;
639 $title = $this->getRedirectTarget();
640 if ( is_null( $title ) ) {
641 return null;
642 }
643 // recursive check to follow double redirects
644 $recurse = $wgMaxRedirects;
645 $titles = array( $title );
646 while ( --$recurse > 0 ) {
647 if ( $title->isRedirect() ) {
648 $page = WikiPage::factory( $title );
649 $newtitle = $page->getRedirectTarget();
650 } else {
651 break;
652 }
653 // Redirects to some special pages are not permitted
654 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
655 // The new title passes the checks, so make that our current
656 // title so that further recursion can be checked
657 $title = $newtitle;
658 $titles[] = $newtitle;
659 } else {
660 break;
661 }
662 }
663 return $titles;
664 }
665
666 /**
667 * @see Content::getRedirectTarget()
668 */
669 public function getRedirectTarget() {
670 return null;
671 }
672
673 /**
674 * @see Content::getUltimateRedirectTarget()
675 * @note: migrated here from Title::newFromRedirectRecurse
676 */
677 public function getUltimateRedirectTarget() {
678 $titles = $this->getRedirectChain();
679 return $titles ? array_pop( $titles ) : null;
680 }
681
682 /**
683 * @since WD.1
684 *
685 * @return bool
686 */
687 public function isRedirect() {
688 return $this->getRedirectTarget() !== null;
689 }
690
691 /**
692 * @see Content::getSection()
693 */
694 public function getSection( $sectionId ) {
695 return null;
696 }
697
698 /**
699 * @see Content::replaceSection()
700 */
701 public function replaceSection( $section, Content $with, $sectionTitle = '' ) {
702 return null;
703 }
704
705 /**
706 * @see Content::preSaveTransform()
707 */
708 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
709 return $this;
710 }
711
712 /**
713 * @see Content::addSectionHeader()
714 */
715 public function addSectionHeader( $header ) {
716 return $this;
717 }
718
719 /**
720 * @see Content::preloadTransform()
721 */
722 public function preloadTransform( Title $title, ParserOptions $popts ) {
723 return $this;
724 }
725
726 /**
727 * @see Content::prepareSave()
728 */
729 public function prepareSave( WikiPage $page, $flags, $baseRevId, User $user ) {
730 if ( $this->isValid() ) {
731 return Status::newGood();
732 } else {
733 return Status::newFatal( "invalid-content-data" );
734 }
735 }
736
737 /**
738 * Returns a list of updates to perform when this content is deleted.
739 * The necessary updates may be taken from the Content object, or depend on
740 * the current state of the database.
741 *
742 * @since WD.1
743 *
744 * @param $title \Title the title of the deleted page
745 * @param $parserOutput null|\ParserOutput optional parser output object
746 * for efficient access to meta-information about the content object.
747 * Provide if you have one handy.
748 *
749 * @return array A list of DataUpdate instances that will clean up the
750 * database after deletion.
751 */
752 public function getDeletionUpdates( Title $title,
753 ParserOutput $parserOutput = null )
754 {
755 return array(
756 new LinksDeletionUpdate( $title ),
757 );
758 }
759 }
760
761 /**
762 * Content object implementation for representing flat text.
763 *
764 * TextContent instances are immutable
765 *
766 * @since WD.1
767 */
768 abstract class TextContent extends AbstractContent {
769
770 public function __construct( $text, $model_id = null ) {
771 parent::__construct( $model_id );
772
773 $this->mText = $text;
774 }
775
776 public function copy() {
777 return $this; # NOTE: this is ok since TextContent are immutable.
778 }
779
780 public function getTextForSummary( $maxlength = 250 ) {
781 global $wgContLang;
782
783 $text = $this->getNativeData();
784
785 $truncatedtext = $wgContLang->truncate(
786 preg_replace( "/[\n\r]/", ' ', $text ),
787 max( 0, $maxlength ) );
788
789 return $truncatedtext;
790 }
791
792 /**
793 * returns the text's size in bytes.
794 *
795 * @return int The size
796 */
797 public function getSize( ) {
798 $text = $this->getNativeData( );
799 return strlen( $text );
800 }
801
802 /**
803 * Returns true if this content is not a redirect, and $wgArticleCountMethod
804 * is "any".
805 *
806 * @param $hasLinks Bool: if it is known whether this content contains links,
807 * provide this information here, to avoid redundant parsing to find out.
808 *
809 * @return bool True if the content is countable
810 */
811 public function isCountable( $hasLinks = null ) {
812 global $wgArticleCountMethod;
813
814 if ( $this->isRedirect( ) ) {
815 return false;
816 }
817
818 if ( $wgArticleCountMethod === 'any' ) {
819 return true;
820 }
821
822 return false;
823 }
824
825 /**
826 * Returns the text represented by this Content object, as a string.
827 *
828 * @param the raw text
829 */
830 public function getNativeData( ) {
831 $text = $this->mText;
832 return $text;
833 }
834
835 /**
836 * Returns the text represented by this Content object, as a string.
837 *
838 * @param the raw text
839 */
840 public function getTextForSearchIndex( ) {
841 return $this->getNativeData();
842 }
843
844 /**
845 * Returns the text represented by this Content object, as a string.
846 *
847 * @param the raw text
848 */
849 public function getWikitextForTransclusion( ) {
850 return $this->getNativeData();
851 }
852
853 /**
854 * Diff this content object with another content object..
855 *
856 * @since WD.diff
857 *
858 * @param $that Content the other content object to compare this content object to
859 * @param $lang Language the language object to use for text segmentation.
860 * If not given, $wgContentLang is used.
861 *
862 * @return DiffResult a diff representing the changes that would have to be
863 * made to this content object to make it equal to $that.
864 */
865 public function diff( Content $that, Language $lang = null ) {
866 global $wgContLang;
867
868 $this->checkModelID( $that->getModel() );
869
870 # @todo: could implement this in DifferenceEngine and just delegate here?
871
872 if ( !$lang ) $lang = $wgContLang;
873
874 $otext = $this->getNativeData();
875 $ntext = $this->getNativeData();
876
877 # Note: Use native PHP diff, external engines don't give us abstract output
878 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
879 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
880
881 $diff = new Diff( $ota, $nta );
882 return $diff;
883 }
884
885
886 /**
887 * Returns a generic ParserOutput object, wrapping the HTML returned by
888 * getHtml().
889 *
890 * @param $title Title Context title for parsing
891 * @param $revId int|null Revision ID (for {{REVISIONID}})
892 * @param $options ParserOptions|null Parser options
893 * @param $generateHtml bool Whether or not to generate HTML
894 *
895 * @return ParserOutput representing the HTML form of the text
896 */
897 public function getParserOutput( Title $title,
898 $revId = null,
899 ParserOptions $options = null, $generateHtml = true
900 ) {
901 # Generic implementation, relying on $this->getHtml()
902
903 if ( $generateHtml ) {
904 $html = $this->getHtml();
905 } else {
906 $html = '';
907 }
908
909 $po = new ParserOutput( $html );
910 return $po;
911 }
912
913 /**
914 * Generates an HTML version of the content, for display. Used by
915 * getParserOutput() to construct a ParserOutput object.
916 *
917 * This default implementation just calls getHighlightHtml(). Content
918 * models that have another mapping to HTML (as is the case for markup
919 * languages like wikitext) should override this method to generate the
920 * appropriate HTML.
921 *
922 * @return string An HTML representation of the content
923 */
924 protected function getHtml() {
925 return $this->getHighlightHtml();
926 }
927
928 /**
929 * Generates a syntax-highlighted version of the content, as HTML.
930 * Used by the default implementation of getHtml().
931 *
932 * @return string an HTML representation of the content's markup
933 */
934 protected function getHighlightHtml( ) {
935 # TODO: make Highlighter interface, use highlighter here, if available
936 return htmlspecialchars( $this->getNativeData() );
937 }
938
939 }
940
941 /**
942 * @since WD.1
943 */
944 class WikitextContent extends TextContent {
945
946 public function __construct( $text ) {
947 parent::__construct( $text, CONTENT_MODEL_WIKITEXT );
948 }
949
950 /**
951 * @see Content::getSection()
952 */
953 public function getSection( $section ) {
954 global $wgParser;
955
956 $text = $this->getNativeData();
957 $sect = $wgParser->getSection( $text, $section, false );
958
959 return new WikitextContent( $sect );
960 }
961
962 /**
963 * @see Content::replaceSection()
964 */
965 public function replaceSection( $section, Content $with, $sectionTitle = '' ) {
966 wfProfileIn( __METHOD__ );
967
968 $myModelId = $this->getModel();
969 $sectionModelId = $with->getModel();
970
971 if ( $sectionModelId != $myModelId ) {
972 throw new MWException( "Incompatible content model for section: " .
973 "document uses $myModelId but " .
974 "section uses $sectionModelId." );
975 }
976
977 $oldtext = $this->getNativeData();
978 $text = $with->getNativeData();
979
980 if ( $section === '' ) {
981 return $with; # XXX: copy first?
982 } if ( $section == 'new' ) {
983 # Inserting a new section
984 if ( $sectionTitle ) {
985 $subject = wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n";
986 } else {
987 $subject = '';
988 }
989 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
990 $text = strlen( trim( $oldtext ) ) > 0
991 ? "{$oldtext}\n\n{$subject}{$text}"
992 : "{$subject}{$text}";
993 }
994 } else {
995 # Replacing an existing section; roll out the big guns
996 global $wgParser;
997
998 $text = $wgParser->replaceSection( $oldtext, $section, $text );
999 }
1000
1001 $newContent = new WikitextContent( $text );
1002
1003 wfProfileOut( __METHOD__ );
1004 return $newContent;
1005 }
1006
1007 /**
1008 * Returns a new WikitextContent object with the given section heading
1009 * prepended.
1010 *
1011 * @param $header string
1012 * @return Content
1013 */
1014 public function addSectionHeader( $header ) {
1015 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $header ) . "\n\n" .
1016 $this->getNativeData();
1017
1018 return new WikitextContent( $text );
1019 }
1020
1021 /**
1022 * Returns a Content object with pre-save transformations applied using
1023 * Parser::preSaveTransform().
1024 *
1025 * @param $title Title
1026 * @param $user User
1027 * @param $popts ParserOptions
1028 * @return Content
1029 */
1030 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
1031 global $wgParser;
1032
1033 $text = $this->getNativeData();
1034 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
1035
1036 return new WikitextContent( $pst );
1037 }
1038
1039 /**
1040 * Returns a Content object with preload transformations applied (or this
1041 * object if no transformations apply).
1042 *
1043 * @param $title Title
1044 * @param $popts ParserOptions
1045 * @return Content
1046 */
1047 public function preloadTransform( Title $title, ParserOptions $popts ) {
1048 global $wgParser;
1049
1050 $text = $this->getNativeData();
1051 $plt = $wgParser->getPreloadText( $text, $title, $popts );
1052
1053 return new WikitextContent( $plt );
1054 }
1055
1056 /**
1057 * Implement redirect extraction for wikitext.
1058 *
1059 * @return null|Title
1060 *
1061 * @note: migrated here from Title::newFromRedirectInternal()
1062 *
1063 * @see Content::getRedirectTarget
1064 * @see AbstractContent::getRedirectTarget
1065 */
1066 public function getRedirectTarget() {
1067 global $wgMaxRedirects;
1068 if ( $wgMaxRedirects < 1 ) {
1069 // redirects are disabled, so quit early
1070 return null;
1071 }
1072 $redir = MagicWord::get( 'redirect' );
1073 $text = trim( $this->getNativeData() );
1074 if ( $redir->matchStartAndRemove( $text ) ) {
1075 // Extract the first link and see if it's usable
1076 // Ensure that it really does come directly after #REDIRECT
1077 // Some older redirects included a colon, so don't freak about that!
1078 $m = array();
1079 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
1080 // Strip preceding colon used to "escape" categories, etc.
1081 // and URL-decode links
1082 if ( strpos( $m[1], '%' ) !== false ) {
1083 // Match behavior of inline link parsing here;
1084 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
1085 }
1086 $title = Title::newFromText( $m[1] );
1087 // If the title is a redirect to bad special pages or is invalid, return null
1088 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
1089 return null;
1090 }
1091 return $title;
1092 }
1093 }
1094 return null;
1095 }
1096
1097 /**
1098 * Returns true if this content is not a redirect, and this content's text
1099 * is countable according to the criteria defined by $wgArticleCountMethod.
1100 *
1101 * @param $hasLinks Bool if it is known whether this content contains
1102 * links, provide this information here, to avoid redundant parsing to
1103 * find out.
1104 * @param $title null|\Title
1105 *
1106 * @internal param \IContextSource $context context for parsing if necessary
1107 *
1108 * @return bool True if the content is countable
1109 */
1110 public function isCountable( $hasLinks = null, Title $title = null ) {
1111 global $wgArticleCountMethod;
1112
1113 if ( $this->isRedirect( ) ) {
1114 return false;
1115 }
1116
1117 $text = $this->getNativeData();
1118
1119 switch ( $wgArticleCountMethod ) {
1120 case 'any':
1121 return true;
1122 case 'comma':
1123 return strpos( $text, ',' ) !== false;
1124 case 'link':
1125 if ( $hasLinks === null ) { # not known, find out
1126 if ( !$title ) {
1127 $context = RequestContext::getMain();
1128 $title = $context->getTitle();
1129 }
1130
1131 $po = $this->getParserOutput( $title, null, null, false );
1132 $links = $po->getLinks();
1133 $hasLinks = !empty( $links );
1134 }
1135
1136 return $hasLinks;
1137 }
1138
1139 return false;
1140 }
1141
1142 public function getTextForSummary( $maxlength = 250 ) {
1143 $truncatedtext = parent::getTextForSummary( $maxlength );
1144
1145 # clean up unfinished links
1146 # XXX: make this optional? wasn't there in autosummary, but required for
1147 # deletion summary.
1148 $truncatedtext = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $truncatedtext );
1149
1150 return $truncatedtext;
1151 }
1152
1153
1154 /**
1155 * Returns a ParserOutput object resulting from parsing the content's text
1156 * using $wgParser.
1157 *
1158 * @since WD.1
1159 *
1160 * @param $content Content the content to render
1161 * @param $title \Title
1162 * @param $revId null
1163 * @param $options null|ParserOptions
1164 * @param $generateHtml bool
1165 *
1166 * @internal param \IContextSource|null $context
1167 * @return ParserOutput representing the HTML form of the text
1168 */
1169 public function getParserOutput( Title $title,
1170 $revId = null,
1171 ParserOptions $options = null, $generateHtml = true
1172 ) {
1173 global $wgParser;
1174
1175 if ( !$options ) {
1176 $options = new ParserOptions();
1177 }
1178
1179 $po = $wgParser->parse( $this->getNativeData(), $title, $options, true, true, $revId );
1180 return $po;
1181 }
1182
1183 protected function getHtml() {
1184 throw new MWException(
1185 "getHtml() not implemented for wikitext. "
1186 . "Use getParserOutput()->getText()."
1187 );
1188 }
1189
1190
1191 }
1192
1193 /**
1194 * @since WD.1
1195 */
1196 class MessageContent extends TextContent {
1197 public function __construct( $msg_key, $params = null, $options = null ) {
1198 # XXX: messages may be wikitext, html or plain text! and maybe even
1199 # something else entirely.
1200 parent::__construct( null, CONTENT_MODEL_WIKITEXT );
1201
1202 $this->mMessageKey = $msg_key;
1203
1204 $this->mParameters = $params;
1205
1206 if ( is_null( $options ) ) {
1207 $options = array();
1208 }
1209 elseif ( is_string( $options ) ) {
1210 $options = array( $options );
1211 }
1212
1213 $this->mOptions = $options;
1214 }
1215
1216 /**
1217 * Returns the message as rendered HTML, using the options supplied to the
1218 * constructor plus "parse".
1219 * @param the message text, parsed
1220 */
1221 public function getHtml( ) {
1222 $opt = array_merge( $this->mOptions, array( 'parse' ) );
1223
1224 return wfMsgExt( $this->mMessageKey, $this->mParameters, $opt );
1225 }
1226
1227
1228 /**
1229 * Returns the message as raw text, using the options supplied to the
1230 * constructor minus "parse" and "parseinline".
1231 *
1232 * @param the message text, unparsed.
1233 */
1234 public function getNativeData( ) {
1235 $opt = array_diff( $this->mOptions, array( 'parse', 'parseinline' ) );
1236
1237 return wfMsgExt( $this->mMessageKey, $this->mParameters, $opt );
1238 }
1239
1240 }
1241
1242 /**
1243 * @since WD.1
1244 */
1245 class JavaScriptContent extends TextContent {
1246 public function __construct( $text ) {
1247 parent::__construct( $text, CONTENT_MODEL_JAVASCRIPT );
1248 }
1249
1250 /**
1251 * Returns a Content object with pre-save transformations applied using
1252 * Parser::preSaveTransform().
1253 *
1254 * @param Title $title
1255 * @param User $user
1256 * @param ParserOptions $popts
1257 * @return Content
1258 */
1259 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
1260 global $wgParser;
1261 // @todo: make pre-save transformation optional for script pages
1262 // See bug #32858
1263
1264 $text = $this->getNativeData();
1265 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
1266
1267 return new JavaScriptContent( $pst );
1268 }
1269
1270
1271 protected function getHtml( ) {
1272 $html = "";
1273 $html .= "<pre class=\"mw-code mw-js\" dir=\"ltr\">\n";
1274 $html .= $this->getHighlightHtml( );
1275 $html .= "\n</pre>\n";
1276
1277 return $html;
1278 }
1279 }
1280
1281 /**
1282 * @since WD.1
1283 */
1284 class CssContent extends TextContent {
1285 public function __construct( $text ) {
1286 parent::__construct( $text, CONTENT_MODEL_CSS );
1287 }
1288
1289 /**
1290 * Returns a Content object with pre-save transformations applied using
1291 * Parser::preSaveTransform().
1292 *
1293 * @param $title Title
1294 * @param $user User
1295 * @param $popts ParserOptions
1296 * @return Content
1297 */
1298 public function preSaveTransform( Title $title, User $user, ParserOptions $popts ) {
1299 global $wgParser;
1300 // @todo: make pre-save transformation optional for script pages
1301
1302 $text = $this->getNativeData();
1303 $pst = $wgParser->preSaveTransform( $text, $title, $user, $popts );
1304
1305 return new CssContent( $pst );
1306 }
1307
1308
1309 protected function getHtml( ) {
1310 $html = "";
1311 $html .= "<pre class=\"mw-code mw-css\" dir=\"ltr\">\n";
1312 $html .= $this->getHighlightHtml( );
1313 $html .= "\n</pre>\n";
1314
1315 return $html;
1316 }
1317 }