4 class DifferenceEngine
{
5 /* private */ var $mOldid, $mNewid;
6 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
7 /* private */ var $mOldtext, $mNewtext;
8 /* private */ var $mOldUser, $mNewUser;
9 /* private */ var $mOldComment, $mNewComment;
10 /* private */ var $mOldPage, $mNewPage;
11 /* private */ var $mRcidMarkPatrolled;
13 function DifferenceEngine( $old, $new, $rcid = 0 )
16 if ( 'prev' == $new ) {
17 # Show diff between revision $old and the previous one.
18 # Get previous one from DB.
20 $this->mNewid
= intval($old);
21 $dbr =& wfGetDB( DB_SLAVE
);
22 $this->mOldid
= $dbr->selectField( 'old', 'old_id',
23 "old_title='" . $wgTitle->getDBkey() . "'" .
24 ' AND old_namespace=' . $wgTitle->getNamespace() .
25 " AND old_id<{$this->mNewid} ORDER BY old_id DESC" );
27 } elseif ( 'next' == $new ) {
29 # Show diff between revision $old and the previous one.
30 # Get previous one from DB.
32 $this->mOldid
= intval($old);
33 $dbr =& wfGetDB( DB_SLAVE
);
34 $this->mNewid
= $dbr->selectField( 'old', 'old_id',
35 "old_title='" . $wgTitle->getDBkey() . "'" .
36 ' AND old_namespace=' . $wgTitle->getNamespace() .
37 " AND old_id>{$this->mOldid} ORDER BY old_id " );
38 if ( false === $this->mNewid
) {
39 # if no result, NewId points to the newest old revision. The only newer
40 # revision is cur, which is "0".
46 $this->mOldid
= intval($old);
47 $this->mNewid
= intval($new);
49 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
52 function showDiffPage()
54 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
55 $fname = 'DifferenceEngine::showDiffPage';
56 wfProfileIn( $fname );
58 # mOldid is false if the difference engine is called with a "vague" query for
59 # a diff between a version V and its previous version V' AND the version V
60 # is the first version of that article. In that case, V' does not exist.
61 if ( $this->mOldid
=== false ) {
62 $this->showFirstRevision();
63 wfProfileOut( $fname );
67 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
69 $mtext = wfMsg( 'missingarticle', $t );
71 $wgOut->setArticleFlag( false );
72 if ( ! $this->loadText() ) {
73 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
74 $wgOut->addHTML( $mtext );
75 wfProfileOut( $fname );
78 $wgOut->suppressQuickbar();
80 $oldTitle = $this->mOldPage
->getPrefixedText();
81 $newTitle = $this->mNewPage
->getPrefixedText();
82 if( $oldTitle == $newTitle ) {
83 $wgOut->setPageTitle( $newTitle );
85 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
87 $wgOut->setSubtitle( wfMsg( 'difference' ) );
88 $wgOut->setRobotpolicy( 'noindex,follow' );
90 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
93 wfProfileOut( $fname );
97 $sk = $wgUser->getSkin();
98 $talk = $wgLang->getNsText( NS_TALK
);
99 $contribs = wfMsg( 'contribslink' );
101 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
102 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
104 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
105 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
106 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
107 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
108 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
109 'target=' . urlencode($this->mOldUser
) );
110 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
111 'target=' . urlencode($this->mNewUser
) );
112 if ( !$this->mNewid
&& $wgUser->isSysop() ) {
113 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
114 'action=rollback&from=' . urlencode($this->mNewUser
) ) . ']</strong>';
118 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
119 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
121 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
122 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
127 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
128 if ( $this->mNewid
== 0 ) {
131 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
134 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
135 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
136 '<br />' . $prevlink;
137 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
138 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
139 '<br />' . $nextlink . $patrol;
141 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
142 $oldHeader, $newHeader );
143 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
144 $wgOut->addWikiText( $this->mNewtext
);
146 wfProfileOut( $fname );
149 # Show the first revision of an article. Uses normal diff headers in contrast to normal
150 # "old revision" display style.
152 function showFirstRevision()
154 global $wgOut, $wgTitle, $wgUser, $wgLang;
156 $fname = 'DifferenceEngine::showFirstRevision';
157 wfProfileIn( $fname );
160 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
162 # Get article text from the DB
164 if ( ! $this->loadText() ) {
165 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
167 $mtext = wfMsg( 'missingarticle', $t );
168 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
169 $wgOut->addHTML( $mtext );
170 wfProfileOut( $fname );
174 # Check if user is allowed to look at this page. If not, bail out.
176 if ( !( $this->mOldPage
->userCanRead() ) ) {
177 $wgOut->loginToUse();
179 wfProfileOut( $fname );
183 # Prepare the header box
185 $sk = $wgUser->getSkin();
187 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
188 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
189 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
190 'target=' . urlencode($this->mOldUser
) );
191 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
192 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
193 "($uTLink | $contribs)<br />" . $this->mOldComment
.
194 '<br />' . $nextlink. "</div>\n";
196 $wgOut->addHTML( $header );
198 $wgOut->setSubtitle( wfMsg( 'difference' ) );
199 $wgOut->setRobotpolicy( 'noindex,follow' );
202 # Show current revision
204 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
205 $wgOut->addWikiText( $this->mNewtext
);
207 wfProfileOut( $fname );
210 function showDiff( $otext, $ntext, $otitle, $ntitle )
212 global $wgOut, $wgUseExternalDiffEngine;
215 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
217 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
218 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
222 if ( $wgUseExternalDiffEngine ) {
223 # For historical reasons, external diff engine expects
224 # input text to be HTML-escaped already
225 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
226 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
227 dl('php_wikidiff.so');
228 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
230 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
231 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
232 $diffs = new Diff( $ota, $nta );
233 $formatter = new TableDiffFormatter();
234 $formatter->format( $diffs );
236 $wgOut->addHTML( "</table>\n" );
239 # Load the text of the articles to compare. If newid is 0, then compare
240 # the old article in oldid to the current article; if oldid is 0, then
241 # compare the current article to the immediately previous one (ignoring
242 # the value of newid).
246 global $wgTitle, $wgOut, $wgLang;
247 $fname = 'DifferenceEngine::loadText';
249 $dbr =& wfGetDB( DB_SLAVE
);
250 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
251 $wgOut->setArticleFlag( true );
252 $newLink = $wgTitle->getLocalUrl();
253 $this->mPagetitle
= wfMsg( 'currentrev' );
254 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
255 $id = $wgTitle->getArticleID();
257 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
258 array( 'cur_id' => $id ), $fname );
259 if ( $s === false ) {
263 $this->mNewPage
= &$wgTitle;
264 $this->mNewtext
= $s->cur_text
;
265 $this->mNewUser
= $s->cur_user_text
;
266 $this->mNewComment
= $s->cur_comment
;
268 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
269 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
271 if ( $s === false ) {
275 $this->mNewtext
= Article
::getRevisionText( $s );
277 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
278 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
279 $newLink = $wgTitle->getLocalUrl ('oldid=' . $this->mNewid
);
280 $this->mPagetitle
= wfMsg( 'revisionasof', $t );
281 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
282 $this->mNewUser
= $s->old_user_text
;
283 $this->mNewComment
= $s->old_comment
;
285 if ( 0 == $this->mOldid
) {
286 $s = $dbr->getArray( 'old',
287 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
289 'old_namespace' => $this->mNewPage
->getNamespace(),
290 'old_title' => $this->mNewPage
->getDBkey()
291 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
294 $s = $dbr->getArray( 'old',
295 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
296 array( 'old_id' => $this->mOldid
),
300 if ( $s === false ) {
303 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
304 $this->mOldtext
= Article
::getRevisionText( $s );
306 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
307 $oldLink = $this->mOldPage
->getLocalUrl ('oldid=' . $this->mOldid
);
308 $this->mOldtitle
= "<a href='$oldLink'>" . wfMsg( 'revisionasof', $t ) . '</a>';
309 $this->mOldUser
= $s->old_user_text
;
310 $this->mOldComment
= $s->old_comment
;
316 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
318 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
319 // You may copy this code freely under the conditions of the GPL.
322 define('USE_ASSERTS', function_exists('assert'));
330 trigger_error('pure virtual', E_USER_ERROR
);
334 return $this->orig ?
sizeof($this->orig
) : 0;
337 function nclosing() {
338 return $this->closing ?
sizeof($this->closing
) : 0;
342 class _DiffOp_Copy
extends _DiffOp
{
345 function _DiffOp_Copy ($orig, $closing = false) {
346 if (!is_array($closing))
349 $this->closing
= $closing;
353 return new _DiffOp_Copy($this->closing
, $this->orig
);
357 class _DiffOp_Delete
extends _DiffOp
{
358 var $type = 'delete';
360 function _DiffOp_Delete ($lines) {
361 $this->orig
= $lines;
362 $this->closing
= false;
366 return new _DiffOp_Add($this->orig
);
370 class _DiffOp_Add
extends _DiffOp
{
373 function _DiffOp_Add ($lines) {
374 $this->closing
= $lines;
379 return new _DiffOp_Delete($this->closing
);
383 class _DiffOp_Change
extends _DiffOp
{
384 var $type = 'change';
386 function _DiffOp_Change ($orig, $closing) {
388 $this->closing
= $closing;
392 return new _DiffOp_Change($this->closing
, $this->orig
);
398 * Class used internally by Diff to actually compute the diffs.
400 * The algorithm used here is mostly lifted from the perl module
401 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
402 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
404 * More ideas are taken from:
405 * http://www.ics.uci.edu/~eppstein/161/960229.html
407 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
408 * diffutils-2.7, which can be found at:
409 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
411 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
414 * @author Geoffrey T. Dairiki
419 function diff ($from_lines, $to_lines) {
420 $n_from = sizeof($from_lines);
421 $n_to = sizeof($to_lines);
423 $this->xchanged
= $this->ychanged
= array();
424 $this->xv
= $this->yv
= array();
425 $this->xind
= $this->yind
= array();
427 unset($this->in_seq
);
430 // Skip leading common lines.
431 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
432 if ($from_lines[$skip] != $to_lines[$skip])
434 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
436 // Skip trailing common lines.
437 $xi = $n_from; $yi = $n_to;
438 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
439 if ($from_lines[$xi] != $to_lines[$yi])
441 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
444 // Ignore lines which do not exist in both files.
445 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
446 $xhash[$from_lines[$xi]] = 1;
447 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
448 $line = $to_lines[$yi];
449 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
455 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
456 $line = $from_lines[$xi];
457 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
464 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
466 // Merge edits when possible
467 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
468 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
470 // Compute the edit operations.
473 while ($xi < $n_from ||
$yi < $n_to) {
474 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
475 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
477 // Skip matching "snake".
479 while ( $xi < $n_from && $yi < $n_to
480 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
481 $copy[] = $from_lines[$xi++
];
485 $edits[] = new _DiffOp_Copy($copy);
487 // Find deletes & adds.
489 while ($xi < $n_from && $this->xchanged
[$xi])
490 $delete[] = $from_lines[$xi++
];
493 while ($yi < $n_to && $this->ychanged
[$yi])
494 $add[] = $to_lines[$yi++
];
497 $edits[] = new _DiffOp_Change($delete, $add);
499 $edits[] = new _DiffOp_Delete($delete);
501 $edits[] = new _DiffOp_Add($add);
507 /* Divide the Largest Common Subsequence (LCS) of the sequences
508 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
511 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
512 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
513 * sub sequences. The first sub-sequence is contained in [X0, X1),
514 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
515 * that (X0, Y0) == (XOFF, YOFF) and
516 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
518 * This function assumes that the first lines of the specified portions
519 * of the two files do not match, and likewise that the last lines do not
520 * match. The caller must trim matching lines from the beginning and end
521 * of the portions it is going to specify.
523 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
526 if ($xlim - $xoff > $ylim - $yoff) {
527 // Things seems faster (I'm not sure I understand why)
528 // when the shortest sequence in X.
530 list ($xoff, $xlim, $yoff, $ylim)
531 = array( $yoff, $ylim, $xoff, $xlim);
535 for ($i = $ylim - 1; $i >= $yoff; $i--)
536 $ymatches[$this->xv
[$i]][] = $i;
538 for ($i = $ylim - 1; $i >= $yoff; $i--)
539 $ymatches[$this->yv
[$i]][] = $i;
542 $this->seq
[0]= $yoff - 1;
543 $this->in_seq
= array();
546 $numer = $xlim - $xoff +
$nchunks - 1;
548 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
550 for ($i = 0; $i <= $this->lcs
; $i++
)
551 $ymids[$i][$chunk-1] = $this->seq
[$i];
553 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
554 for ( ; $x < $x1; $x++
) {
555 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
556 if (empty($ymatches[$line]))
558 $matches = $ymatches[$line];
560 while (list ($junk, $y) = each($matches))
561 if (empty($this->in_seq
[$y])) {
562 $k = $this->_lcs_pos($y);
563 USE_ASSERTS
&& assert($k > 0);
564 $ymids[$k] = $ymids[$k-1];
567 while (list ($junk, $y) = each($matches)) {
568 if ($y > $this->seq
[$k-1]) {
569 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
570 // Optimization: this is a common case:
571 // next match is just replacing previous match.
572 $this->in_seq
[$this->seq
[$k]] = false;
574 $this->in_seq
[$y] = 1;
576 else if (empty($this->in_seq
[$y])) {
577 $k = $this->_lcs_pos($y);
578 USE_ASSERTS
&& assert($k > 0);
579 $ymids[$k] = $ymids[$k-1];
585 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
586 $ymid = $ymids[$this->lcs
];
587 for ($n = 0; $n < $nchunks - 1; $n++
) {
588 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
590 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
592 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
594 return array($this->lcs
, $seps);
597 function _lcs_pos ($ypos) {
599 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
600 $this->seq
[++
$this->lcs
] = $ypos;
601 $this->in_seq
[$ypos] = 1;
606 while ($beg < $end) {
607 $mid = (int)(($beg +
$end) / 2);
608 if ( $ypos > $this->seq
[$mid] )
614 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
616 $this->in_seq
[$this->seq
[$end]] = false;
617 $this->seq
[$end] = $ypos;
618 $this->in_seq
[$ypos] = 1;
622 /* Find LCS of two sequences.
624 * The results are recorded in the vectors $this->{x,y}changed[], by
625 * storing a 1 in the element for each line that is an insertion
626 * or deletion (ie. is not in the LCS).
628 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
630 * Note that XLIM, YLIM are exclusive bounds.
631 * All line numbers are origin-0 and discarded lines are not counted.
633 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
634 // Slide down the bottom initial diagonal.
635 while ($xoff < $xlim && $yoff < $ylim
636 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
641 // Slide up the top initial diagonal.
642 while ($xlim > $xoff && $ylim > $yoff
643 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
648 if ($xoff == $xlim ||
$yoff == $ylim)
651 // This is ad hoc but seems to work well.
652 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
653 //$nchunks = max(2,min(8,(int)$nchunks));
654 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
656 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
660 // X and Y sequences have no common subsequence:
662 while ($yoff < $ylim)
663 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
664 while ($xoff < $xlim)
665 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
668 // Use the partitions to split this problem into subproblems.
671 while ($pt2 = next($seps)) {
672 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
678 /* Adjust inserts/deletes of identical lines to join changes
679 * as much as possible.
681 * We do something when a run of changed lines include a
682 * line at one end and has an excluded, identical line at the other.
683 * We are free to choose which identical line is included.
684 * `compareseq' usually chooses the one at the beginning,
685 * but usually it is cleaner to consider the following identical line
686 * to be the "change".
688 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
690 function _shift_boundaries ($lines, &$changed, $other_changed) {
694 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
695 $len = sizeof($lines);
696 $other_len = sizeof($other_changed);
700 * Scan forwards to find beginning of another run of changes.
701 * Also keep track of the corresponding point in the other file.
703 * Throughout this code, $i and $j are adjusted together so that
704 * the first $i elements of $changed and the first $j elements
705 * of $other_changed both contain the same number of zeros
707 * Furthermore, $j is always kept so that $j == $other_len or
708 * $other_changed[$j] == false.
710 while ($j < $other_len && $other_changed[$j])
713 while ($i < $len && ! $changed[$i]) {
714 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
716 while ($j < $other_len && $other_changed[$j])
725 // Find the end of this run of changes.
726 while (++
$i < $len && $changed[$i])
731 * Record the length of this run of changes, so that
732 * we can later determine whether the run has grown.
734 $runlength = $i - $start;
737 * Move the changed region back, so long as the
738 * previous unchanged line matches the last changed one.
739 * This merges with previous changed regions.
741 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
742 $changed[--$start] = 1;
743 $changed[--$i] = false;
744 while ($start > 0 && $changed[$start - 1])
746 USE_ASSERTS
&& assert('$j > 0');
747 while ($other_changed[--$j])
749 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
753 * Set CORRESPONDING to the end of the changed run, at the last
754 * point where it corresponds to a changed run in the other file.
755 * CORRESPONDING == LEN means no such point has been found.
757 $corresponding = $j < $other_len ?
$i : $len;
760 * Move the changed region forward, so long as the
761 * first changed line matches the following unchanged one.
762 * This merges with following changed regions.
763 * Do this second, so that if there are no merges,
764 * the changed region is moved forward as far as possible.
766 while ($i < $len && $lines[$start] == $lines[$i]) {
767 $changed[$start++
] = false;
769 while ($i < $len && $changed[$i])
772 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
774 if ($j < $other_len && $other_changed[$j]) {
776 while ($j < $other_len && $other_changed[$j])
780 } while ($runlength != $i - $start);
783 * If possible, move the fully-merged run of changes
784 * back to a corresponding run in the other file.
786 while ($corresponding < $i) {
787 $changed[--$start] = 1;
789 USE_ASSERTS
&& assert('$j > 0');
790 while ($other_changed[--$j])
792 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
799 * Class representing a 'diff' between two sequences of strings.
807 * Computes diff between sequences of strings.
809 * @param $from_lines array An array of strings.
810 * (Typically these are lines from a file.)
811 * @param $to_lines array An array of strings.
813 function Diff($from_lines, $to_lines) {
814 $eng = new _DiffEngine
;
815 $this->edits
= $eng->diff($from_lines, $to_lines);
816 //$this->_check($from_lines, $to_lines);
820 * Compute reversed Diff.
824 * $diff = new Diff($lines1, $lines2);
825 * $rev = $diff->reverse();
826 * @return object A Diff object representing the inverse of the
829 function reverse () {
831 $rev->edits
= array();
832 foreach ($this->edits
as $edit) {
833 $rev->edits
[] = $edit->reverse();
839 * Check for empty diff.
841 * @return bool True iff two sequences were identical.
843 function isEmpty () {
844 foreach ($this->edits
as $edit) {
845 if ($edit->type
!= 'copy')
852 * Compute the length of the Longest Common Subsequence (LCS).
854 * This is mostly for diagnostic purposed.
856 * @return int The length of the LCS.
860 foreach ($this->edits
as $edit) {
861 if ($edit->type
== 'copy')
862 $lcs +
= sizeof($edit->orig
);
868 * Get the original set of lines.
870 * This reconstructs the $from_lines parameter passed to the
873 * @return array The original sequence of strings.
878 foreach ($this->edits
as $edit) {
880 array_splice($lines, sizeof($lines), 0, $edit->orig
);
886 * Get the closing set of lines.
888 * This reconstructs the $to_lines parameter passed to the
891 * @return array The sequence of strings.
896 foreach ($this->edits
as $edit) {
898 array_splice($lines, sizeof($lines), 0, $edit->closing
);
904 * Check a Diff for validity.
906 * This is here only for debugging purposes.
908 function _check ($from_lines, $to_lines) {
909 if (serialize($from_lines) != serialize($this->orig()))
910 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
911 if (serialize($to_lines) != serialize($this->closing()))
912 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
914 $rev = $this->reverse();
915 if (serialize($to_lines) != serialize($rev->orig()))
916 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
917 if (serialize($from_lines) != serialize($rev->closing()))
918 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
922 foreach ($this->edits
as $edit) {
923 if ( $prevtype == $edit->type
)
924 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
925 $prevtype = $edit->type
;
929 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
942 * Computes diff between sequences of strings.
944 * This can be used to compute things like
945 * case-insensitve diffs, or diffs which ignore
946 * changes in white-space.
948 * @param $from_lines array An array of strings.
949 * (Typically these are lines from a file.)
951 * @param $to_lines array An array of strings.
953 * @param $mapped_from_lines array This array should
954 * have the same size number of elements as $from_lines.
955 * The elements in $mapped_from_lines and
956 * $mapped_to_lines are what is actually compared
957 * when computing the diff.
959 * @param $mapped_to_lines array This array should
960 * have the same number of elements as $to_lines.
962 function MappedDiff($from_lines, $to_lines,
963 $mapped_from_lines, $mapped_to_lines) {
965 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
966 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
968 $this->Diff($mapped_from_lines, $mapped_to_lines);
971 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
972 $orig = &$this->edits
[$i]->orig
;
973 if (is_array($orig)) {
974 $orig = array_slice($from_lines, $xi, sizeof($orig));
975 $xi +
= sizeof($orig);
978 $closing = &$this->edits
[$i]->closing
;
979 if (is_array($closing)) {
980 $closing = array_slice($to_lines, $yi, sizeof($closing));
981 $yi +
= sizeof($closing);
988 * A class to format Diffs
990 * This class formats the diff in classic diff format.
991 * It is intended that this class be customized via inheritance,
992 * to obtain fancier outputs.
997 * Number of leading context "lines" to preserve.
999 * This should be left at zero for this class, but subclasses
1000 * may want to set this to other values.
1002 var $leading_context_lines = 0;
1005 * Number of trailing context "lines" to preserve.
1007 * This should be left at zero for this class, but subclasses
1008 * may want to set this to other values.
1010 var $trailing_context_lines = 0;
1015 * @param $diff object A Diff object.
1016 * @return string The formatted output.
1018 function format($diff) {
1024 $nlead = $this->leading_context_lines
;
1025 $ntrail = $this->trailing_context_lines
;
1027 $this->_start_diff();
1029 foreach ($diff->edits
as $edit) {
1030 if ($edit->type
== 'copy') {
1031 if (is_array($block)) {
1032 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1037 $context = array_slice($edit->orig
, 0, $ntrail);
1038 $block[] = new _DiffOp_Copy($context);
1040 $this->_block($x0, $ntrail +
$xi - $x0,
1041 $y0, $ntrail +
$yi - $y0,
1046 $context = $edit->orig
;
1049 if (! is_array($block)) {
1050 $context = array_slice($context, sizeof($context) - $nlead);
1051 $x0 = $xi - sizeof($context);
1052 $y0 = $yi - sizeof($context);
1055 $block[] = new _DiffOp_Copy($context);
1061 $xi +
= sizeof($edit->orig
);
1063 $yi +
= sizeof($edit->closing
);
1066 if (is_array($block))
1067 $this->_block($x0, $xi - $x0,
1071 return $this->_end_diff();
1074 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1075 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1076 foreach ($edits as $edit) {
1077 if ($edit->type
== 'copy')
1078 $this->_context($edit->orig
);
1079 elseif ($edit->type
== 'add')
1080 $this->_added($edit->closing
);
1081 elseif ($edit->type
== 'delete')
1082 $this->_deleted($edit->orig
);
1083 elseif ($edit->type
== 'change')
1084 $this->_changed($edit->orig
, $edit->closing
);
1086 trigger_error('Unknown edit type', E_USER_ERROR
);
1088 $this->_end_block();
1091 function _start_diff() {
1095 function _end_diff() {
1096 $val = ob_get_contents();
1101 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1103 $xbeg .= "," . ($xbeg +
$xlen - 1);
1105 $ybeg .= "," . ($ybeg +
$ylen - 1);
1107 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1110 function _start_block($header) {
1114 function _end_block() {
1117 function _lines($lines, $prefix = ' ') {
1118 foreach ($lines as $line)
1119 echo "$prefix $line\n";
1122 function _context($lines) {
1123 $this->_lines($lines);
1126 function _added($lines) {
1127 $this->_lines($lines, '>');
1129 function _deleted($lines) {
1130 $this->_lines($lines, '<');
1133 function _changed($orig, $closing) {
1134 $this->_deleted($orig);
1136 $this->_added($closing);
1142 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1146 define('NBSP', ' '); // iso-8859-x non-breaking space.
1148 class _HWLDF_WordAccumulator
{
1149 function _HWLDF_WordAccumulator () {
1150 $this->_lines
= array();
1156 function _flushGroup ($new_tag) {
1157 if ($this->_group
!== '') {
1158 if ($this->_tag
== 'mark')
1159 $this->_line
.= '<span class="diffchange">' .
1160 htmlspecialchars ( $this->_group
) . '</span>';
1162 $this->_line
.= htmlspecialchars ( $this->_group
);
1165 $this->_tag
= $new_tag;
1168 function _flushLine ($new_tag) {
1169 $this->_flushGroup($new_tag);
1170 if ($this->_line
!= '')
1171 array_push ( $this->_lines
, $this->_line
);
1173 # make empty lines visible by inserting an NBSP
1174 array_push ( $this->_lines
, NBSP
);
1178 function addWords ($words, $tag = '') {
1179 if ($tag != $this->_tag
)
1180 $this->_flushGroup($tag);
1182 foreach ($words as $word) {
1183 // new-line should only come as first char of word.
1186 if ($word[0] == "\n") {
1187 $this->_flushLine($tag);
1188 $word = substr($word, 1);
1190 assert(!strstr($word, "\n"));
1191 $this->_group
.= $word;
1195 function getLines() {
1196 $this->_flushLine('~done');
1197 return $this->_lines
;
1201 class WordLevelDiff
extends MappedDiff
1203 function WordLevelDiff ($orig_lines, $closing_lines) {
1204 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1205 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1208 $this->MappedDiff($orig_words, $closing_words,
1209 $orig_stripped, $closing_stripped);
1212 function _split($lines) {
1213 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1214 implode("\n", $lines),
1216 return array(array(''), array(''));
1218 return array($m[0], $m[1]);
1222 $orig = new _HWLDF_WordAccumulator
;
1224 foreach ($this->edits
as $edit) {
1225 if ($edit->type
== 'copy')
1226 $orig->addWords($edit->orig
);
1227 elseif ($edit->orig
)
1228 $orig->addWords($edit->orig
, 'mark');
1230 return $orig->getLines();
1233 function closing () {
1234 $closing = new _HWLDF_WordAccumulator
;
1236 foreach ($this->edits
as $edit) {
1237 if ($edit->type
== 'copy')
1238 $closing->addWords($edit->closing
);
1239 elseif ($edit->closing
)
1240 $closing->addWords($edit->closing
, 'mark');
1242 return $closing->getLines();
1247 * Wikipedia Table style diff formatter.
1250 class TableDiffFormatter
extends DiffFormatter
1252 function TableDiffFormatter() {
1253 $this->leading_context_lines
= 2;
1254 $this->trailing_context_lines
= 2;
1257 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1258 $l1 = wfMsg( 'lineno', $xbeg );
1259 $l2 = wfMsg( 'lineno', $ybeg );
1261 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1262 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1266 function _start_block( $header ) {
1268 $wgOut->addHTML( $header );
1271 function _end_block() {
1274 function _lines( $lines, $prefix=' ', $color='white' ) {
1277 # HTML-escape parameter before calling this
1278 function addedLine( $line ) {
1279 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1282 # HTML-escape parameter before calling this
1283 function deletedLine( $line ) {
1284 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1287 # HTML-escape parameter before calling this
1288 function contextLine( $line ) {
1289 return "<td> </td><td class='diff-context'>{$line}</td>";
1292 function emptyLine() {
1293 return '<td colspan="2"> </td>';
1296 function _added( $lines ) {
1298 foreach ($lines as $line) {
1299 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1300 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1304 function _deleted($lines) {
1306 foreach ($lines as $line) {
1307 $wgOut->addHTML( '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1308 $this->emptyLine() . "</tr>\n" );
1312 function _context( $lines ) {
1314 foreach ($lines as $line) {
1315 $wgOut->addHTML( '<tr>' .
1316 $this->contextLine( htmlspecialchars ( $line ) ) .
1317 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1321 function _changed( $orig, $closing ) {
1323 $diff = new WordLevelDiff( $orig, $closing );
1324 $del = $diff->orig();
1325 $add = $diff->closing();
1327 # Notice that WordLevelDiff returns HTML-escaped output.
1328 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1330 while ( $line = array_shift( $del ) ) {
1331 $aline = array_shift( $add );
1332 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1333 $this->addedLine( $aline ) . "</tr>\n" );
1335 foreach ($add as $line) { # If any leftovers
1336 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1337 $this->addedLine( $line ) . "</tr>\n" );