9 class DifferenceEngine
{
10 /* private */ var $mOldid, $mNewid;
11 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
12 /* private */ var $mOldtext, $mNewtext;
13 /* private */ var $mOldUser, $mNewUser;
14 /* private */ var $mOldComment, $mNewComment;
15 /* private */ var $mOldPage, $mNewPage;
16 /* private */ var $mRcidMarkPatrolled;
18 function DifferenceEngine( $old, $new, $rcid = 0 )
21 if ( 'prev' == $new ) {
22 # Show diff between revision $old and the previous one.
23 # Get previous one from DB.
25 $this->mNewid
= intval($old);
26 $dbr =& wfGetDB( DB_SLAVE
);
27 $this->mOldid
= $dbr->selectField( 'old', 'old_id',
28 "old_title='" . $wgTitle->getDBkey() . "'" .
29 ' AND old_namespace=' . $wgTitle->getNamespace() .
30 " AND old_id<{$this->mNewid} ORDER BY old_id DESC" );
32 } elseif ( 'next' == $new ) {
34 # Show diff between revision $old and the previous one.
35 # Get previous one from DB.
37 $this->mOldid
= intval($old);
38 $dbr =& wfGetDB( DB_SLAVE
);
39 $this->mNewid
= $dbr->selectField( 'old', 'old_id',
40 "old_title='" . $wgTitle->getDBkey() . "'" .
41 ' AND old_namespace=' . $wgTitle->getNamespace() .
42 " AND old_id>{$this->mOldid} ORDER BY old_id " );
43 if ( false === $this->mNewid
) {
44 # if no result, NewId points to the newest old revision. The only newer
45 # revision is cur, which is "0".
51 $this->mOldid
= intval($old);
52 $this->mNewid
= intval($new);
54 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
57 function showDiffPage()
59 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
60 $fname = 'DifferenceEngine::showDiffPage';
61 wfProfileIn( $fname );
63 # mOldid is false if the difference engine is called with a "vague" query for
64 # a diff between a version V and its previous version V' AND the version V
65 # is the first version of that article. In that case, V' does not exist.
66 if ( $this->mOldid
=== false ) {
67 $this->showFirstRevision();
68 wfProfileOut( $fname );
72 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
74 $mtext = wfMsg( 'missingarticle', $t );
76 $wgOut->setArticleFlag( false );
77 if ( ! $this->loadText() ) {
78 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
79 $wgOut->addHTML( $mtext );
80 wfProfileOut( $fname );
83 $wgOut->suppressQuickbar();
85 $oldTitle = $this->mOldPage
->getPrefixedText();
86 $newTitle = $this->mNewPage
->getPrefixedText();
87 if( $oldTitle == $newTitle ) {
88 $wgOut->setPageTitle( $newTitle );
90 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
92 $wgOut->setSubtitle( wfMsg( 'difference' ) );
93 $wgOut->setRobotpolicy( 'noindex,follow' );
95 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
98 wfProfileOut( $fname );
102 $sk = $wgUser->getSkin();
103 $talk = $wgLang->getNsText( NS_TALK
);
104 $contribs = wfMsg( 'contribslink' );
106 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
107 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
109 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
110 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
111 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
112 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
113 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
114 'target=' . urlencode($this->mOldUser
) );
115 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
116 'target=' . urlencode($this->mNewUser
) );
117 if ( !$this->mNewid
&& $wgUser->isSysop() ) {
118 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
119 'action=rollback&from=' . urlencode($this->mNewUser
) ) . ']</strong>';
123 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
124 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
126 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
127 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
132 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
133 if ( $this->mNewid
== 0 ) {
136 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
139 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
140 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
141 '<br />' . $prevlink;
142 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
143 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
144 '<br />' . $nextlink . $patrol;
146 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
147 $oldHeader, $newHeader );
148 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
149 $wgOut->addWikiText( $this->mNewtext
);
151 wfProfileOut( $fname );
154 # Show the first revision of an article. Uses normal diff headers in contrast to normal
155 # "old revision" display style.
157 function showFirstRevision()
159 global $wgOut, $wgTitle, $wgUser, $wgLang;
161 $fname = 'DifferenceEngine::showFirstRevision';
162 wfProfileIn( $fname );
165 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
167 # Get article text from the DB
169 if ( ! $this->loadText() ) {
170 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
172 $mtext = wfMsg( 'missingarticle', $t );
173 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
174 $wgOut->addHTML( $mtext );
175 wfProfileOut( $fname );
179 # Check if user is allowed to look at this page. If not, bail out.
181 if ( !( $this->mOldPage
->userCanRead() ) ) {
182 $wgOut->loginToUse();
184 wfProfileOut( $fname );
188 # Prepare the header box
190 $sk = $wgUser->getSkin();
192 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
193 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
194 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
195 'target=' . urlencode($this->mOldUser
) );
196 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
197 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
198 "($uTLink | $contribs)<br />" . $this->mOldComment
.
199 '<br />' . $nextlink. "</div>\n";
201 $wgOut->addHTML( $header );
203 $wgOut->setSubtitle( wfMsg( 'difference' ) );
204 $wgOut->setRobotpolicy( 'noindex,follow' );
207 # Show current revision
209 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
210 $wgOut->addWikiText( $this->mNewtext
);
212 wfProfileOut( $fname );
215 function showDiff( $otext, $ntext, $otitle, $ntitle )
217 global $wgOut, $wgUseExternalDiffEngine;
220 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
222 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
223 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
227 if ( $wgUseExternalDiffEngine ) {
228 # For historical reasons, external diff engine expects
229 # input text to be HTML-escaped already
230 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
231 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
232 dl('php_wikidiff.so');
233 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
235 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
236 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
237 $diffs = new Diff( $ota, $nta );
238 $formatter = new TableDiffFormatter();
239 $formatter->format( $diffs );
241 $wgOut->addHTML( "</table>\n" );
244 # Load the text of the articles to compare. If newid is 0, then compare
245 # the old article in oldid to the current article; if oldid is 0, then
246 # compare the current article to the immediately previous one (ignoring
247 # the value of newid).
251 global $wgTitle, $wgOut, $wgLang;
252 $fname = 'DifferenceEngine::loadText';
254 $dbr =& wfGetDB( DB_SLAVE
);
255 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
256 $wgOut->setArticleFlag( true );
257 $newLink = $wgTitle->getLocalUrl();
258 $this->mPagetitle
= wfMsg( 'currentrev' );
259 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
260 $id = $wgTitle->getArticleID();
262 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
263 array( 'cur_id' => $id ), $fname );
264 if ( $s === false ) {
268 $this->mNewPage
= &$wgTitle;
269 $this->mNewtext
= $s->cur_text
;
270 $this->mNewUser
= $s->cur_user_text
;
271 $this->mNewComment
= $s->cur_comment
;
273 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
274 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
276 if ( $s === false ) {
280 $this->mNewtext
= Article
::getRevisionText( $s );
282 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
283 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
284 $newLink = $wgTitle->getLocalUrl ('oldid=' . $this->mNewid
);
285 $this->mPagetitle
= wfMsg( 'revisionasof', $t );
286 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
287 $this->mNewUser
= $s->old_user_text
;
288 $this->mNewComment
= $s->old_comment
;
290 if ( 0 == $this->mOldid
) {
291 $s = $dbr->getArray( 'old',
292 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
294 'old_namespace' => $this->mNewPage
->getNamespace(),
295 'old_title' => $this->mNewPage
->getDBkey()
296 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
299 $s = $dbr->getArray( 'old',
300 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
301 array( 'old_id' => $this->mOldid
),
305 if ( $s === false ) {
308 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
309 $this->mOldtext
= Article
::getRevisionText( $s );
311 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
312 $oldLink = $this->mOldPage
->getLocalUrl ('oldid=' . $this->mOldid
);
313 $this->mOldtitle
= "<a href='$oldLink'>" . wfMsg( 'revisionasof', $t ) . '</a>';
314 $this->mOldUser
= $s->old_user_text
;
315 $this->mOldComment
= $s->old_comment
;
321 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
323 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
324 // You may copy this code freely under the conditions of the GPL.
327 define('USE_ASSERTS', function_exists('assert'));
338 trigger_error('pure virtual', E_USER_ERROR
);
342 return $this->orig ?
sizeof($this->orig
) : 0;
345 function nclosing() {
346 return $this->closing ?
sizeof($this->closing
) : 0;
353 class _DiffOp_Copy
extends _DiffOp
{
356 function _DiffOp_Copy ($orig, $closing = false) {
357 if (!is_array($closing))
360 $this->closing
= $closing;
364 return new _DiffOp_Copy($this->closing
, $this->orig
);
371 class _DiffOp_Delete
extends _DiffOp
{
372 var $type = 'delete';
374 function _DiffOp_Delete ($lines) {
375 $this->orig
= $lines;
376 $this->closing
= false;
380 return new _DiffOp_Add($this->orig
);
387 class _DiffOp_Add
extends _DiffOp
{
390 function _DiffOp_Add ($lines) {
391 $this->closing
= $lines;
396 return new _DiffOp_Delete($this->closing
);
403 class _DiffOp_Change
extends _DiffOp
{
404 var $type = 'change';
406 function _DiffOp_Change ($orig, $closing) {
408 $this->closing
= $closing;
412 return new _DiffOp_Change($this->closing
, $this->orig
);
418 * Class used internally by Diff to actually compute the diffs.
420 * The algorithm used here is mostly lifted from the perl module
421 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
422 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
424 * More ideas are taken from:
425 * http://www.ics.uci.edu/~eppstein/161/960229.html
427 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
428 * diffutils-2.7, which can be found at:
429 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
431 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
434 * @author Geoffrey T. Dairiki
439 function diff ($from_lines, $to_lines) {
440 $n_from = sizeof($from_lines);
441 $n_to = sizeof($to_lines);
443 $this->xchanged
= $this->ychanged
= array();
444 $this->xv
= $this->yv
= array();
445 $this->xind
= $this->yind
= array();
447 unset($this->in_seq
);
450 // Skip leading common lines.
451 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
452 if ($from_lines[$skip] != $to_lines[$skip])
454 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
456 // Skip trailing common lines.
457 $xi = $n_from; $yi = $n_to;
458 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
459 if ($from_lines[$xi] != $to_lines[$yi])
461 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
464 // Ignore lines which do not exist in both files.
465 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
466 $xhash[$from_lines[$xi]] = 1;
467 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
468 $line = $to_lines[$yi];
469 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
475 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
476 $line = $from_lines[$xi];
477 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
484 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
486 // Merge edits when possible
487 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
488 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
490 // Compute the edit operations.
493 while ($xi < $n_from ||
$yi < $n_to) {
494 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
495 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
497 // Skip matching "snake".
499 while ( $xi < $n_from && $yi < $n_to
500 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
501 $copy[] = $from_lines[$xi++
];
505 $edits[] = new _DiffOp_Copy($copy);
507 // Find deletes & adds.
509 while ($xi < $n_from && $this->xchanged
[$xi])
510 $delete[] = $from_lines[$xi++
];
513 while ($yi < $n_to && $this->ychanged
[$yi])
514 $add[] = $to_lines[$yi++
];
517 $edits[] = new _DiffOp_Change($delete, $add);
519 $edits[] = new _DiffOp_Delete($delete);
521 $edits[] = new _DiffOp_Add($add);
527 /* Divide the Largest Common Subsequence (LCS) of the sequences
528 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
531 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
532 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
533 * sub sequences. The first sub-sequence is contained in [X0, X1),
534 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
535 * that (X0, Y0) == (XOFF, YOFF) and
536 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
538 * This function assumes that the first lines of the specified portions
539 * of the two files do not match, and likewise that the last lines do not
540 * match. The caller must trim matching lines from the beginning and end
541 * of the portions it is going to specify.
543 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
546 if ($xlim - $xoff > $ylim - $yoff) {
547 // Things seems faster (I'm not sure I understand why)
548 // when the shortest sequence in X.
550 list ($xoff, $xlim, $yoff, $ylim)
551 = array( $yoff, $ylim, $xoff, $xlim);
555 for ($i = $ylim - 1; $i >= $yoff; $i--)
556 $ymatches[$this->xv
[$i]][] = $i;
558 for ($i = $ylim - 1; $i >= $yoff; $i--)
559 $ymatches[$this->yv
[$i]][] = $i;
562 $this->seq
[0]= $yoff - 1;
563 $this->in_seq
= array();
566 $numer = $xlim - $xoff +
$nchunks - 1;
568 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
570 for ($i = 0; $i <= $this->lcs
; $i++
)
571 $ymids[$i][$chunk-1] = $this->seq
[$i];
573 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
574 for ( ; $x < $x1; $x++
) {
575 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
576 if (empty($ymatches[$line]))
578 $matches = $ymatches[$line];
580 while (list ($junk, $y) = each($matches))
581 if (empty($this->in_seq
[$y])) {
582 $k = $this->_lcs_pos($y);
583 USE_ASSERTS
&& assert($k > 0);
584 $ymids[$k] = $ymids[$k-1];
587 while (list ($junk, $y) = each($matches)) {
588 if ($y > $this->seq
[$k-1]) {
589 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
590 // Optimization: this is a common case:
591 // next match is just replacing previous match.
592 $this->in_seq
[$this->seq
[$k]] = false;
594 $this->in_seq
[$y] = 1;
596 else if (empty($this->in_seq
[$y])) {
597 $k = $this->_lcs_pos($y);
598 USE_ASSERTS
&& assert($k > 0);
599 $ymids[$k] = $ymids[$k-1];
605 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
606 $ymid = $ymids[$this->lcs
];
607 for ($n = 0; $n < $nchunks - 1; $n++
) {
608 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
610 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
612 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
614 return array($this->lcs
, $seps);
617 function _lcs_pos ($ypos) {
619 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
620 $this->seq
[++
$this->lcs
] = $ypos;
621 $this->in_seq
[$ypos] = 1;
626 while ($beg < $end) {
627 $mid = (int)(($beg +
$end) / 2);
628 if ( $ypos > $this->seq
[$mid] )
634 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
636 $this->in_seq
[$this->seq
[$end]] = false;
637 $this->seq
[$end] = $ypos;
638 $this->in_seq
[$ypos] = 1;
642 /* Find LCS of two sequences.
644 * The results are recorded in the vectors $this->{x,y}changed[], by
645 * storing a 1 in the element for each line that is an insertion
646 * or deletion (ie. is not in the LCS).
648 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
650 * Note that XLIM, YLIM are exclusive bounds.
651 * All line numbers are origin-0 and discarded lines are not counted.
653 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
654 // Slide down the bottom initial diagonal.
655 while ($xoff < $xlim && $yoff < $ylim
656 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
661 // Slide up the top initial diagonal.
662 while ($xlim > $xoff && $ylim > $yoff
663 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
668 if ($xoff == $xlim ||
$yoff == $ylim)
671 // This is ad hoc but seems to work well.
672 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
673 //$nchunks = max(2,min(8,(int)$nchunks));
674 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
676 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
680 // X and Y sequences have no common subsequence:
682 while ($yoff < $ylim)
683 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
684 while ($xoff < $xlim)
685 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
688 // Use the partitions to split this problem into subproblems.
691 while ($pt2 = next($seps)) {
692 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
698 /* Adjust inserts/deletes of identical lines to join changes
699 * as much as possible.
701 * We do something when a run of changed lines include a
702 * line at one end and has an excluded, identical line at the other.
703 * We are free to choose which identical line is included.
704 * `compareseq' usually chooses the one at the beginning,
705 * but usually it is cleaner to consider the following identical line
706 * to be the "change".
708 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
710 function _shift_boundaries ($lines, &$changed, $other_changed) {
714 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
715 $len = sizeof($lines);
716 $other_len = sizeof($other_changed);
720 * Scan forwards to find beginning of another run of changes.
721 * Also keep track of the corresponding point in the other file.
723 * Throughout this code, $i and $j are adjusted together so that
724 * the first $i elements of $changed and the first $j elements
725 * of $other_changed both contain the same number of zeros
727 * Furthermore, $j is always kept so that $j == $other_len or
728 * $other_changed[$j] == false.
730 while ($j < $other_len && $other_changed[$j])
733 while ($i < $len && ! $changed[$i]) {
734 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
736 while ($j < $other_len && $other_changed[$j])
745 // Find the end of this run of changes.
746 while (++
$i < $len && $changed[$i])
751 * Record the length of this run of changes, so that
752 * we can later determine whether the run has grown.
754 $runlength = $i - $start;
757 * Move the changed region back, so long as the
758 * previous unchanged line matches the last changed one.
759 * This merges with previous changed regions.
761 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
762 $changed[--$start] = 1;
763 $changed[--$i] = false;
764 while ($start > 0 && $changed[$start - 1])
766 USE_ASSERTS
&& assert('$j > 0');
767 while ($other_changed[--$j])
769 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
773 * Set CORRESPONDING to the end of the changed run, at the last
774 * point where it corresponds to a changed run in the other file.
775 * CORRESPONDING == LEN means no such point has been found.
777 $corresponding = $j < $other_len ?
$i : $len;
780 * Move the changed region forward, so long as the
781 * first changed line matches the following unchanged one.
782 * This merges with following changed regions.
783 * Do this second, so that if there are no merges,
784 * the changed region is moved forward as far as possible.
786 while ($i < $len && $lines[$start] == $lines[$i]) {
787 $changed[$start++
] = false;
789 while ($i < $len && $changed[$i])
792 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
794 if ($j < $other_len && $other_changed[$j]) {
796 while ($j < $other_len && $other_changed[$j])
800 } while ($runlength != $i - $start);
803 * If possible, move the fully-merged run of changes
804 * back to a corresponding run in the other file.
806 while ($corresponding < $i) {
807 $changed[--$start] = 1;
809 USE_ASSERTS
&& assert('$j > 0');
810 while ($other_changed[--$j])
812 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
819 * Class representing a 'diff' between two sequences of strings.
828 * Computes diff between sequences of strings.
830 * @param $from_lines array An array of strings.
831 * (Typically these are lines from a file.)
832 * @param $to_lines array An array of strings.
834 function Diff($from_lines, $to_lines) {
835 $eng = new _DiffEngine
;
836 $this->edits
= $eng->diff($from_lines, $to_lines);
837 //$this->_check($from_lines, $to_lines);
841 * Compute reversed Diff.
845 * $diff = new Diff($lines1, $lines2);
846 * $rev = $diff->reverse();
847 * @return object A Diff object representing the inverse of the
850 function reverse () {
852 $rev->edits
= array();
853 foreach ($this->edits
as $edit) {
854 $rev->edits
[] = $edit->reverse();
860 * Check for empty diff.
862 * @return bool True iff two sequences were identical.
864 function isEmpty () {
865 foreach ($this->edits
as $edit) {
866 if ($edit->type
!= 'copy')
873 * Compute the length of the Longest Common Subsequence (LCS).
875 * This is mostly for diagnostic purposed.
877 * @return int The length of the LCS.
881 foreach ($this->edits
as $edit) {
882 if ($edit->type
== 'copy')
883 $lcs +
= sizeof($edit->orig
);
889 * Get the original set of lines.
891 * This reconstructs the $from_lines parameter passed to the
894 * @return array The original sequence of strings.
899 foreach ($this->edits
as $edit) {
901 array_splice($lines, sizeof($lines), 0, $edit->orig
);
907 * Get the closing set of lines.
909 * This reconstructs the $to_lines parameter passed to the
912 * @return array The sequence of strings.
917 foreach ($this->edits
as $edit) {
919 array_splice($lines, sizeof($lines), 0, $edit->closing
);
925 * Check a Diff for validity.
927 * This is here only for debugging purposes.
929 function _check ($from_lines, $to_lines) {
930 if (serialize($from_lines) != serialize($this->orig()))
931 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
932 if (serialize($to_lines) != serialize($this->closing()))
933 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
935 $rev = $this->reverse();
936 if (serialize($to_lines) != serialize($rev->orig()))
937 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
938 if (serialize($from_lines) != serialize($rev->closing()))
939 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
943 foreach ($this->edits
as $edit) {
944 if ( $prevtype == $edit->type
)
945 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
946 $prevtype = $edit->type
;
950 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
958 class MappedDiff
extends Diff
963 * Computes diff between sequences of strings.
965 * This can be used to compute things like
966 * case-insensitve diffs, or diffs which ignore
967 * changes in white-space.
969 * @param $from_lines array An array of strings.
970 * (Typically these are lines from a file.)
972 * @param $to_lines array An array of strings.
974 * @param $mapped_from_lines array This array should
975 * have the same size number of elements as $from_lines.
976 * The elements in $mapped_from_lines and
977 * $mapped_to_lines are what is actually compared
978 * when computing the diff.
980 * @param $mapped_to_lines array This array should
981 * have the same number of elements as $to_lines.
983 function MappedDiff($from_lines, $to_lines,
984 $mapped_from_lines, $mapped_to_lines) {
986 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
987 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
989 $this->Diff($mapped_from_lines, $mapped_to_lines);
992 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
993 $orig = &$this->edits
[$i]->orig
;
994 if (is_array($orig)) {
995 $orig = array_slice($from_lines, $xi, sizeof($orig));
996 $xi +
= sizeof($orig);
999 $closing = &$this->edits
[$i]->closing
;
1000 if (is_array($closing)) {
1001 $closing = array_slice($to_lines, $yi, sizeof($closing));
1002 $yi +
= sizeof($closing);
1009 * A class to format Diffs
1011 * This class formats the diff in classic diff format.
1012 * It is intended that this class be customized via inheritance,
1013 * to obtain fancier outputs.
1019 * Number of leading context "lines" to preserve.
1021 * This should be left at zero for this class, but subclasses
1022 * may want to set this to other values.
1024 var $leading_context_lines = 0;
1027 * Number of trailing context "lines" to preserve.
1029 * This should be left at zero for this class, but subclasses
1030 * may want to set this to other values.
1032 var $trailing_context_lines = 0;
1037 * @param $diff object A Diff object.
1038 * @return string The formatted output.
1040 function format($diff) {
1046 $nlead = $this->leading_context_lines
;
1047 $ntrail = $this->trailing_context_lines
;
1049 $this->_start_diff();
1051 foreach ($diff->edits
as $edit) {
1052 if ($edit->type
== 'copy') {
1053 if (is_array($block)) {
1054 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1059 $context = array_slice($edit->orig
, 0, $ntrail);
1060 $block[] = new _DiffOp_Copy($context);
1062 $this->_block($x0, $ntrail +
$xi - $x0,
1063 $y0, $ntrail +
$yi - $y0,
1068 $context = $edit->orig
;
1071 if (! is_array($block)) {
1072 $context = array_slice($context, sizeof($context) - $nlead);
1073 $x0 = $xi - sizeof($context);
1074 $y0 = $yi - sizeof($context);
1077 $block[] = new _DiffOp_Copy($context);
1083 $xi +
= sizeof($edit->orig
);
1085 $yi +
= sizeof($edit->closing
);
1088 if (is_array($block))
1089 $this->_block($x0, $xi - $x0,
1093 return $this->_end_diff();
1096 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1097 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1098 foreach ($edits as $edit) {
1099 if ($edit->type
== 'copy')
1100 $this->_context($edit->orig
);
1101 elseif ($edit->type
== 'add')
1102 $this->_added($edit->closing
);
1103 elseif ($edit->type
== 'delete')
1104 $this->_deleted($edit->orig
);
1105 elseif ($edit->type
== 'change')
1106 $this->_changed($edit->orig
, $edit->closing
);
1108 trigger_error('Unknown edit type', E_USER_ERROR
);
1110 $this->_end_block();
1113 function _start_diff() {
1117 function _end_diff() {
1118 $val = ob_get_contents();
1123 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1125 $xbeg .= "," . ($xbeg +
$xlen - 1);
1127 $ybeg .= "," . ($ybeg +
$ylen - 1);
1129 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1132 function _start_block($header) {
1136 function _end_block() {
1139 function _lines($lines, $prefix = ' ') {
1140 foreach ($lines as $line)
1141 echo "$prefix $line\n";
1144 function _context($lines) {
1145 $this->_lines($lines);
1148 function _added($lines) {
1149 $this->_lines($lines, '>');
1151 function _deleted($lines) {
1152 $this->_lines($lines, '<');
1155 function _changed($orig, $closing) {
1156 $this->_deleted($orig);
1158 $this->_added($closing);
1164 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1168 define('NBSP', ' '); // iso-8859-x non-breaking space.
1173 class _HWLDF_WordAccumulator
{
1174 function _HWLDF_WordAccumulator () {
1175 $this->_lines
= array();
1181 function _flushGroup ($new_tag) {
1182 if ($this->_group
!== '') {
1183 if ($this->_tag
== 'mark')
1184 $this->_line
.= '<span class="diffchange">' .
1185 htmlspecialchars ( $this->_group
) . '</span>';
1187 $this->_line
.= htmlspecialchars ( $this->_group
);
1190 $this->_tag
= $new_tag;
1193 function _flushLine ($new_tag) {
1194 $this->_flushGroup($new_tag);
1195 if ($this->_line
!= '')
1196 array_push ( $this->_lines
, $this->_line
);
1198 # make empty lines visible by inserting an NBSP
1199 array_push ( $this->_lines
, NBSP
);
1203 function addWords ($words, $tag = '') {
1204 if ($tag != $this->_tag
)
1205 $this->_flushGroup($tag);
1207 foreach ($words as $word) {
1208 // new-line should only come as first char of word.
1211 if ($word[0] == "\n") {
1212 $this->_flushLine($tag);
1213 $word = substr($word, 1);
1215 assert(!strstr($word, "\n"));
1216 $this->_group
.= $word;
1220 function getLines() {
1221 $this->_flushLine('~done');
1222 return $this->_lines
;
1229 class WordLevelDiff
extends MappedDiff
1231 function WordLevelDiff ($orig_lines, $closing_lines) {
1232 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1233 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1236 $this->MappedDiff($orig_words, $closing_words,
1237 $orig_stripped, $closing_stripped);
1240 function _split($lines) {
1241 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1242 implode("\n", $lines),
1244 return array(array(''), array(''));
1246 return array($m[0], $m[1]);
1250 $orig = new _HWLDF_WordAccumulator
;
1252 foreach ($this->edits
as $edit) {
1253 if ($edit->type
== 'copy')
1254 $orig->addWords($edit->orig
);
1255 elseif ($edit->orig
)
1256 $orig->addWords($edit->orig
, 'mark');
1258 return $orig->getLines();
1261 function closing () {
1262 $closing = new _HWLDF_WordAccumulator
;
1264 foreach ($this->edits
as $edit) {
1265 if ($edit->type
== 'copy')
1266 $closing->addWords($edit->closing
);
1267 elseif ($edit->closing
)
1268 $closing->addWords($edit->closing
, 'mark');
1270 return $closing->getLines();
1275 * Wikipedia Table style diff formatter.
1278 class TableDiffFormatter
extends DiffFormatter
1280 function TableDiffFormatter() {
1281 $this->leading_context_lines
= 2;
1282 $this->trailing_context_lines
= 2;
1285 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1286 $l1 = wfMsg( 'lineno', $xbeg );
1287 $l2 = wfMsg( 'lineno', $ybeg );
1289 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1290 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1294 function _start_block( $header ) {
1296 $wgOut->addHTML( $header );
1299 function _end_block() {
1302 function _lines( $lines, $prefix=' ', $color='white' ) {
1305 # HTML-escape parameter before calling this
1306 function addedLine( $line ) {
1307 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1310 # HTML-escape parameter before calling this
1311 function deletedLine( $line ) {
1312 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1315 # HTML-escape parameter before calling this
1316 function contextLine( $line ) {
1317 return "<td> </td><td class='diff-context'>{$line}</td>";
1320 function emptyLine() {
1321 return '<td colspan="2"> </td>';
1324 function _added( $lines ) {
1326 foreach ($lines as $line) {
1327 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1328 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1332 function _deleted($lines) {
1334 foreach ($lines as $line) {
1335 $wgOut->addHTML( '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1336 $this->emptyLine() . "</tr>\n" );
1340 function _context( $lines ) {
1342 foreach ($lines as $line) {
1343 $wgOut->addHTML( '<tr>' .
1344 $this->contextLine( htmlspecialchars ( $line ) ) .
1345 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1349 function _changed( $orig, $closing ) {
1351 $diff = new WordLevelDiff( $orig, $closing );
1352 $del = $diff->orig();
1353 $add = $diff->closing();
1355 # Notice that WordLevelDiff returns HTML-escaped output.
1356 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1358 while ( $line = array_shift( $del ) ) {
1359 $aline = array_shift( $add );
1360 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1361 $this->addedLine( $aline ) . "</tr>\n" );
1363 foreach ($add as $line) { # If any leftovers
1364 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1365 $this->addedLine( $line ) . "</tr>\n" );