758a6e06018576f5e7409cccb4398de4e1eb17fb
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();
286 $this->mOldid
= $this->oldRev
->getId();
289 $this->mOldPage
= $this->oldRev
->getTitle();
291 $t = $wgLang->timeanddate( $this->oldRev
->getTimestamp(), true );
292 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
293 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
295 $this->mNewUser
= $this->newRev
->getUserText();
296 $this->mNewComment
= $this->newRev
->getComment();
297 $this->mNewtext
= $this->newRev
->getText();
299 $this->mOldUser
= $this->oldRev
->getUserText();
300 $this->mOldComment
= $this->oldRev
->getComment();
301 $this->mOldtext
= $this->oldRev
->getText();
307 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
309 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
310 // You may copy this code freely under the conditions of the GPL.
313 define('USE_ASSERTS', function_exists('assert'));
325 trigger_error('pure virtual', E_USER_ERROR
);
329 return $this->orig ?
sizeof($this->orig
) : 0;
332 function nclosing() {
333 return $this->closing ?
sizeof($this->closing
) : 0;
341 class _DiffOp_Copy
extends _DiffOp
{
344 function _DiffOp_Copy ($orig, $closing = false) {
345 if (!is_array($closing))
348 $this->closing
= $closing;
352 return new _DiffOp_Copy($this->closing
, $this->orig
);
360 class _DiffOp_Delete
extends _DiffOp
{
361 var $type = 'delete';
363 function _DiffOp_Delete ($lines) {
364 $this->orig
= $lines;
365 $this->closing
= false;
369 return new _DiffOp_Add($this->orig
);
377 class _DiffOp_Add
extends _DiffOp
{
380 function _DiffOp_Add ($lines) {
381 $this->closing
= $lines;
386 return new _DiffOp_Delete($this->closing
);
394 class _DiffOp_Change
extends _DiffOp
{
395 var $type = 'change';
397 function _DiffOp_Change ($orig, $closing) {
399 $this->closing
= $closing;
403 return new _DiffOp_Change($this->closing
, $this->orig
);
409 * Class used internally by Diff to actually compute the diffs.
411 * The algorithm used here is mostly lifted from the perl module
412 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
413 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
415 * More ideas are taken from:
416 * http://www.ics.uci.edu/~eppstein/161/960229.html
418 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
419 * diffutils-2.7, which can be found at:
420 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
422 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
425 * @author Geoffrey T. Dairiki
430 function diff ($from_lines, $to_lines) {
431 $fname = '_DiffEngine::diff';
432 wfProfileIn( $fname );
434 $n_from = sizeof($from_lines);
435 $n_to = sizeof($to_lines);
437 $this->xchanged
= $this->ychanged
= array();
438 $this->xv
= $this->yv
= array();
439 $this->xind
= $this->yind
= array();
441 unset($this->in_seq
);
444 // Skip leading common lines.
445 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
446 if ($from_lines[$skip] != $to_lines[$skip])
448 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
450 // Skip trailing common lines.
451 $xi = $n_from; $yi = $n_to;
452 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
453 if ($from_lines[$xi] != $to_lines[$yi])
455 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
458 // Ignore lines which do not exist in both files.
459 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
460 $xhash[$from_lines[$xi]] = 1;
461 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
462 $line = $to_lines[$yi];
463 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
469 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
470 $line = $from_lines[$xi];
471 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
478 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
480 // Merge edits when possible
481 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
482 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
484 // Compute the edit operations.
487 while ($xi < $n_from ||
$yi < $n_to) {
488 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
489 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
491 // Skip matching "snake".
493 while ( $xi < $n_from && $yi < $n_to
494 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
495 $copy[] = $from_lines[$xi++
];
499 $edits[] = new _DiffOp_Copy($copy);
501 // Find deletes & adds.
503 while ($xi < $n_from && $this->xchanged
[$xi])
504 $delete[] = $from_lines[$xi++
];
507 while ($yi < $n_to && $this->ychanged
[$yi])
508 $add[] = $to_lines[$yi++
];
511 $edits[] = new _DiffOp_Change($delete, $add);
513 $edits[] = new _DiffOp_Delete($delete);
515 $edits[] = new _DiffOp_Add($add);
517 wfProfileOut( $fname );
522 /* Divide the Largest Common Subsequence (LCS) of the sequences
523 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
526 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
527 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
528 * sub sequences. The first sub-sequence is contained in [X0, X1),
529 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
530 * that (X0, Y0) == (XOFF, YOFF) and
531 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
533 * This function assumes that the first lines of the specified portions
534 * of the two files do not match, and likewise that the last lines do not
535 * match. The caller must trim matching lines from the beginning and end
536 * of the portions it is going to specify.
538 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
539 $fname = '_DiffEngine::_diag';
540 wfProfileIn( $fname );
543 if ($xlim - $xoff > $ylim - $yoff) {
544 // Things seems faster (I'm not sure I understand why)
545 // when the shortest sequence in X.
547 list ($xoff, $xlim, $yoff, $ylim)
548 = array( $yoff, $ylim, $xoff, $xlim);
552 for ($i = $ylim - 1; $i >= $yoff; $i--)
553 $ymatches[$this->xv
[$i]][] = $i;
555 for ($i = $ylim - 1; $i >= $yoff; $i--)
556 $ymatches[$this->yv
[$i]][] = $i;
559 $this->seq
[0]= $yoff - 1;
560 $this->in_seq
= array();
563 $numer = $xlim - $xoff +
$nchunks - 1;
565 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
566 wfProfileIn( "$fname-chunk" );
568 for ($i = 0; $i <= $this->lcs
; $i++
)
569 $ymids[$i][$chunk-1] = $this->seq
[$i];
571 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
572 for ( ; $x < $x1; $x++
) {
573 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
574 if (empty($ymatches[$line]))
576 $matches = $ymatches[$line];
578 while (list ($junk, $y) = each($matches))
579 if (empty($this->in_seq
[$y])) {
580 $k = $this->_lcs_pos($y);
581 USE_ASSERTS
&& assert($k > 0);
582 $ymids[$k] = $ymids[$k-1];
585 while (list ($junk, $y) = each($matches)) {
586 if ($y > $this->seq
[$k-1]) {
587 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
588 // Optimization: this is a common case:
589 // next match is just replacing previous match.
590 $this->in_seq
[$this->seq
[$k]] = false;
592 $this->in_seq
[$y] = 1;
593 } else if (empty($this->in_seq
[$y])) {
594 $k = $this->_lcs_pos($y);
595 USE_ASSERTS
&& assert($k > 0);
596 $ymids[$k] = $ymids[$k-1];
600 wfProfileOut( "$fname-chunk" );
603 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
604 $ymid = $ymids[$this->lcs
];
605 for ($n = 0; $n < $nchunks - 1; $n++
) {
606 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
608 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
610 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
612 wfProfileOut( $fname );
613 return array($this->lcs
, $seps);
616 function _lcs_pos ($ypos) {
617 $fname = '_DiffEngine::_lcs_pos';
618 wfProfileIn( $fname );
621 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
622 $this->seq
[++
$this->lcs
] = $ypos;
623 $this->in_seq
[$ypos] = 1;
624 wfProfileOut( $fname );
629 while ($beg < $end) {
630 $mid = (int)(($beg +
$end) / 2);
631 if ( $ypos > $this->seq
[$mid] )
637 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
639 $this->in_seq
[$this->seq
[$end]] = false;
640 $this->seq
[$end] = $ypos;
641 $this->in_seq
[$ypos] = 1;
642 wfProfileOut( $fname );
646 /* Find LCS of two sequences.
648 * The results are recorded in the vectors $this->{x,y}changed[], by
649 * storing a 1 in the element for each line that is an insertion
650 * or deletion (ie. is not in the LCS).
652 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
654 * Note that XLIM, YLIM are exclusive bounds.
655 * All line numbers are origin-0 and discarded lines are not counted.
657 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
658 $fname = '_DiffEngine::_compareseq';
659 wfProfileIn( $fname );
661 // Slide down the bottom initial diagonal.
662 while ($xoff < $xlim && $yoff < $ylim
663 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
668 // Slide up the top initial diagonal.
669 while ($xlim > $xoff && $ylim > $yoff
670 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
675 if ($xoff == $xlim ||
$yoff == $ylim)
678 // This is ad hoc but seems to work well.
679 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
680 //$nchunks = max(2,min(8,(int)$nchunks));
681 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
683 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
687 // X and Y sequences have no common subsequence:
689 while ($yoff < $ylim)
690 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
691 while ($xoff < $xlim)
692 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
694 // Use the partitions to split this problem into subproblems.
697 while ($pt2 = next($seps)) {
698 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
702 wfProfileOut( $fname );
705 /* Adjust inserts/deletes of identical lines to join changes
706 * as much as possible.
708 * We do something when a run of changed lines include a
709 * line at one end and has an excluded, identical line at the other.
710 * We are free to choose which identical line is included.
711 * `compareseq' usually chooses the one at the beginning,
712 * but usually it is cleaner to consider the following identical line
713 * to be the "change".
715 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
717 function _shift_boundaries ($lines, &$changed, $other_changed) {
718 $fname = '_DiffEngine::_shift_boundaries';
719 wfProfileIn( $fname );
723 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
724 $len = sizeof($lines);
725 $other_len = sizeof($other_changed);
729 * Scan forwards to find beginning of another run of changes.
730 * Also keep track of the corresponding point in the other file.
732 * Throughout this code, $i and $j are adjusted together so that
733 * the first $i elements of $changed and the first $j elements
734 * of $other_changed both contain the same number of zeros
736 * Furthermore, $j is always kept so that $j == $other_len or
737 * $other_changed[$j] == false.
739 while ($j < $other_len && $other_changed[$j])
742 while ($i < $len && ! $changed[$i]) {
743 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
745 while ($j < $other_len && $other_changed[$j])
754 // Find the end of this run of changes.
755 while (++
$i < $len && $changed[$i])
760 * Record the length of this run of changes, so that
761 * we can later determine whether the run has grown.
763 $runlength = $i - $start;
766 * Move the changed region back, so long as the
767 * previous unchanged line matches the last changed one.
768 * This merges with previous changed regions.
770 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
771 $changed[--$start] = 1;
772 $changed[--$i] = false;
773 while ($start > 0 && $changed[$start - 1])
775 USE_ASSERTS
&& assert('$j > 0');
776 while ($other_changed[--$j])
778 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
782 * Set CORRESPONDING to the end of the changed run, at the last
783 * point where it corresponds to a changed run in the other file.
784 * CORRESPONDING == LEN means no such point has been found.
786 $corresponding = $j < $other_len ?
$i : $len;
789 * Move the changed region forward, so long as the
790 * first changed line matches the following unchanged one.
791 * This merges with following changed regions.
792 * Do this second, so that if there are no merges,
793 * the changed region is moved forward as far as possible.
795 while ($i < $len && $lines[$start] == $lines[$i]) {
796 $changed[$start++
] = false;
798 while ($i < $len && $changed[$i])
801 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
803 if ($j < $other_len && $other_changed[$j]) {
805 while ($j < $other_len && $other_changed[$j])
809 } while ($runlength != $i - $start);
812 * If possible, move the fully-merged run of changes
813 * back to a corresponding run in the other file.
815 while ($corresponding < $i) {
816 $changed[--$start] = 1;
818 USE_ASSERTS
&& assert('$j > 0');
819 while ($other_changed[--$j])
821 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
824 wfProfileOut( $fname );
829 * Class representing a 'diff' between two sequences of strings.
839 * Computes diff between sequences of strings.
841 * @param $from_lines array An array of strings.
842 * (Typically these are lines from a file.)
843 * @param $to_lines array An array of strings.
845 function Diff($from_lines, $to_lines) {
846 $eng = new _DiffEngine
;
847 $this->edits
= $eng->diff($from_lines, $to_lines);
848 //$this->_check($from_lines, $to_lines);
852 * Compute reversed Diff.
856 * $diff = new Diff($lines1, $lines2);
857 * $rev = $diff->reverse();
858 * @return object A Diff object representing the inverse of the
861 function reverse () {
863 $rev->edits
= array();
864 foreach ($this->edits
as $edit) {
865 $rev->edits
[] = $edit->reverse();
871 * Check for empty diff.
873 * @return bool True iff two sequences were identical.
875 function isEmpty () {
876 foreach ($this->edits
as $edit) {
877 if ($edit->type
!= 'copy')
884 * Compute the length of the Longest Common Subsequence (LCS).
886 * This is mostly for diagnostic purposed.
888 * @return int The length of the LCS.
892 foreach ($this->edits
as $edit) {
893 if ($edit->type
== 'copy')
894 $lcs +
= sizeof($edit->orig
);
900 * Get the original set of lines.
902 * This reconstructs the $from_lines parameter passed to the
905 * @return array The original sequence of strings.
910 foreach ($this->edits
as $edit) {
912 array_splice($lines, sizeof($lines), 0, $edit->orig
);
918 * Get the closing set of lines.
920 * This reconstructs the $to_lines parameter passed to the
923 * @return array The sequence of strings.
928 foreach ($this->edits
as $edit) {
930 array_splice($lines, sizeof($lines), 0, $edit->closing
);
936 * Check a Diff for validity.
938 * This is here only for debugging purposes.
940 function _check ($from_lines, $to_lines) {
941 $fname = 'Diff::_check';
942 wfProfileIn( $fname );
943 if (serialize($from_lines) != serialize($this->orig()))
944 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
945 if (serialize($to_lines) != serialize($this->closing()))
946 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
948 $rev = $this->reverse();
949 if (serialize($to_lines) != serialize($rev->orig()))
950 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
951 if (serialize($from_lines) != serialize($rev->closing()))
952 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
956 foreach ($this->edits
as $edit) {
957 if ( $prevtype == $edit->type
)
958 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
959 $prevtype = $edit->type
;
963 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
964 wfProfileOut( $fname );
973 class MappedDiff
extends Diff
978 * Computes diff between sequences of strings.
980 * This can be used to compute things like
981 * case-insensitve diffs, or diffs which ignore
982 * changes in white-space.
984 * @param $from_lines array An array of strings.
985 * (Typically these are lines from a file.)
987 * @param $to_lines array An array of strings.
989 * @param $mapped_from_lines array This array should
990 * have the same size number of elements as $from_lines.
991 * The elements in $mapped_from_lines and
992 * $mapped_to_lines are what is actually compared
993 * when computing the diff.
995 * @param $mapped_to_lines array This array should
996 * have the same number of elements as $to_lines.
998 function MappedDiff($from_lines, $to_lines,
999 $mapped_from_lines, $mapped_to_lines) {
1000 $fname = 'MappedDiff::MappedDiff';
1001 wfProfileIn( $fname );
1003 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1004 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1006 $this->Diff($mapped_from_lines, $mapped_to_lines);
1009 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1010 $orig = &$this->edits
[$i]->orig
;
1011 if (is_array($orig)) {
1012 $orig = array_slice($from_lines, $xi, sizeof($orig));
1013 $xi +
= sizeof($orig);
1016 $closing = &$this->edits
[$i]->closing
;
1017 if (is_array($closing)) {
1018 $closing = array_slice($to_lines, $yi, sizeof($closing));
1019 $yi +
= sizeof($closing);
1022 wfProfileOut( $fname );
1027 * A class to format Diffs
1029 * This class formats the diff in classic diff format.
1030 * It is intended that this class be customized via inheritance,
1031 * to obtain fancier outputs.
1038 * Number of leading context "lines" to preserve.
1040 * This should be left at zero for this class, but subclasses
1041 * may want to set this to other values.
1043 var $leading_context_lines = 0;
1046 * Number of trailing context "lines" to preserve.
1048 * This should be left at zero for this class, but subclasses
1049 * may want to set this to other values.
1051 var $trailing_context_lines = 0;
1056 * @param $diff object A Diff object.
1057 * @return string The formatted output.
1059 function format($diff) {
1060 $fname = 'DiffFormatter::format';
1061 wfProfileIn( $fname );
1067 $nlead = $this->leading_context_lines
;
1068 $ntrail = $this->trailing_context_lines
;
1070 $this->_start_diff();
1072 foreach ($diff->edits
as $edit) {
1073 if ($edit->type
== 'copy') {
1074 if (is_array($block)) {
1075 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1080 $context = array_slice($edit->orig
, 0, $ntrail);
1081 $block[] = new _DiffOp_Copy($context);
1083 $this->_block($x0, $ntrail +
$xi - $x0,
1084 $y0, $ntrail +
$yi - $y0,
1089 $context = $edit->orig
;
1092 if (! is_array($block)) {
1093 $context = array_slice($context, sizeof($context) - $nlead);
1094 $x0 = $xi - sizeof($context);
1095 $y0 = $yi - sizeof($context);
1098 $block[] = new _DiffOp_Copy($context);
1104 $xi +
= sizeof($edit->orig
);
1106 $yi +
= sizeof($edit->closing
);
1109 if (is_array($block))
1110 $this->_block($x0, $xi - $x0,
1114 $end = $this->_end_diff();
1115 wfProfileOut( $fname );
1119 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1120 $fname = 'DiffFormatter::_block';
1121 wfProfileIn( $fname );
1122 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1123 foreach ($edits as $edit) {
1124 if ($edit->type
== 'copy')
1125 $this->_context($edit->orig
);
1126 elseif ($edit->type
== 'add')
1127 $this->_added($edit->closing
);
1128 elseif ($edit->type
== 'delete')
1129 $this->_deleted($edit->orig
);
1130 elseif ($edit->type
== 'change')
1131 $this->_changed($edit->orig
, $edit->closing
);
1133 trigger_error('Unknown edit type', E_USER_ERROR
);
1135 $this->_end_block();
1136 wfProfileOut( $fname );
1139 function _start_diff() {
1143 function _end_diff() {
1144 $val = ob_get_contents();
1149 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1151 $xbeg .= "," . ($xbeg +
$xlen - 1);
1153 $ybeg .= "," . ($ybeg +
$ylen - 1);
1155 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1158 function _start_block($header) {
1162 function _end_block() {
1165 function _lines($lines, $prefix = ' ') {
1166 foreach ($lines as $line)
1167 echo "$prefix $line\n";
1170 function _context($lines) {
1171 $this->_lines($lines);
1174 function _added($lines) {
1175 $this->_lines($lines, '>');
1177 function _deleted($lines) {
1178 $this->_lines($lines, '<');
1181 function _changed($orig, $closing) {
1182 $this->_deleted($orig);
1184 $this->_added($closing);
1190 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1194 define('NBSP', ' '); // iso-8859-x non-breaking space.
1200 class _HWLDF_WordAccumulator
{
1201 function _HWLDF_WordAccumulator () {
1202 $this->_lines
= array();
1208 function _flushGroup ($new_tag) {
1209 if ($this->_group
!== '') {
1210 if ($this->_tag
== 'mark')
1211 $this->_line
.= '<span class="diffchange">' .
1212 htmlspecialchars ( $this->_group
) . '</span>';
1214 $this->_line
.= htmlspecialchars ( $this->_group
);
1217 $this->_tag
= $new_tag;
1220 function _flushLine ($new_tag) {
1221 $this->_flushGroup($new_tag);
1222 if ($this->_line
!= '')
1223 array_push ( $this->_lines
, $this->_line
);
1225 # make empty lines visible by inserting an NBSP
1226 array_push ( $this->_lines
, NBSP
);
1230 function addWords ($words, $tag = '') {
1231 if ($tag != $this->_tag
)
1232 $this->_flushGroup($tag);
1234 foreach ($words as $word) {
1235 // new-line should only come as first char of word.
1238 if ($word[0] == "\n") {
1239 $this->_flushLine($tag);
1240 $word = substr($word, 1);
1242 assert(!strstr($word, "\n"));
1243 $this->_group
.= $word;
1247 function getLines() {
1248 $this->_flushLine('~done');
1249 return $this->_lines
;
1257 class WordLevelDiff
extends MappedDiff
1259 function WordLevelDiff ($orig_lines, $closing_lines) {
1260 $fname = 'WordLevelDiff::WordLevelDiff';
1261 wfProfileIn( $fname );
1263 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1264 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1267 $this->MappedDiff($orig_words, $closing_words,
1268 $orig_stripped, $closing_stripped);
1269 wfProfileOut( $fname );
1272 function _split($lines) {
1273 $fname = 'WordLevelDiff::_split';
1274 wfProfileIn( $fname );
1275 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1276 implode("\n", $lines),
1278 wfProfileOut( $fname );
1279 return array(array(''), array(''));
1281 wfProfileOut( $fname );
1282 return array($m[0], $m[1]);
1286 $fname = 'WordLevelDiff::orig';
1287 wfProfileIn( $fname );
1288 $orig = new _HWLDF_WordAccumulator
;
1290 foreach ($this->edits
as $edit) {
1291 if ($edit->type
== 'copy')
1292 $orig->addWords($edit->orig
);
1293 elseif ($edit->orig
)
1294 $orig->addWords($edit->orig
, 'mark');
1296 $lines = $orig->getLines();
1297 wfProfileOut( $fname );
1301 function closing () {
1302 $fname = 'WordLevelDiff::closing';
1303 wfProfileIn( $fname );
1304 $closing = new _HWLDF_WordAccumulator
;
1306 foreach ($this->edits
as $edit) {
1307 if ($edit->type
== 'copy')
1308 $closing->addWords($edit->closing
);
1309 elseif ($edit->closing
)
1310 $closing->addWords($edit->closing
, 'mark');
1312 $lines = $closing->getLines();
1313 wfProfileOut( $fname );
1319 * Wikipedia Table style diff formatter.
1323 class TableDiffFormatter
extends DiffFormatter
1325 function TableDiffFormatter() {
1326 $this->leading_context_lines
= 2;
1327 $this->trailing_context_lines
= 2;
1330 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1331 $l1 = wfMsg( 'lineno', $xbeg );
1332 $l2 = wfMsg( 'lineno', $ybeg );
1334 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1335 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1339 function _start_block( $header ) {
1344 function _end_block() {
1347 function _lines( $lines, $prefix=' ', $color='white' ) {
1350 # HTML-escape parameter before calling this
1351 function addedLine( $line ) {
1352 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1355 # HTML-escape parameter before calling this
1356 function deletedLine( $line ) {
1357 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1360 # HTML-escape parameter before calling this
1361 function contextLine( $line ) {
1362 return "<td> </td><td class='diff-context'>{$line}</td>";
1365 function emptyLine() {
1366 return '<td colspan="2"> </td>';
1369 function _added( $lines ) {
1370 foreach ($lines as $line) {
1371 echo '<tr>' . $this->emptyLine() .
1372 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1376 function _deleted($lines) {
1377 foreach ($lines as $line) {
1378 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1379 $this->emptyLine() . "</tr>\n";
1383 function _context( $lines ) {
1384 foreach ($lines as $line) {
1386 $this->contextLine( htmlspecialchars ( $line ) ) .
1387 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1391 function _changed( $orig, $closing ) {
1392 $fname = 'TableDiffFormatter::_changed';
1393 wfProfileIn( $fname );
1395 $diff = new WordLevelDiff( $orig, $closing );
1396 $del = $diff->orig();
1397 $add = $diff->closing();
1399 # Notice that WordLevelDiff returns HTML-escaped output.
1400 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1402 while ( $line = array_shift( $del ) ) {
1403 $aline = array_shift( $add );
1404 echo '<tr>' . $this->deletedLine( $line ) .
1405 $this->addedLine( $aline ) . "</tr>\n";
1407 foreach ($add as $line) { # If any leftovers
1408 echo '<tr>' . $this->emptyLine() .
1409 $this->addedLine( $line ) . "</tr>\n";
1411 wfProfileOut( $fname );