5 * @subpackage DifferenceEngine
8 require_once( 'Revision.php' );
14 class DifferenceEngine
{
15 /* private */ var $mOldid, $mNewid;
16 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
17 /* private */ var $mOldtext, $mNewtext;
18 /* private */ var $mOldUser, $mNewUser;
19 /* private */ var $mOldComment, $mNewComment;
20 /* private */ var $mOldPage, $mNewPage;
21 /* private */ var $mRcidMarkPatrolled;
23 function DifferenceEngine( $old, $new, $rcid = 0 )
26 if ( 'prev' == $new ) {
27 # Show diff between revision $old and the previous one.
28 # Get previous one from DB.
30 $this->mNewid
= intval($old);
32 $this->mOldid
= $wgTitle->getPreviousRevisionID( $this->mNewid
);
34 } elseif ( 'next' == $new ) {
36 # Show diff between revision $old and the previous one.
37 # Get previous one from DB.
39 $this->mOldid
= intval($old);
40 $this->mNewid
= $wgTitle->getNextRevisionID( $this->mOldid
);
41 if ( false === $this->mNewid
) {
42 # if no result, NewId points to the newest old revision. The only newer
43 # revision is cur, which is "0".
49 $this->mOldid
= intval($old);
50 $this->mNewid
= intval($new);
52 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
55 function showDiffPage()
57 global $wgUser, $wgTitle, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
58 $fname = 'DifferenceEngine::showDiffPage';
59 wfProfileIn( $fname );
61 # mOldid is false if the difference engine is called with a "vague" query for
62 # a diff between a version V and its previous version V' AND the version V
63 # is the first version of that article. In that case, V' does not exist.
64 if ( $this->mOldid
=== false ) {
65 $this->showFirstRevision();
66 wfProfileOut( $fname );
70 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
72 $mtext = wfMsg( 'missingarticle', $t );
74 $wgOut->setArticleFlag( false );
75 if ( ! $this->loadText() ) {
76 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
77 $wgOut->addHTML( $mtext );
78 wfProfileOut( $fname );
81 $wgOut->suppressQuickbar();
83 $oldTitle = $this->mOldPage
->getPrefixedText();
84 $newTitle = $this->mNewPage
->getPrefixedText();
85 if( $oldTitle == $newTitle ) {
86 $wgOut->setPageTitle( $newTitle );
88 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
90 $wgOut->setSubtitle( wfMsg( 'difference' ) );
91 $wgOut->setRobotpolicy( 'noindex,follow' );
93 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
96 wfProfileOut( $fname );
100 $sk = $wgUser->getSkin();
101 $talk = $wgContLang->getNsText( NS_TALK
);
102 $contribs = wfMsg( 'contribslink' );
104 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
105 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
107 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
108 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
109 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
110 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
111 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
112 'target=' . urlencode($this->mOldUser
) );
113 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
114 'target=' . urlencode($this->mNewUser
) );
115 if ( !$this->mNewid
&& $wgUser->isAllowed('rollback') ) {
116 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
117 'action=rollback&from=' . urlencode($this->mNewUser
) ) . ']</strong>';
121 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
122 ( $wgUser->isAllowed('rollback') ||
!$wgOnlySysopsCanPatrol ) )
124 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
125 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
130 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
131 if ( $this->mNewid
== 0 ) {
134 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
137 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
138 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
139 '<br />' . $prevlink;
140 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
141 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
142 '<br />' . $nextlink . $patrol;
144 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
145 $oldHeader, $newHeader );
146 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
147 $wgOut->addWikiText( $this->mNewtext
);
149 wfProfileOut( $fname );
152 # Show the first revision of an article. Uses normal diff headers in contrast to normal
153 # "old revision" display style.
155 function showFirstRevision()
157 global $wgOut, $wgTitle, $wgUser, $wgLang;
159 $fname = 'DifferenceEngine::showFirstRevision';
160 wfProfileIn( $fname );
163 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
165 # Get article text from the DB
167 if ( ! $this->loadText() ) {
168 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
170 $mtext = wfMsg( 'missingarticle', $t );
171 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
172 $wgOut->addHTML( $mtext );
173 wfProfileOut( $fname );
177 # Check if user is allowed to look at this page. If not, bail out.
179 if ( !( $this->mOldPage
->userCanRead() ) ) {
180 $wgOut->loginToUse();
182 wfProfileOut( $fname );
186 # Prepare the header box
188 $sk = $wgUser->getSkin();
190 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
191 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
192 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
193 'target=' . urlencode($this->mOldUser
) );
194 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
195 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
196 "($uTLink | $contribs)<br />" . $this->mOldComment
.
197 '<br />' . $nextlink. "</div>\n";
199 $wgOut->addHTML( $header );
201 $wgOut->setSubtitle( wfMsg( 'difference' ) );
202 $wgOut->setRobotpolicy( 'noindex,follow' );
205 # Show current revision
207 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
208 $wgOut->addWikiText( $this->mNewtext
);
210 wfProfileOut( $fname );
213 function showDiff( $otext, $ntext, $otitle, $ntitle )
216 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
219 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
220 global $wgUseExternalDiffEngine, $wgContLang;
222 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
224 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
225 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
228 $otext = $wgContLang->segmentForDiff($otext);
229 $ntext = $wgContLang->segmentForDiff($ntext);
231 if ( $wgUseExternalDiffEngine ) {
232 # For historical reasons, external diff engine expects
233 # input text to be HTML-escaped already
234 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
235 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
236 if( !function_exists( 'wikidiff_do_diff' ) ) {
237 dl('php_wikidiff.so');
239 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
241 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
242 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
243 $diffs =& new Diff( $ota, $nta );
244 $formatter =& new TableDiffFormatter();
245 $difftext = $formatter->format( $diffs );
247 $difftext = $wgContLang->unsegmentForDiff($difftext);
248 $out .= $difftext."</table>\n";
252 # Load the text of the articles to compare. If newid is 0, then compare
253 # the old article in oldid to the current article; if oldid is 0, then
254 # compare the current article to the immediately previous one (ignoring
255 # the value of newid).
259 global $wgTitle, $wgOut, $wgLang;
260 $fname = 'DifferenceEngine::loadText';
262 $dbr =& wfGetDB( DB_SLAVE
);
263 if( $this->mNewid
) {
264 $this->newRev
=& Revision
::newFromId( $this->mNewid
);
266 $this->newRev
=& Revision
::newFromTitle( $wgTitle );
269 if( $this->newRev
->isCurrent() ) {
270 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
271 $this->mNewPage
= $wgTitle;
272 $newLink = $this->mNewPage
->escapeLocalUrl();
273 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
275 $this->mNewPage
= $this->newRev
->getTitle();
276 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
277 $t = $wgLang->timeanddate( $this->newRev
->getTimestamp(), true );
278 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
279 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
282 if( $this->mOldid
) {
283 $this->oldRev
=& Revision
::newFromId( $this->mOldid
);
285 $this->oldRev
=& $this->newRev
->getPrevious();
288 $this->mOldPage
= $this->oldRev
->getTitle();
290 $t = $wgLang->timeanddate( $this->oldRev
->getTimestamp(), true );
291 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
292 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
294 $this->mNewUser
= $this->newRev
->getUserText();
295 $this->mNewComment
= $this->newRev
->getComment();
296 $this->mNewtext
= $this->newRev
->getText();
298 $this->mOldUser
= $this->oldRev
->getUserText();
299 $this->mOldComment
= $this->oldRev
->getComment();
300 $this->mOldtext
= $this->oldRev
->getText();
306 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
308 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
309 // You may copy this code freely under the conditions of the GPL.
312 define('USE_ASSERTS', function_exists('assert'));
324 trigger_error('pure virtual', E_USER_ERROR
);
328 return $this->orig ?
sizeof($this->orig
) : 0;
331 function nclosing() {
332 return $this->closing ?
sizeof($this->closing
) : 0;
340 class _DiffOp_Copy
extends _DiffOp
{
343 function _DiffOp_Copy ($orig, $closing = false) {
344 if (!is_array($closing))
347 $this->closing
= $closing;
351 return new _DiffOp_Copy($this->closing
, $this->orig
);
359 class _DiffOp_Delete
extends _DiffOp
{
360 var $type = 'delete';
362 function _DiffOp_Delete ($lines) {
363 $this->orig
= $lines;
364 $this->closing
= false;
368 return new _DiffOp_Add($this->orig
);
376 class _DiffOp_Add
extends _DiffOp
{
379 function _DiffOp_Add ($lines) {
380 $this->closing
= $lines;
385 return new _DiffOp_Delete($this->closing
);
393 class _DiffOp_Change
extends _DiffOp
{
394 var $type = 'change';
396 function _DiffOp_Change ($orig, $closing) {
398 $this->closing
= $closing;
402 return new _DiffOp_Change($this->closing
, $this->orig
);
408 * Class used internally by Diff to actually compute the diffs.
410 * The algorithm used here is mostly lifted from the perl module
411 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
412 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
414 * More ideas are taken from:
415 * http://www.ics.uci.edu/~eppstein/161/960229.html
417 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
418 * diffutils-2.7, which can be found at:
419 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
421 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
424 * @author Geoffrey T. Dairiki
429 function diff ($from_lines, $to_lines) {
430 $fname = '_DiffEngine::diff';
431 wfProfileIn( $fname );
433 $n_from = sizeof($from_lines);
434 $n_to = sizeof($to_lines);
436 $this->xchanged
= $this->ychanged
= array();
437 $this->xv
= $this->yv
= array();
438 $this->xind
= $this->yind
= array();
440 unset($this->in_seq
);
443 // Skip leading common lines.
444 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
445 if ($from_lines[$skip] != $to_lines[$skip])
447 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
449 // Skip trailing common lines.
450 $xi = $n_from; $yi = $n_to;
451 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
452 if ($from_lines[$xi] != $to_lines[$yi])
454 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
457 // Ignore lines which do not exist in both files.
458 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
459 $xhash[$from_lines[$xi]] = 1;
460 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
461 $line = $to_lines[$yi];
462 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
468 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
469 $line = $from_lines[$xi];
470 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
477 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
479 // Merge edits when possible
480 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
481 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
483 // Compute the edit operations.
486 while ($xi < $n_from ||
$yi < $n_to) {
487 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
488 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
490 // Skip matching "snake".
492 while ( $xi < $n_from && $yi < $n_to
493 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
494 $copy[] = $from_lines[$xi++
];
498 $edits[] = new _DiffOp_Copy($copy);
500 // Find deletes & adds.
502 while ($xi < $n_from && $this->xchanged
[$xi])
503 $delete[] = $from_lines[$xi++
];
506 while ($yi < $n_to && $this->ychanged
[$yi])
507 $add[] = $to_lines[$yi++
];
510 $edits[] = new _DiffOp_Change($delete, $add);
512 $edits[] = new _DiffOp_Delete($delete);
514 $edits[] = new _DiffOp_Add($add);
516 wfProfileOut( $fname );
521 /* Divide the Largest Common Subsequence (LCS) of the sequences
522 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
525 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
526 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
527 * sub sequences. The first sub-sequence is contained in [X0, X1),
528 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
529 * that (X0, Y0) == (XOFF, YOFF) and
530 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
532 * This function assumes that the first lines of the specified portions
533 * of the two files do not match, and likewise that the last lines do not
534 * match. The caller must trim matching lines from the beginning and end
535 * of the portions it is going to specify.
537 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
538 $fname = '_DiffEngine::_diag';
539 wfProfileIn( $fname );
542 if ($xlim - $xoff > $ylim - $yoff) {
543 // Things seems faster (I'm not sure I understand why)
544 // when the shortest sequence in X.
546 list ($xoff, $xlim, $yoff, $ylim)
547 = array( $yoff, $ylim, $xoff, $xlim);
551 for ($i = $ylim - 1; $i >= $yoff; $i--)
552 $ymatches[$this->xv
[$i]][] = $i;
554 for ($i = $ylim - 1; $i >= $yoff; $i--)
555 $ymatches[$this->yv
[$i]][] = $i;
558 $this->seq
[0]= $yoff - 1;
559 $this->in_seq
= array();
562 $numer = $xlim - $xoff +
$nchunks - 1;
564 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
565 wfProfileIn( "$fname-chunk" );
567 for ($i = 0; $i <= $this->lcs
; $i++
)
568 $ymids[$i][$chunk-1] = $this->seq
[$i];
570 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
571 for ( ; $x < $x1; $x++
) {
572 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
573 if (empty($ymatches[$line]))
575 $matches = $ymatches[$line];
577 while (list ($junk, $y) = each($matches))
578 if (empty($this->in_seq
[$y])) {
579 $k = $this->_lcs_pos($y);
580 USE_ASSERTS
&& assert($k > 0);
581 $ymids[$k] = $ymids[$k-1];
584 while (list ($junk, $y) = each($matches)) {
585 if ($y > $this->seq
[$k-1]) {
586 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
587 // Optimization: this is a common case:
588 // next match is just replacing previous match.
589 $this->in_seq
[$this->seq
[$k]] = false;
591 $this->in_seq
[$y] = 1;
592 } else if (empty($this->in_seq
[$y])) {
593 $k = $this->_lcs_pos($y);
594 USE_ASSERTS
&& assert($k > 0);
595 $ymids[$k] = $ymids[$k-1];
599 wfProfileOut( "$fname-chunk" );
602 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
603 $ymid = $ymids[$this->lcs
];
604 for ($n = 0; $n < $nchunks - 1; $n++
) {
605 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
607 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
609 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
611 wfProfileOut( $fname );
612 return array($this->lcs
, $seps);
615 function _lcs_pos ($ypos) {
616 $fname = '_DiffEngine::_lcs_pos';
617 wfProfileIn( $fname );
620 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
621 $this->seq
[++
$this->lcs
] = $ypos;
622 $this->in_seq
[$ypos] = 1;
623 wfProfileOut( $fname );
628 while ($beg < $end) {
629 $mid = (int)(($beg +
$end) / 2);
630 if ( $ypos > $this->seq
[$mid] )
636 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
638 $this->in_seq
[$this->seq
[$end]] = false;
639 $this->seq
[$end] = $ypos;
640 $this->in_seq
[$ypos] = 1;
641 wfProfileOut( $fname );
645 /* Find LCS of two sequences.
647 * The results are recorded in the vectors $this->{x,y}changed[], by
648 * storing a 1 in the element for each line that is an insertion
649 * or deletion (ie. is not in the LCS).
651 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
653 * Note that XLIM, YLIM are exclusive bounds.
654 * All line numbers are origin-0 and discarded lines are not counted.
656 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
657 $fname = '_DiffEngine::_compareseq';
658 wfProfileIn( $fname );
660 // Slide down the bottom initial diagonal.
661 while ($xoff < $xlim && $yoff < $ylim
662 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
667 // Slide up the top initial diagonal.
668 while ($xlim > $xoff && $ylim > $yoff
669 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
674 if ($xoff == $xlim ||
$yoff == $ylim)
677 // This is ad hoc but seems to work well.
678 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
679 //$nchunks = max(2,min(8,(int)$nchunks));
680 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
682 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
686 // X and Y sequences have no common subsequence:
688 while ($yoff < $ylim)
689 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
690 while ($xoff < $xlim)
691 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
693 // Use the partitions to split this problem into subproblems.
696 while ($pt2 = next($seps)) {
697 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
701 wfProfileOut( $fname );
704 /* Adjust inserts/deletes of identical lines to join changes
705 * as much as possible.
707 * We do something when a run of changed lines include a
708 * line at one end and has an excluded, identical line at the other.
709 * We are free to choose which identical line is included.
710 * `compareseq' usually chooses the one at the beginning,
711 * but usually it is cleaner to consider the following identical line
712 * to be the "change".
714 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
716 function _shift_boundaries ($lines, &$changed, $other_changed) {
717 $fname = '_DiffEngine::_shift_boundaries';
718 wfProfileIn( $fname );
722 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
723 $len = sizeof($lines);
724 $other_len = sizeof($other_changed);
728 * Scan forwards to find beginning of another run of changes.
729 * Also keep track of the corresponding point in the other file.
731 * Throughout this code, $i and $j are adjusted together so that
732 * the first $i elements of $changed and the first $j elements
733 * of $other_changed both contain the same number of zeros
735 * Furthermore, $j is always kept so that $j == $other_len or
736 * $other_changed[$j] == false.
738 while ($j < $other_len && $other_changed[$j])
741 while ($i < $len && ! $changed[$i]) {
742 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
744 while ($j < $other_len && $other_changed[$j])
753 // Find the end of this run of changes.
754 while (++
$i < $len && $changed[$i])
759 * Record the length of this run of changes, so that
760 * we can later determine whether the run has grown.
762 $runlength = $i - $start;
765 * Move the changed region back, so long as the
766 * previous unchanged line matches the last changed one.
767 * This merges with previous changed regions.
769 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
770 $changed[--$start] = 1;
771 $changed[--$i] = false;
772 while ($start > 0 && $changed[$start - 1])
774 USE_ASSERTS
&& assert('$j > 0');
775 while ($other_changed[--$j])
777 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
781 * Set CORRESPONDING to the end of the changed run, at the last
782 * point where it corresponds to a changed run in the other file.
783 * CORRESPONDING == LEN means no such point has been found.
785 $corresponding = $j < $other_len ?
$i : $len;
788 * Move the changed region forward, so long as the
789 * first changed line matches the following unchanged one.
790 * This merges with following changed regions.
791 * Do this second, so that if there are no merges,
792 * the changed region is moved forward as far as possible.
794 while ($i < $len && $lines[$start] == $lines[$i]) {
795 $changed[$start++
] = false;
797 while ($i < $len && $changed[$i])
800 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
802 if ($j < $other_len && $other_changed[$j]) {
804 while ($j < $other_len && $other_changed[$j])
808 } while ($runlength != $i - $start);
811 * If possible, move the fully-merged run of changes
812 * back to a corresponding run in the other file.
814 while ($corresponding < $i) {
815 $changed[--$start] = 1;
817 USE_ASSERTS
&& assert('$j > 0');
818 while ($other_changed[--$j])
820 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
823 wfProfileOut( $fname );
828 * Class representing a 'diff' between two sequences of strings.
838 * Computes diff between sequences of strings.
840 * @param $from_lines array An array of strings.
841 * (Typically these are lines from a file.)
842 * @param $to_lines array An array of strings.
844 function Diff($from_lines, $to_lines) {
845 $eng = new _DiffEngine
;
846 $this->edits
= $eng->diff($from_lines, $to_lines);
847 //$this->_check($from_lines, $to_lines);
851 * Compute reversed Diff.
855 * $diff = new Diff($lines1, $lines2);
856 * $rev = $diff->reverse();
857 * @return object A Diff object representing the inverse of the
860 function reverse () {
862 $rev->edits
= array();
863 foreach ($this->edits
as $edit) {
864 $rev->edits
[] = $edit->reverse();
870 * Check for empty diff.
872 * @return bool True iff two sequences were identical.
874 function isEmpty () {
875 foreach ($this->edits
as $edit) {
876 if ($edit->type
!= 'copy')
883 * Compute the length of the Longest Common Subsequence (LCS).
885 * This is mostly for diagnostic purposed.
887 * @return int The length of the LCS.
891 foreach ($this->edits
as $edit) {
892 if ($edit->type
== 'copy')
893 $lcs +
= sizeof($edit->orig
);
899 * Get the original set of lines.
901 * This reconstructs the $from_lines parameter passed to the
904 * @return array The original sequence of strings.
909 foreach ($this->edits
as $edit) {
911 array_splice($lines, sizeof($lines), 0, $edit->orig
);
917 * Get the closing set of lines.
919 * This reconstructs the $to_lines parameter passed to the
922 * @return array The sequence of strings.
927 foreach ($this->edits
as $edit) {
929 array_splice($lines, sizeof($lines), 0, $edit->closing
);
935 * Check a Diff for validity.
937 * This is here only for debugging purposes.
939 function _check ($from_lines, $to_lines) {
940 $fname = 'Diff::_check';
941 wfProfileIn( $fname );
942 if (serialize($from_lines) != serialize($this->orig()))
943 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
944 if (serialize($to_lines) != serialize($this->closing()))
945 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
947 $rev = $this->reverse();
948 if (serialize($to_lines) != serialize($rev->orig()))
949 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
950 if (serialize($from_lines) != serialize($rev->closing()))
951 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
955 foreach ($this->edits
as $edit) {
956 if ( $prevtype == $edit->type
)
957 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
958 $prevtype = $edit->type
;
962 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
963 wfProfileOut( $fname );
972 class MappedDiff
extends Diff
977 * Computes diff between sequences of strings.
979 * This can be used to compute things like
980 * case-insensitve diffs, or diffs which ignore
981 * changes in white-space.
983 * @param $from_lines array An array of strings.
984 * (Typically these are lines from a file.)
986 * @param $to_lines array An array of strings.
988 * @param $mapped_from_lines array This array should
989 * have the same size number of elements as $from_lines.
990 * The elements in $mapped_from_lines and
991 * $mapped_to_lines are what is actually compared
992 * when computing the diff.
994 * @param $mapped_to_lines array This array should
995 * have the same number of elements as $to_lines.
997 function MappedDiff($from_lines, $to_lines,
998 $mapped_from_lines, $mapped_to_lines) {
999 $fname = 'MappedDiff::MappedDiff';
1000 wfProfileIn( $fname );
1002 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1003 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1005 $this->Diff($mapped_from_lines, $mapped_to_lines);
1008 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1009 $orig = &$this->edits
[$i]->orig
;
1010 if (is_array($orig)) {
1011 $orig = array_slice($from_lines, $xi, sizeof($orig));
1012 $xi +
= sizeof($orig);
1015 $closing = &$this->edits
[$i]->closing
;
1016 if (is_array($closing)) {
1017 $closing = array_slice($to_lines, $yi, sizeof($closing));
1018 $yi +
= sizeof($closing);
1021 wfProfileOut( $fname );
1026 * A class to format Diffs
1028 * This class formats the diff in classic diff format.
1029 * It is intended that this class be customized via inheritance,
1030 * to obtain fancier outputs.
1037 * Number of leading context "lines" to preserve.
1039 * This should be left at zero for this class, but subclasses
1040 * may want to set this to other values.
1042 var $leading_context_lines = 0;
1045 * Number of trailing context "lines" to preserve.
1047 * This should be left at zero for this class, but subclasses
1048 * may want to set this to other values.
1050 var $trailing_context_lines = 0;
1055 * @param $diff object A Diff object.
1056 * @return string The formatted output.
1058 function format($diff) {
1059 $fname = 'DiffFormatter::format';
1060 wfProfileIn( $fname );
1066 $nlead = $this->leading_context_lines
;
1067 $ntrail = $this->trailing_context_lines
;
1069 $this->_start_diff();
1071 foreach ($diff->edits
as $edit) {
1072 if ($edit->type
== 'copy') {
1073 if (is_array($block)) {
1074 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1079 $context = array_slice($edit->orig
, 0, $ntrail);
1080 $block[] = new _DiffOp_Copy($context);
1082 $this->_block($x0, $ntrail +
$xi - $x0,
1083 $y0, $ntrail +
$yi - $y0,
1088 $context = $edit->orig
;
1091 if (! is_array($block)) {
1092 $context = array_slice($context, sizeof($context) - $nlead);
1093 $x0 = $xi - sizeof($context);
1094 $y0 = $yi - sizeof($context);
1097 $block[] = new _DiffOp_Copy($context);
1103 $xi +
= sizeof($edit->orig
);
1105 $yi +
= sizeof($edit->closing
);
1108 if (is_array($block))
1109 $this->_block($x0, $xi - $x0,
1113 $end = $this->_end_diff();
1114 wfProfileOut( $fname );
1118 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1119 $fname = 'DiffFormatter::_block';
1120 wfProfileIn( $fname );
1121 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1122 foreach ($edits as $edit) {
1123 if ($edit->type
== 'copy')
1124 $this->_context($edit->orig
);
1125 elseif ($edit->type
== 'add')
1126 $this->_added($edit->closing
);
1127 elseif ($edit->type
== 'delete')
1128 $this->_deleted($edit->orig
);
1129 elseif ($edit->type
== 'change')
1130 $this->_changed($edit->orig
, $edit->closing
);
1132 trigger_error('Unknown edit type', E_USER_ERROR
);
1134 $this->_end_block();
1135 wfProfileOut( $fname );
1138 function _start_diff() {
1142 function _end_diff() {
1143 $val = ob_get_contents();
1148 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1150 $xbeg .= "," . ($xbeg +
$xlen - 1);
1152 $ybeg .= "," . ($ybeg +
$ylen - 1);
1154 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1157 function _start_block($header) {
1161 function _end_block() {
1164 function _lines($lines, $prefix = ' ') {
1165 foreach ($lines as $line)
1166 echo "$prefix $line\n";
1169 function _context($lines) {
1170 $this->_lines($lines);
1173 function _added($lines) {
1174 $this->_lines($lines, '>');
1176 function _deleted($lines) {
1177 $this->_lines($lines, '<');
1180 function _changed($orig, $closing) {
1181 $this->_deleted($orig);
1183 $this->_added($closing);
1189 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1193 define('NBSP', ' '); // iso-8859-x non-breaking space.
1199 class _HWLDF_WordAccumulator
{
1200 function _HWLDF_WordAccumulator () {
1201 $this->_lines
= array();
1207 function _flushGroup ($new_tag) {
1208 if ($this->_group
!== '') {
1209 if ($this->_tag
== 'mark')
1210 $this->_line
.= '<span class="diffchange">' .
1211 htmlspecialchars ( $this->_group
) . '</span>';
1213 $this->_line
.= htmlspecialchars ( $this->_group
);
1216 $this->_tag
= $new_tag;
1219 function _flushLine ($new_tag) {
1220 $this->_flushGroup($new_tag);
1221 if ($this->_line
!= '')
1222 array_push ( $this->_lines
, $this->_line
);
1224 # make empty lines visible by inserting an NBSP
1225 array_push ( $this->_lines
, NBSP
);
1229 function addWords ($words, $tag = '') {
1230 if ($tag != $this->_tag
)
1231 $this->_flushGroup($tag);
1233 foreach ($words as $word) {
1234 // new-line should only come as first char of word.
1237 if ($word[0] == "\n") {
1238 $this->_flushLine($tag);
1239 $word = substr($word, 1);
1241 assert(!strstr($word, "\n"));
1242 $this->_group
.= $word;
1246 function getLines() {
1247 $this->_flushLine('~done');
1248 return $this->_lines
;
1256 class WordLevelDiff
extends MappedDiff
1258 function WordLevelDiff ($orig_lines, $closing_lines) {
1259 $fname = 'WordLevelDiff::WordLevelDiff';
1260 wfProfileIn( $fname );
1262 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1263 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1266 $this->MappedDiff($orig_words, $closing_words,
1267 $orig_stripped, $closing_stripped);
1268 wfProfileOut( $fname );
1271 function _split($lines) {
1272 $fname = 'WordLevelDiff::_split';
1273 wfProfileIn( $fname );
1274 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1275 implode("\n", $lines),
1277 wfProfileOut( $fname );
1278 return array(array(''), array(''));
1280 wfProfileOut( $fname );
1281 return array($m[0], $m[1]);
1285 $fname = 'WordLevelDiff::orig';
1286 wfProfileIn( $fname );
1287 $orig = new _HWLDF_WordAccumulator
;
1289 foreach ($this->edits
as $edit) {
1290 if ($edit->type
== 'copy')
1291 $orig->addWords($edit->orig
);
1292 elseif ($edit->orig
)
1293 $orig->addWords($edit->orig
, 'mark');
1295 $lines = $orig->getLines();
1296 wfProfileOut( $fname );
1300 function closing () {
1301 $fname = 'WordLevelDiff::closing';
1302 wfProfileIn( $fname );
1303 $closing = new _HWLDF_WordAccumulator
;
1305 foreach ($this->edits
as $edit) {
1306 if ($edit->type
== 'copy')
1307 $closing->addWords($edit->closing
);
1308 elseif ($edit->closing
)
1309 $closing->addWords($edit->closing
, 'mark');
1311 $lines = $closing->getLines();
1312 wfProfileOut( $fname );
1318 * Wikipedia Table style diff formatter.
1322 class TableDiffFormatter
extends DiffFormatter
1324 function TableDiffFormatter() {
1325 $this->leading_context_lines
= 2;
1326 $this->trailing_context_lines
= 2;
1329 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1330 $l1 = wfMsg( 'lineno', $xbeg );
1331 $l2 = wfMsg( 'lineno', $ybeg );
1333 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1334 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1338 function _start_block( $header ) {
1343 function _end_block() {
1346 function _lines( $lines, $prefix=' ', $color='white' ) {
1349 # HTML-escape parameter before calling this
1350 function addedLine( $line ) {
1351 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1354 # HTML-escape parameter before calling this
1355 function deletedLine( $line ) {
1356 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1359 # HTML-escape parameter before calling this
1360 function contextLine( $line ) {
1361 return "<td> </td><td class='diff-context'>{$line}</td>";
1364 function emptyLine() {
1365 return '<td colspan="2"> </td>';
1368 function _added( $lines ) {
1369 foreach ($lines as $line) {
1370 echo '<tr>' . $this->emptyLine() .
1371 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1375 function _deleted($lines) {
1376 foreach ($lines as $line) {
1377 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1378 $this->emptyLine() . "</tr>\n";
1382 function _context( $lines ) {
1383 foreach ($lines as $line) {
1385 $this->contextLine( htmlspecialchars ( $line ) ) .
1386 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1390 function _changed( $orig, $closing ) {
1391 $fname = 'TableDiffFormatter::_changed';
1392 wfProfileIn( $fname );
1394 $diff = new WordLevelDiff( $orig, $closing );
1395 $del = $diff->orig();
1396 $add = $diff->closing();
1398 # Notice that WordLevelDiff returns HTML-escaped output.
1399 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1401 while ( $line = array_shift( $del ) ) {
1402 $aline = array_shift( $add );
1403 echo '<tr>' . $this->deletedLine( $line ) .
1404 $this->addedLine( $aline ) . "</tr>\n";
1406 foreach ($add as $line) { # If any leftovers
1407 echo '<tr>' . $this->emptyLine() .
1408 $this->addedLine( $line ) . "</tr>\n";
1410 wfProfileOut( $fname );