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