4 * @addtogroup DifferenceEngine
10 * @addtogroup DifferenceEngine
12 class DifferenceEngine
{
16 var $mOldid, $mNewid, $mTitle;
17 var $mOldtitle, $mNewtitle, $mPagetitle;
18 var $mOldtext, $mNewtext;
19 var $mOldPage, $mNewPage;
20 var $mRcidMarkPatrolled;
21 var $mOldRev, $mNewRev;
22 var $mRevisionsLoaded = false; // Have the revisions been loaded
23 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
28 * @param $titleObj Title object that the diff is associated with
29 * @param $old Integer: old ID we want to show and diff with.
30 * @param $new String: either 'prev' or 'next'.
31 * @param $rcid Integer: ??? FIXME (default 0)
33 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
34 $this->mTitle
= $titleObj;
35 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
37 if ( 'prev' === $new ) {
38 # Show diff between revision $old and the previous one.
39 # Get previous one from DB.
41 $this->mNewid
= intval($old);
43 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
45 } elseif ( 'next' === $new ) {
46 # Show diff between revision $old and the previous one.
47 # Get previous one from DB.
49 $this->mOldid
= intval($old);
50 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
51 if ( false === $this->mNewid
) {
52 # if no result, NewId points to the newest old revision. The only newer
53 # revision is cur, which is "0".
58 $this->mOldid
= intval($old);
59 $this->mNewid
= intval($new);
61 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
64 function showDiffPage( $diffOnly = false ) {
65 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
66 $fname = 'DifferenceEngine::showDiffPage';
67 wfProfileIn( $fname );
69 # If external diffs are enabled both globally and for the user,
70 # we'll use the application/x-external-editor interface to call
71 # an external diff tool like kompare, kdiff3, etc.
72 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
73 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
75 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
76 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
77 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
78 $special=$wgLang->getNsText(NS_SPECIAL
);
83 Script={$wgServer}{$wgScript}
84 Special namespace={$special}
98 $wgOut->setArticleFlag( false );
99 if ( ! $this->loadRevisionData() ) {
100 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
101 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
102 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
103 $wgOut->addWikitext( $mtext );
104 wfProfileOut( $fname );
108 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
110 if ( $this->mNewRev
->isCurrent() ) {
111 $wgOut->setArticleFlag( true );
114 # mOldid is false if the difference engine is called with a "vague" query for
115 # a diff between a version V and its previous version V' AND the version V
116 # is the first version of that article. In that case, V' does not exist.
117 if ( $this->mOldid
=== false ) {
118 $this->showFirstRevision();
119 $this->renderNewRevision(); // should we respect $diffOnly here or not?
120 wfProfileOut( $fname );
124 $wgOut->suppressQuickbar();
126 $oldTitle = $this->mOldPage
->getPrefixedText();
127 $newTitle = $this->mNewPage
->getPrefixedText();
128 if( $oldTitle == $newTitle ) {
129 $wgOut->setPageTitle( $newTitle );
131 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
133 $wgOut->setSubtitle( wfMsg( 'difference' ) );
134 $wgOut->setRobotpolicy( 'noindex,nofollow' );
136 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
137 $wgOut->loginToUse();
139 wfProfileOut( $fname );
143 $sk = $wgUser->getSkin();
145 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
146 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
150 if( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isAllowed( 'patrol' ) ) {
151 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
156 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
157 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
158 if ( $this->mNewRev
->isCurrent() ) {
159 $nextlink = ' ';
161 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
162 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
168 if ($this->mOldRev
->mMinorEdit
== 1) {
169 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
170 wfMsg( 'minoreditletter') ) . ' ';
173 if ($this->mNewRev
->mMinorEdit
== 1) {
174 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
175 wfMsg( 'minoreditletter') ) . ' ';
178 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />" .
179 $sk->revUserTools( $this->mOldRev
) . "<br />" .
180 $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly ) . "<br />" .
182 $newHeader = "<strong>{$this->mNewtitle}</strong><br />" .
183 $sk->revUserTools( $this->mNewRev
) . " $rollback<br />" .
184 $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly ) . "<br />" .
187 $this->showDiff( $oldHeader, $newHeader );
190 $this->renderNewRevision();
192 wfProfileOut( $fname );
196 * Show the new revision of the page.
198 function renderNewRevision() {
200 $fname = 'DifferenceEngine::renderNewRevision';
201 wfProfileIn( $fname );
203 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
205 if( !$this->mNewRev
->isCurrent() ) {
206 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
209 $this->loadNewText();
210 if( is_object( $this->mNewRev
) ) {
211 $wgOut->setRevisionId( $this->mNewRev
->getId() );
214 $wgOut->addWikiTextTidy( $this->mNewtext
);
216 if( !$this->mNewRev
->isCurrent() ) {
217 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
220 wfProfileOut( $fname );
224 * Show the first revision of an article. Uses normal diff headers in
225 * contrast to normal "old revision" display style.
227 function showFirstRevision() {
228 global $wgOut, $wgUser;
230 $fname = 'DifferenceEngine::showFirstRevision';
231 wfProfileIn( $fname );
233 # Get article text from the DB
235 if ( ! $this->loadNewText() ) {
236 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
238 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
239 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
240 $wgOut->addWikitext( $mtext );
241 wfProfileOut( $fname );
244 if ( $this->mNewRev
->isCurrent() ) {
245 $wgOut->setArticleFlag( true );
248 # Check if user is allowed to look at this page. If not, bail out.
250 if ( !( $this->mTitle
->userCanRead() ) ) {
251 $wgOut->loginToUse();
253 wfProfileOut( $fname );
257 # Prepare the header box
259 $sk = $wgUser->getSkin();
261 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
262 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
263 $sk->revUserTools( $this->mNewRev
) . "<br />" .
264 $sk->revComment( $this->mNewRev
) . "<br />" .
265 $nextlink . "</div>\n";
267 $wgOut->addHTML( $header );
269 $wgOut->setSubtitle( wfMsg( 'difference' ) );
270 $wgOut->setRobotpolicy( 'noindex,nofollow' );
272 wfProfileOut( $fname );
276 * Get the diff text, send it to $wgOut
277 * Returns false if the diff could not be generated, otherwise returns true
279 function showDiff( $otitle, $ntitle ) {
281 $diff = $this->getDiff( $otitle, $ntitle );
282 if ( $diff === false ) {
283 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
286 $wgOut->addHTML( $diff );
292 * Get diff table, including header
293 * Note that the interface has changed, it's no longer static.
294 * Returns false on error
296 function getDiff( $otitle, $ntitle ) {
297 $body = $this->getDiffBody();
298 if ( $body === false ) {
301 $multi = $this->getMultiNotice();
302 return $this->addHeader( $body, $otitle, $ntitle, $multi );
307 * Get the diff table body, without header
309 * Returns false on error
311 function getDiffBody() {
313 $fname = 'DifferenceEngine::getDiffBody';
314 wfProfileIn( $fname );
318 if ( $this->mOldid
&& $this->mNewid
) {
320 $key = wfMemcKey( 'diff', 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
321 $difftext = $wgMemc->get( $key );
323 wfIncrStats( 'diff_cache_hit' );
324 $difftext = $this->localiseLineNumbers( $difftext );
325 $difftext .= "\n<!-- diff cache key $key -->\n";
326 wfProfileOut( $fname );
331 if ( !$this->loadText() ) {
332 wfProfileOut( $fname );
336 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
338 // Save to cache for 7 days
339 if ( $key !== false && $difftext !== false ) {
340 wfIncrStats( 'diff_cache_miss' );
341 $wgMemc->set( $key, $difftext, 7*86400 );
343 wfIncrStats( 'diff_uncacheable' );
345 // Replace line numbers with the text in the user's language
346 if ( $difftext !== false ) {
347 $difftext = $this->localiseLineNumbers( $difftext );
349 wfProfileOut( $fname );
354 * Generate a diff, no caching
355 * $otext and $ntext must be already segmented
357 function generateDiffBody( $otext, $ntext ) {
358 global $wgExternalDiffEngine, $wgContLang;
359 $fname = 'DifferenceEngine::generateDiffBody';
361 $otext = str_replace( "\r\n", "\n", $otext );
362 $ntext = str_replace( "\r\n", "\n", $ntext );
364 if ( $wgExternalDiffEngine == 'wikidiff' ) {
365 # For historical reasons, external diff engine expects
366 # input text to be HTML-escaped already
367 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
368 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
369 if( !function_exists( 'wikidiff_do_diff' ) ) {
370 dl('php_wikidiff.so');
372 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
375 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
376 # Better external diff engine, the 2 may some day be dropped
377 # This one does the escaping and segmenting itself
378 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
379 wfProfileIn( "$fname-dl" );
380 @dl
('php_wikidiff2.so');
381 wfProfileOut( "$fname-dl" );
383 if ( function_exists( 'wikidiff2_do_diff' ) ) {
384 wfProfileIn( 'wikidiff2_do_diff' );
385 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
386 wfProfileOut( 'wikidiff2_do_diff' );
390 if ( $wgExternalDiffEngine !== false ) {
392 global $wgTmpDirectory;
393 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
394 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
396 $tempFile1 = fopen( $tempName1, "w" );
398 wfProfileOut( $fname );
401 $tempFile2 = fopen( $tempName2, "w" );
403 wfProfileOut( $fname );
406 fwrite( $tempFile1, $otext );
407 fwrite( $tempFile2, $ntext );
408 fclose( $tempFile1 );
409 fclose( $tempFile2 );
410 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
411 wfProfileIn( "$fname-shellexec" );
412 $difftext = wfShellExec( $cmd );
413 wfProfileOut( "$fname-shellexec" );
414 unlink( $tempName1 );
415 unlink( $tempName2 );
420 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
421 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
422 $diffs = new Diff( $ota, $nta );
423 $formatter = new TableDiffFormatter();
424 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
429 * Replace line numbers with the text in the user's language
431 function localiseLineNumbers( $text ) {
432 return preg_replace_callback( '/<!--LINE (\d+)-->/',
433 array( &$this, 'localiseLineNumbersCb' ), $text );
436 function localiseLineNumbersCb( $matches ) {
438 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
443 * If there are revisions between the ones being compared, return a note saying so.
445 function getMultiNotice() {
446 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
449 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
450 // Comparing two different pages? Count would be meaningless.
454 $oldid = $this->mOldRev
->getId();
455 $newid = $this->mNewRev
->getId();
456 if ( $oldid > $newid ) {
457 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
460 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
464 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
469 * Add the header to a diff body
471 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
473 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
475 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
476 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
481 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
483 return $header . $diff . "</table>";
487 * Use specified text instead of loading from the database
489 function setText( $oldText, $newText ) {
490 $this->mOldtext
= $oldText;
491 $this->mNewtext
= $newText;
492 $this->mTextLoaded
= 2;
496 * Load revision metadata for the specified articles. If newid is 0, then compare
497 * the old article in oldid to the current article; if oldid is 0, then
498 * compare the current article to the immediately previous one (ignoring the
501 * If oldid is false, leave the corresponding revision object set
502 * to false. This is impossible via ordinary user input, and is provided for
505 function loadRevisionData() {
507 if ( $this->mRevisionsLoaded
) {
510 // Whether it succeeds or fails, we don't want to try again
511 $this->mRevisionsLoaded
= true;
514 // Load the new revision object
515 if( $this->mNewid
) {
516 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
518 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
521 if( is_null( $this->mNewRev
) ) {
525 // Set assorted variables
526 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
527 $this->mNewPage
= $this->mNewRev
->getTitle();
528 if( $this->mNewRev
->isCurrent() ) {
529 $newLink = $this->mNewPage
->escapeLocalUrl();
530 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
531 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
532 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undo=' . $this->mNewid
);
534 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
535 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)"
536 . " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
539 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
540 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
541 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undo=' . $this->mNewid
);
542 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
544 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
545 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)"
546 . " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
549 // Load the old revision object
550 $this->mOldRev
= false;
551 if( $this->mOldid
) {
552 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
553 } elseif ( $this->mOldid
=== 0 ) {
554 $rev = $this->mNewRev
->getPrevious();
556 $this->mOldid
= $rev->getId();
557 $this->mOldRev
= $rev;
559 // No previous revision; mark to show as first-version only.
560 $this->mOldid
= false;
561 $this->mOldRev
= false;
563 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
565 if( is_null( $this->mOldRev
) ) {
569 if ( $this->mOldRev
) {
570 $this->mOldPage
= $this->mOldRev
->getTitle();
572 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
573 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
574 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
575 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
576 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
583 * Load the text of the revisions, as well as revision data.
585 function loadText() {
586 if ( $this->mTextLoaded
== 2 ) {
589 // Whether it succeeds or fails, we don't want to try again
590 $this->mTextLoaded
= 2;
593 if ( !$this->loadRevisionData() ) {
596 if ( $this->mOldRev
) {
597 // FIXME: permission tests
598 $this->mOldtext
= $this->mOldRev
->getText();
599 if ( $this->mOldtext
=== false ) {
603 if ( $this->mNewRev
) {
604 $this->mNewtext
= $this->mNewRev
->getText();
605 if ( $this->mNewtext
=== false ) {
613 * Load the text of the new revision, not the old one
615 function loadNewText() {
616 if ( $this->mTextLoaded
>= 1 ) {
619 $this->mTextLoaded
= 1;
621 if ( !$this->loadRevisionData() ) {
624 $this->mNewtext
= $this->mNewRev
->getText();
631 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
633 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
634 // You may copy this code freely under the conditions of the GPL.
637 define('USE_ASSERTS', function_exists('assert'));
642 * @addtogroup DifferenceEngine
650 trigger_error('pure virtual', E_USER_ERROR
);
654 return $this->orig ?
sizeof($this->orig
) : 0;
657 function nclosing() {
658 return $this->closing ?
sizeof($this->closing
) : 0;
665 * @addtogroup DifferenceEngine
667 class _DiffOp_Copy
extends _DiffOp
{
670 function _DiffOp_Copy ($orig, $closing = false) {
671 if (!is_array($closing))
674 $this->closing
= $closing;
678 return new _DiffOp_Copy($this->closing
, $this->orig
);
685 * @addtogroup DifferenceEngine
687 class _DiffOp_Delete
extends _DiffOp
{
688 var $type = 'delete';
690 function _DiffOp_Delete ($lines) {
691 $this->orig
= $lines;
692 $this->closing
= false;
696 return new _DiffOp_Add($this->orig
);
703 * @addtogroup DifferenceEngine
705 class _DiffOp_Add
extends _DiffOp
{
708 function _DiffOp_Add ($lines) {
709 $this->closing
= $lines;
714 return new _DiffOp_Delete($this->closing
);
721 * @addtogroup DifferenceEngine
723 class _DiffOp_Change
extends _DiffOp
{
724 var $type = 'change';
726 function _DiffOp_Change ($orig, $closing) {
728 $this->closing
= $closing;
732 return new _DiffOp_Change($this->closing
, $this->orig
);
738 * Class used internally by Diff to actually compute the diffs.
740 * The algorithm used here is mostly lifted from the perl module
741 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
742 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
744 * More ideas are taken from:
745 * http://www.ics.uci.edu/~eppstein/161/960229.html
747 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
748 * diffutils-2.7, which can be found at:
749 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
751 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
754 * Line length limits for robustness added by Tim Starling, 2005-08-31
756 * @author Geoffrey T. Dairiki, Tim Starling
758 * @addtogroup DifferenceEngine
762 const MAX_XREF_LENGTH
= 10000;
764 function diff ($from_lines, $to_lines) {
765 $fname = '_DiffEngine::diff';
766 wfProfileIn( $fname );
768 $n_from = sizeof($from_lines);
769 $n_to = sizeof($to_lines);
771 $this->xchanged
= $this->ychanged
= array();
772 $this->xv
= $this->yv
= array();
773 $this->xind
= $this->yind
= array();
775 unset($this->in_seq
);
778 // Skip leading common lines.
779 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
780 if ($from_lines[$skip] !== $to_lines[$skip])
782 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
784 // Skip trailing common lines.
785 $xi = $n_from; $yi = $n_to;
786 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
787 if ($from_lines[$xi] !== $to_lines[$yi])
789 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
792 // Ignore lines which do not exist in both files.
793 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
794 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
797 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
798 $line = $to_lines[$yi];
799 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
801 $yhash[$this->_line_hash($line)] = 1;
805 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
806 $line = $from_lines[$xi];
807 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
814 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
816 // Merge edits when possible
817 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
818 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
820 // Compute the edit operations.
823 while ($xi < $n_from ||
$yi < $n_to) {
824 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
825 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
827 // Skip matching "snake".
829 while ( $xi < $n_from && $yi < $n_to
830 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
831 $copy[] = $from_lines[$xi++
];
835 $edits[] = new _DiffOp_Copy($copy);
837 // Find deletes & adds.
839 while ($xi < $n_from && $this->xchanged
[$xi])
840 $delete[] = $from_lines[$xi++
];
843 while ($yi < $n_to && $this->ychanged
[$yi])
844 $add[] = $to_lines[$yi++
];
847 $edits[] = new _DiffOp_Change($delete, $add);
849 $edits[] = new _DiffOp_Delete($delete);
851 $edits[] = new _DiffOp_Add($add);
853 wfProfileOut( $fname );
858 * Returns the whole line if it's small enough, or the MD5 hash otherwise
860 function _line_hash( $line ) {
861 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
869 /* Divide the Largest Common Subsequence (LCS) of the sequences
870 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
873 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
874 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
875 * sub sequences. The first sub-sequence is contained in [X0, X1),
876 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
877 * that (X0, Y0) == (XOFF, YOFF) and
878 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
880 * This function assumes that the first lines of the specified portions
881 * of the two files do not match, and likewise that the last lines do not
882 * match. The caller must trim matching lines from the beginning and end
883 * of the portions it is going to specify.
885 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
886 $fname = '_DiffEngine::_diag';
887 wfProfileIn( $fname );
890 if ($xlim - $xoff > $ylim - $yoff) {
891 // Things seems faster (I'm not sure I understand why)
892 // when the shortest sequence in X.
894 list ($xoff, $xlim, $yoff, $ylim)
895 = array( $yoff, $ylim, $xoff, $xlim);
899 for ($i = $ylim - 1; $i >= $yoff; $i--)
900 $ymatches[$this->xv
[$i]][] = $i;
902 for ($i = $ylim - 1; $i >= $yoff; $i--)
903 $ymatches[$this->yv
[$i]][] = $i;
906 $this->seq
[0]= $yoff - 1;
907 $this->in_seq
= array();
910 $numer = $xlim - $xoff +
$nchunks - 1;
912 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
913 wfProfileIn( "$fname-chunk" );
915 for ($i = 0; $i <= $this->lcs
; $i++
)
916 $ymids[$i][$chunk-1] = $this->seq
[$i];
918 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
919 for ( ; $x < $x1; $x++
) {
920 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
921 if (empty($ymatches[$line]))
923 $matches = $ymatches[$line];
925 while (list ($junk, $y) = each($matches))
926 if (empty($this->in_seq
[$y])) {
927 $k = $this->_lcs_pos($y);
928 USE_ASSERTS
&& assert($k > 0);
929 $ymids[$k] = $ymids[$k-1];
932 while (list ( /* $junk */, $y) = each($matches)) {
933 if ($y > $this->seq
[$k-1]) {
934 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
935 // Optimization: this is a common case:
936 // next match is just replacing previous match.
937 $this->in_seq
[$this->seq
[$k]] = false;
939 $this->in_seq
[$y] = 1;
940 } else if (empty($this->in_seq
[$y])) {
941 $k = $this->_lcs_pos($y);
942 USE_ASSERTS
&& assert($k > 0);
943 $ymids[$k] = $ymids[$k-1];
947 wfProfileOut( "$fname-chunk" );
950 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
951 $ymid = $ymids[$this->lcs
];
952 for ($n = 0; $n < $nchunks - 1; $n++
) {
953 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
955 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
957 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
959 wfProfileOut( $fname );
960 return array($this->lcs
, $seps);
963 function _lcs_pos ($ypos) {
964 $fname = '_DiffEngine::_lcs_pos';
965 wfProfileIn( $fname );
968 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
969 $this->seq
[++
$this->lcs
] = $ypos;
970 $this->in_seq
[$ypos] = 1;
971 wfProfileOut( $fname );
976 while ($beg < $end) {
977 $mid = (int)(($beg +
$end) / 2);
978 if ( $ypos > $this->seq
[$mid] )
984 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
986 $this->in_seq
[$this->seq
[$end]] = false;
987 $this->seq
[$end] = $ypos;
988 $this->in_seq
[$ypos] = 1;
989 wfProfileOut( $fname );
993 /* Find LCS of two sequences.
995 * The results are recorded in the vectors $this->{x,y}changed[], by
996 * storing a 1 in the element for each line that is an insertion
997 * or deletion (ie. is not in the LCS).
999 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1001 * Note that XLIM, YLIM are exclusive bounds.
1002 * All line numbers are origin-0 and discarded lines are not counted.
1004 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1005 $fname = '_DiffEngine::_compareseq';
1006 wfProfileIn( $fname );
1008 // Slide down the bottom initial diagonal.
1009 while ($xoff < $xlim && $yoff < $ylim
1010 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1015 // Slide up the top initial diagonal.
1016 while ($xlim > $xoff && $ylim > $yoff
1017 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1022 if ($xoff == $xlim ||
$yoff == $ylim)
1025 // This is ad hoc but seems to work well.
1026 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1027 //$nchunks = max(2,min(8,(int)$nchunks));
1028 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1030 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1034 // X and Y sequences have no common subsequence:
1035 // mark all changed.
1036 while ($yoff < $ylim)
1037 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1038 while ($xoff < $xlim)
1039 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1041 // Use the partitions to split this problem into subproblems.
1044 while ($pt2 = next($seps)) {
1045 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1049 wfProfileOut( $fname );
1052 /* Adjust inserts/deletes of identical lines to join changes
1053 * as much as possible.
1055 * We do something when a run of changed lines include a
1056 * line at one end and has an excluded, identical line at the other.
1057 * We are free to choose which identical line is included.
1058 * `compareseq' usually chooses the one at the beginning,
1059 * but usually it is cleaner to consider the following identical line
1060 * to be the "change".
1062 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1064 function _shift_boundaries ($lines, &$changed, $other_changed) {
1065 $fname = '_DiffEngine::_shift_boundaries';
1066 wfProfileIn( $fname );
1070 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1071 $len = sizeof($lines);
1072 $other_len = sizeof($other_changed);
1076 * Scan forwards to find beginning of another run of changes.
1077 * Also keep track of the corresponding point in the other file.
1079 * Throughout this code, $i and $j are adjusted together so that
1080 * the first $i elements of $changed and the first $j elements
1081 * of $other_changed both contain the same number of zeros
1082 * (unchanged lines).
1083 * Furthermore, $j is always kept so that $j == $other_len or
1084 * $other_changed[$j] == false.
1086 while ($j < $other_len && $other_changed[$j])
1089 while ($i < $len && ! $changed[$i]) {
1090 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1092 while ($j < $other_len && $other_changed[$j])
1101 // Find the end of this run of changes.
1102 while (++
$i < $len && $changed[$i])
1107 * Record the length of this run of changes, so that
1108 * we can later determine whether the run has grown.
1110 $runlength = $i - $start;
1113 * Move the changed region back, so long as the
1114 * previous unchanged line matches the last changed one.
1115 * This merges with previous changed regions.
1117 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1118 $changed[--$start] = 1;
1119 $changed[--$i] = false;
1120 while ($start > 0 && $changed[$start - 1])
1122 USE_ASSERTS
&& assert('$j > 0');
1123 while ($other_changed[--$j])
1125 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1129 * Set CORRESPONDING to the end of the changed run, at the last
1130 * point where it corresponds to a changed run in the other file.
1131 * CORRESPONDING == LEN means no such point has been found.
1133 $corresponding = $j < $other_len ?
$i : $len;
1136 * Move the changed region forward, so long as the
1137 * first changed line matches the following unchanged one.
1138 * This merges with following changed regions.
1139 * Do this second, so that if there are no merges,
1140 * the changed region is moved forward as far as possible.
1142 while ($i < $len && $lines[$start] == $lines[$i]) {
1143 $changed[$start++
] = false;
1145 while ($i < $len && $changed[$i])
1148 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1150 if ($j < $other_len && $other_changed[$j]) {
1151 $corresponding = $i;
1152 while ($j < $other_len && $other_changed[$j])
1156 } while ($runlength != $i - $start);
1159 * If possible, move the fully-merged run of changes
1160 * back to a corresponding run in the other file.
1162 while ($corresponding < $i) {
1163 $changed[--$start] = 1;
1165 USE_ASSERTS
&& assert('$j > 0');
1166 while ($other_changed[--$j])
1168 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1171 wfProfileOut( $fname );
1176 * Class representing a 'diff' between two sequences of strings.
1179 * @addtogroup DifferenceEngine
1187 * Computes diff between sequences of strings.
1189 * @param $from_lines array An array of strings.
1190 * (Typically these are lines from a file.)
1191 * @param $to_lines array An array of strings.
1193 function Diff($from_lines, $to_lines) {
1194 $eng = new _DiffEngine
;
1195 $this->edits
= $eng->diff($from_lines, $to_lines);
1196 //$this->_check($from_lines, $to_lines);
1200 * Compute reversed Diff.
1204 * $diff = new Diff($lines1, $lines2);
1205 * $rev = $diff->reverse();
1206 * @return object A Diff object representing the inverse of the
1209 function reverse () {
1211 $rev->edits
= array();
1212 foreach ($this->edits
as $edit) {
1213 $rev->edits
[] = $edit->reverse();
1219 * Check for empty diff.
1221 * @return bool True iff two sequences were identical.
1223 function isEmpty () {
1224 foreach ($this->edits
as $edit) {
1225 if ($edit->type
!= 'copy')
1232 * Compute the length of the Longest Common Subsequence (LCS).
1234 * This is mostly for diagnostic purposed.
1236 * @return int The length of the LCS.
1240 foreach ($this->edits
as $edit) {
1241 if ($edit->type
== 'copy')
1242 $lcs +
= sizeof($edit->orig
);
1248 * Get the original set of lines.
1250 * This reconstructs the $from_lines parameter passed to the
1253 * @return array The original sequence of strings.
1258 foreach ($this->edits
as $edit) {
1260 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1266 * Get the closing set of lines.
1268 * This reconstructs the $to_lines parameter passed to the
1271 * @return array The sequence of strings.
1273 function closing() {
1276 foreach ($this->edits
as $edit) {
1278 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1284 * Check a Diff for validity.
1286 * This is here only for debugging purposes.
1288 function _check ($from_lines, $to_lines) {
1289 $fname = 'Diff::_check';
1290 wfProfileIn( $fname );
1291 if (serialize($from_lines) != serialize($this->orig()))
1292 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1293 if (serialize($to_lines) != serialize($this->closing()))
1294 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1296 $rev = $this->reverse();
1297 if (serialize($to_lines) != serialize($rev->orig()))
1298 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1299 if (serialize($from_lines) != serialize($rev->closing()))
1300 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1304 foreach ($this->edits
as $edit) {
1305 if ( $prevtype == $edit->type
)
1306 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1307 $prevtype = $edit->type
;
1310 $lcs = $this->lcs();
1311 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1312 wfProfileOut( $fname );
1320 * @addtogroup DifferenceEngine
1322 class MappedDiff
extends Diff
1327 * Computes diff between sequences of strings.
1329 * This can be used to compute things like
1330 * case-insensitve diffs, or diffs which ignore
1331 * changes in white-space.
1333 * @param $from_lines array An array of strings.
1334 * (Typically these are lines from a file.)
1336 * @param $to_lines array An array of strings.
1338 * @param $mapped_from_lines array This array should
1339 * have the same size number of elements as $from_lines.
1340 * The elements in $mapped_from_lines and
1341 * $mapped_to_lines are what is actually compared
1342 * when computing the diff.
1344 * @param $mapped_to_lines array This array should
1345 * have the same number of elements as $to_lines.
1347 function MappedDiff($from_lines, $to_lines,
1348 $mapped_from_lines, $mapped_to_lines) {
1349 $fname = 'MappedDiff::MappedDiff';
1350 wfProfileIn( $fname );
1352 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1353 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1355 $this->Diff($mapped_from_lines, $mapped_to_lines);
1358 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1359 $orig = &$this->edits
[$i]->orig
;
1360 if (is_array($orig)) {
1361 $orig = array_slice($from_lines, $xi, sizeof($orig));
1362 $xi +
= sizeof($orig);
1365 $closing = &$this->edits
[$i]->closing
;
1366 if (is_array($closing)) {
1367 $closing = array_slice($to_lines, $yi, sizeof($closing));
1368 $yi +
= sizeof($closing);
1371 wfProfileOut( $fname );
1376 * A class to format Diffs
1378 * This class formats the diff in classic diff format.
1379 * It is intended that this class be customized via inheritance,
1380 * to obtain fancier outputs.
1383 * @addtogroup DifferenceEngine
1388 * Number of leading context "lines" to preserve.
1390 * This should be left at zero for this class, but subclasses
1391 * may want to set this to other values.
1393 var $leading_context_lines = 0;
1396 * Number of trailing context "lines" to preserve.
1398 * This should be left at zero for this class, but subclasses
1399 * may want to set this to other values.
1401 var $trailing_context_lines = 0;
1406 * @param $diff object A Diff object.
1407 * @return string The formatted output.
1409 function format($diff) {
1410 $fname = 'DiffFormatter::format';
1411 wfProfileIn( $fname );
1417 $nlead = $this->leading_context_lines
;
1418 $ntrail = $this->trailing_context_lines
;
1420 $this->_start_diff();
1422 foreach ($diff->edits
as $edit) {
1423 if ($edit->type
== 'copy') {
1424 if (is_array($block)) {
1425 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1430 $context = array_slice($edit->orig
, 0, $ntrail);
1431 $block[] = new _DiffOp_Copy($context);
1433 $this->_block($x0, $ntrail +
$xi - $x0,
1434 $y0, $ntrail +
$yi - $y0,
1439 $context = $edit->orig
;
1442 if (! is_array($block)) {
1443 $context = array_slice($context, sizeof($context) - $nlead);
1444 $x0 = $xi - sizeof($context);
1445 $y0 = $yi - sizeof($context);
1448 $block[] = new _DiffOp_Copy($context);
1454 $xi +
= sizeof($edit->orig
);
1456 $yi +
= sizeof($edit->closing
);
1459 if (is_array($block))
1460 $this->_block($x0, $xi - $x0,
1464 $end = $this->_end_diff();
1465 wfProfileOut( $fname );
1469 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1470 $fname = 'DiffFormatter::_block';
1471 wfProfileIn( $fname );
1472 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1473 foreach ($edits as $edit) {
1474 if ($edit->type
== 'copy')
1475 $this->_context($edit->orig
);
1476 elseif ($edit->type
== 'add')
1477 $this->_added($edit->closing
);
1478 elseif ($edit->type
== 'delete')
1479 $this->_deleted($edit->orig
);
1480 elseif ($edit->type
== 'change')
1481 $this->_changed($edit->orig
, $edit->closing
);
1483 trigger_error('Unknown edit type', E_USER_ERROR
);
1485 $this->_end_block();
1486 wfProfileOut( $fname );
1489 function _start_diff() {
1493 function _end_diff() {
1494 $val = ob_get_contents();
1499 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1501 $xbeg .= "," . ($xbeg +
$xlen - 1);
1503 $ybeg .= "," . ($ybeg +
$ylen - 1);
1505 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1508 function _start_block($header) {
1512 function _end_block() {
1515 function _lines($lines, $prefix = ' ') {
1516 foreach ($lines as $line)
1517 echo "$prefix $line\n";
1520 function _context($lines) {
1521 $this->_lines($lines);
1524 function _added($lines) {
1525 $this->_lines($lines, '>');
1527 function _deleted($lines) {
1528 $this->_lines($lines, '<');
1531 function _changed($orig, $closing) {
1532 $this->_deleted($orig);
1534 $this->_added($closing);
1540 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1544 define('NBSP', ' '); // iso-8859-x non-breaking space.
1549 * @addtogroup DifferenceEngine
1551 class _HWLDF_WordAccumulator
{
1552 function _HWLDF_WordAccumulator () {
1553 $this->_lines
= array();
1559 function _flushGroup ($new_tag) {
1560 if ($this->_group
!== '') {
1561 if ($this->_tag
== 'ins')
1562 $this->_line
.= '<ins class="diffchange">' .
1563 htmlspecialchars ( $this->_group
) . '</ins>';
1564 elseif ($this->_tag
== 'del')
1565 $this->_line
.= '<del class="diffchange">' .
1566 htmlspecialchars ( $this->_group
) . '</del>';
1568 $this->_line
.= htmlspecialchars ( $this->_group
);
1571 $this->_tag
= $new_tag;
1574 function _flushLine ($new_tag) {
1575 $this->_flushGroup($new_tag);
1576 if ($this->_line
!= '')
1577 array_push ( $this->_lines
, $this->_line
);
1579 # make empty lines visible by inserting an NBSP
1580 array_push ( $this->_lines
, NBSP
);
1584 function addWords ($words, $tag = '') {
1585 if ($tag != $this->_tag
)
1586 $this->_flushGroup($tag);
1588 foreach ($words as $word) {
1589 // new-line should only come as first char of word.
1592 if ($word[0] == "\n") {
1593 $this->_flushLine($tag);
1594 $word = substr($word, 1);
1596 assert(!strstr($word, "\n"));
1597 $this->_group
.= $word;
1601 function getLines() {
1602 $this->_flushLine('~done');
1603 return $this->_lines
;
1610 * @addtogroup DifferenceEngine
1612 class WordLevelDiff
extends MappedDiff
1614 const MAX_LINE_LENGTH
= 10000;
1616 function WordLevelDiff ($orig_lines, $closing_lines) {
1617 $fname = 'WordLevelDiff::WordLevelDiff';
1618 wfProfileIn( $fname );
1620 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1621 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1623 $this->MappedDiff($orig_words, $closing_words,
1624 $orig_stripped, $closing_stripped);
1625 wfProfileOut( $fname );
1628 function _split($lines) {
1629 $fname = 'WordLevelDiff::_split';
1630 wfProfileIn( $fname );
1633 $stripped = array();
1635 foreach ( $lines as $line ) {
1636 # If the line is too long, just pretend the entire line is one big word
1637 # This prevents resource exhaustion problems
1644 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1646 $stripped[] = $line;
1649 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1652 $words = array_merge( $words, $m[0] );
1653 $stripped = array_merge( $stripped, $m[1] );
1657 wfProfileOut( $fname );
1658 return array($words, $stripped);
1662 $fname = 'WordLevelDiff::orig';
1663 wfProfileIn( $fname );
1664 $orig = new _HWLDF_WordAccumulator
;
1666 foreach ($this->edits
as $edit) {
1667 if ($edit->type
== 'copy')
1668 $orig->addWords($edit->orig
);
1669 elseif ($edit->orig
)
1670 $orig->addWords($edit->orig
, 'del');
1672 $lines = $orig->getLines();
1673 wfProfileOut( $fname );
1677 function closing () {
1678 $fname = 'WordLevelDiff::closing';
1679 wfProfileIn( $fname );
1680 $closing = new _HWLDF_WordAccumulator
;
1682 foreach ($this->edits
as $edit) {
1683 if ($edit->type
== 'copy')
1684 $closing->addWords($edit->closing
);
1685 elseif ($edit->closing
)
1686 $closing->addWords($edit->closing
, 'ins');
1688 $lines = $closing->getLines();
1689 wfProfileOut( $fname );
1695 * Wikipedia Table style diff formatter.
1698 * @addtogroup DifferenceEngine
1700 class TableDiffFormatter
extends DiffFormatter
1702 function TableDiffFormatter() {
1703 $this->leading_context_lines
= 2;
1704 $this->trailing_context_lines
= 2;
1707 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1708 $r = '<tr><td colspan="2" align="left"><strong><!--LINE '.$xbeg."--></strong></td>\n" .
1709 '<td colspan="2" align="left"><strong><!--LINE '.$ybeg."--></strong></td></tr>\n";
1713 function _start_block( $header ) {
1717 function _end_block() {
1720 function _lines( $lines, $prefix=' ', $color='white' ) {
1723 # HTML-escape parameter before calling this
1724 function addedLine( $line ) {
1725 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1728 # HTML-escape parameter before calling this
1729 function deletedLine( $line ) {
1730 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1733 # HTML-escape parameter before calling this
1734 function contextLine( $line ) {
1735 return "<td> </td><td class='diff-context'>{$line}</td>";
1738 function emptyLine() {
1739 return '<td colspan="2"> </td>';
1742 function _added( $lines ) {
1743 foreach ($lines as $line) {
1744 echo '<tr>' . $this->emptyLine() .
1745 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1749 function _deleted($lines) {
1750 foreach ($lines as $line) {
1751 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1752 $this->emptyLine() . "</tr>\n";
1756 function _context( $lines ) {
1757 foreach ($lines as $line) {
1759 $this->contextLine( htmlspecialchars ( $line ) ) .
1760 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1764 function _changed( $orig, $closing ) {
1765 $fname = 'TableDiffFormatter::_changed';
1766 wfProfileIn( $fname );
1768 $diff = new WordLevelDiff( $orig, $closing );
1769 $del = $diff->orig();
1770 $add = $diff->closing();
1772 # Notice that WordLevelDiff returns HTML-escaped output.
1773 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1775 while ( $line = array_shift( $del ) ) {
1776 $aline = array_shift( $add );
1777 echo '<tr>' . $this->deletedLine( $line ) .
1778 $this->addedLine( $aline ) . "</tr>\n";
1780 foreach ($add as $line) { # If any leftovers
1781 echo '<tr>' . $this->emptyLine() .
1782 $this->addedLine( $line ) . "</tr>\n";
1784 wfProfileOut( $fname );