5 * @subpackage DifferenceEngine
12 class DifferenceEngine
{
13 /* private */ var $mOldid, $mNewid;
14 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
15 /* private */ var $mOldtext, $mNewtext;
16 /* private */ var $mOldUser, $mNewUser;
17 /* private */ var $mOldComment, $mNewComment;
18 /* private */ var $mOldPage, $mNewPage;
19 /* private */ var $mRcidMarkPatrolled;
21 function DifferenceEngine( $old, $new, $rcid = 0 )
24 if ( 'prev' == $new ) {
25 # Show diff between revision $old and the previous one.
26 # Get previous one from DB.
28 $this->mNewid
= intval($old);
30 $this->mOldid
= $wgTitle->getPreviousRevisionID( $this->mNewid
);
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 $this->mNewid
= $wgTitle->getNextRevisionID( $this->mOldid
);
39 if ( false === $this->mNewid
) {
40 # if no result, NewId points to the newest old revision. The only newer
41 # revision is cur, which is "0".
47 $this->mOldid
= intval($old);
48 $this->mNewid
= intval($new);
50 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
53 function showDiffPage()
55 global $wgUser, $wgTitle, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
56 $fname = 'DifferenceEngine::showDiffPage';
57 wfProfileIn( $fname );
59 # mOldid is false if the difference engine is called with a "vague" query for
60 # a diff between a version V and its previous version V' AND the version V
61 # is the first version of that article. In that case, V' does not exist.
62 if ( $this->mOldid
=== false ) {
63 $this->showFirstRevision();
64 wfProfileOut( $fname );
68 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
70 $mtext = wfMsg( 'missingarticle', $t );
72 $wgOut->setArticleFlag( false );
73 if ( ! $this->loadText() ) {
74 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
75 $wgOut->addHTML( $mtext );
76 wfProfileOut( $fname );
79 $wgOut->suppressQuickbar();
81 $oldTitle = $this->mOldPage
->getPrefixedText();
82 $newTitle = $this->mNewPage
->getPrefixedText();
83 if( $oldTitle == $newTitle ) {
84 $wgOut->setPageTitle( $newTitle );
86 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
88 $wgOut->setSubtitle( wfMsg( 'difference' ) );
89 $wgOut->setRobotpolicy( 'noindex,follow' );
91 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
94 wfProfileOut( $fname );
98 $sk = $wgUser->getSkin();
99 $talk = $wgContLang->getNsText( NS_TALK
);
100 $contribs = wfMsg( 'contribslink' );
102 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
103 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
105 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
106 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
107 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
108 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
109 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
110 'target=' . urlencode($this->mOldUser
) );
111 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
112 'target=' . urlencode($this->mNewUser
) );
113 if ( !$this->mNewid
&& $wgUser->isAllowed('rollback') ) {
114 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
115 'action=rollback&from=' . urlencode($this->mNewUser
) ) . ']</strong>';
119 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
120 ( $wgUser->isAllowed('rollback') ||
!$wgOnlySysopsCanPatrol ) )
122 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
123 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
128 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
129 if ( $this->mNewid
== 0 ) {
132 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
135 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
136 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
137 '<br />' . $prevlink;
138 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
139 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
140 '<br />' . $nextlink . $patrol;
142 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
143 $oldHeader, $newHeader );
144 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
145 $wgOut->addWikiText( $this->mNewtext
);
147 wfProfileOut( $fname );
150 # Show the first revision of an article. Uses normal diff headers in contrast to normal
151 # "old revision" display style.
153 function showFirstRevision()
155 global $wgOut, $wgTitle, $wgUser, $wgLang;
157 $fname = 'DifferenceEngine::showFirstRevision';
158 wfProfileIn( $fname );
161 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
163 # Get article text from the DB
165 if ( ! $this->loadText() ) {
166 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
168 $mtext = wfMsg( 'missingarticle', $t );
169 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
170 $wgOut->addHTML( $mtext );
171 wfProfileOut( $fname );
175 # Check if user is allowed to look at this page. If not, bail out.
177 if ( !( $this->mOldPage
->userCanRead() ) ) {
178 $wgOut->loginToUse();
180 wfProfileOut( $fname );
184 # Prepare the header box
186 $sk = $wgUser->getSkin();
188 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
189 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
190 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
191 'target=' . urlencode($this->mOldUser
) );
192 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
193 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
194 "($uTLink | $contribs)<br />" . $this->mOldComment
.
195 '<br />' . $nextlink. "</div>\n";
197 $wgOut->addHTML( $header );
199 $wgOut->setSubtitle( wfMsg( 'difference' ) );
200 $wgOut->setRobotpolicy( 'noindex,follow' );
203 # Show current revision
205 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
206 $wgOut->addWikiText( $this->mNewtext
);
208 wfProfileOut( $fname );
211 function showDiff( $otext, $ntext, $otitle, $ntitle )
214 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
217 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
218 global $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 if( !function_exists( 'wikidiff_do_diff' ) ) {
233 dl('php_wikidiff.so');
235 $out .= wikidiff_do_diff( $otext, $ntext, 2 );
237 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
238 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
239 $diffs =& new Diff( $ota, $nta );
240 $formatter =& new TableDiffFormatter();
241 $out .= $formatter->format( $diffs );
243 $out .= "</table>\n";
247 # Load the text of the articles to compare. If newid is 0, then compare
248 # the old article in oldid to the current article; if oldid is 0, then
249 # compare the current article to the immediately previous one (ignoring
250 # the value of newid).
254 global $wgTitle, $wgOut, $wgLang;
255 $fname = 'DifferenceEngine::loadText';
257 $dbr =& wfGetDB( DB_SLAVE
);
258 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
259 $wgOut->setArticleFlag( true );
260 $newLink = $wgTitle->escapeLocalUrl();
261 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
262 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
263 $id = $wgTitle->getArticleID();
265 $s = $dbr->selectRow( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
266 array( 'cur_id' => $id ), $fname );
267 if ( $s === false ) {
268 wfDebug( "Unable to load cur_id $id\n" );
272 $this->mNewPage
= &$wgTitle;
273 $this->mNewtext
= $s->cur_text
;
274 $this->mNewUser
= $s->cur_user_text
;
275 $this->mNewComment
= $s->cur_comment
;
277 $s = $dbr->selectRow( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
278 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
280 if ( $s === false ) {
281 wfDebug( "Unable to load old_id {$this->mNewid}\n" );
285 $this->mNewtext
= Article
::getRevisionText( $s );
287 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
288 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
289 $newLink = $wgTitle->escapeLocalUrl ('oldid=' . $this->mNewid
);
290 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
291 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
292 $this->mNewUser
= $s->old_user_text
;
293 $this->mNewComment
= $s->old_comment
;
295 if ( 0 == $this->mOldid
) {
296 $s = $dbr->selectRow( 'old',
297 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
299 'old_namespace' => $this->mNewPage
->getNamespace(),
300 'old_title' => $this->mNewPage
->getDBkey()
301 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
303 if ( $s === false ) {
304 wfDebug( 'Unable to load ' . $this->mNewPage
->getPrefixedDBkey() . " from old\n" );
308 $s = $dbr->selectRow( 'old',
309 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
310 array( 'old_id' => $this->mOldid
),
313 if ( $s === false ) {
314 wfDebug( "Unable to load old_id {$this->mOldid}\n" );
318 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
319 $this->mOldtext
= Article
::getRevisionText( $s );
321 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
322 $oldLink = $this->mOldPage
->escapeLocalUrl ('oldid=' . $this->mOldid
);
323 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
324 $this->mOldUser
= $s->old_user_text
;
325 $this->mOldComment
= $s->old_comment
;
331 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
333 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
334 // You may copy this code freely under the conditions of the GPL.
337 define('USE_ASSERTS', function_exists('assert'));
349 trigger_error('pure virtual', E_USER_ERROR
);
353 return $this->orig ?
sizeof($this->orig
) : 0;
356 function nclosing() {
357 return $this->closing ?
sizeof($this->closing
) : 0;
365 class _DiffOp_Copy
extends _DiffOp
{
368 function _DiffOp_Copy ($orig, $closing = false) {
369 if (!is_array($closing))
372 $this->closing
= $closing;
376 return new _DiffOp_Copy($this->closing
, $this->orig
);
384 class _DiffOp_Delete
extends _DiffOp
{
385 var $type = 'delete';
387 function _DiffOp_Delete ($lines) {
388 $this->orig
= $lines;
389 $this->closing
= false;
393 return new _DiffOp_Add($this->orig
);
401 class _DiffOp_Add
extends _DiffOp
{
404 function _DiffOp_Add ($lines) {
405 $this->closing
= $lines;
410 return new _DiffOp_Delete($this->closing
);
418 class _DiffOp_Change
extends _DiffOp
{
419 var $type = 'change';
421 function _DiffOp_Change ($orig, $closing) {
423 $this->closing
= $closing;
427 return new _DiffOp_Change($this->closing
, $this->orig
);
433 * Class used internally by Diff to actually compute the diffs.
435 * The algorithm used here is mostly lifted from the perl module
436 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
437 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
439 * More ideas are taken from:
440 * http://www.ics.uci.edu/~eppstein/161/960229.html
442 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
443 * diffutils-2.7, which can be found at:
444 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
446 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
449 * @author Geoffrey T. Dairiki
454 function diff ($from_lines, $to_lines) {
455 $n_from = sizeof($from_lines);
456 $n_to = sizeof($to_lines);
458 $this->xchanged
= $this->ychanged
= array();
459 $this->xv
= $this->yv
= array();
460 $this->xind
= $this->yind
= array();
462 unset($this->in_seq
);
465 // Skip leading common lines.
466 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
467 if ($from_lines[$skip] != $to_lines[$skip])
469 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
471 // Skip trailing common lines.
472 $xi = $n_from; $yi = $n_to;
473 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
474 if ($from_lines[$xi] != $to_lines[$yi])
476 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
479 // Ignore lines which do not exist in both files.
480 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
481 $xhash[$from_lines[$xi]] = 1;
482 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
483 $line = $to_lines[$yi];
484 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
490 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
491 $line = $from_lines[$xi];
492 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
499 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
501 // Merge edits when possible
502 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
503 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
505 // Compute the edit operations.
508 while ($xi < $n_from ||
$yi < $n_to) {
509 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
510 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
512 // Skip matching "snake".
514 while ( $xi < $n_from && $yi < $n_to
515 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
516 $copy[] = $from_lines[$xi++
];
520 $edits[] = new _DiffOp_Copy($copy);
522 // Find deletes & adds.
524 while ($xi < $n_from && $this->xchanged
[$xi])
525 $delete[] = $from_lines[$xi++
];
528 while ($yi < $n_to && $this->ychanged
[$yi])
529 $add[] = $to_lines[$yi++
];
532 $edits[] = new _DiffOp_Change($delete, $add);
534 $edits[] = new _DiffOp_Delete($delete);
536 $edits[] = new _DiffOp_Add($add);
542 /* Divide the Largest Common Subsequence (LCS) of the sequences
543 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
546 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
547 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
548 * sub sequences. The first sub-sequence is contained in [X0, X1),
549 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
550 * that (X0, Y0) == (XOFF, YOFF) and
551 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
553 * This function assumes that the first lines of the specified portions
554 * of the two files do not match, and likewise that the last lines do not
555 * match. The caller must trim matching lines from the beginning and end
556 * of the portions it is going to specify.
558 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
561 if ($xlim - $xoff > $ylim - $yoff) {
562 // Things seems faster (I'm not sure I understand why)
563 // when the shortest sequence in X.
565 list ($xoff, $xlim, $yoff, $ylim)
566 = array( $yoff, $ylim, $xoff, $xlim);
570 for ($i = $ylim - 1; $i >= $yoff; $i--)
571 $ymatches[$this->xv
[$i]][] = $i;
573 for ($i = $ylim - 1; $i >= $yoff; $i--)
574 $ymatches[$this->yv
[$i]][] = $i;
577 $this->seq
[0]= $yoff - 1;
578 $this->in_seq
= array();
581 $numer = $xlim - $xoff +
$nchunks - 1;
583 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
585 for ($i = 0; $i <= $this->lcs
; $i++
)
586 $ymids[$i][$chunk-1] = $this->seq
[$i];
588 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
589 for ( ; $x < $x1; $x++
) {
590 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
591 if (empty($ymatches[$line]))
593 $matches = $ymatches[$line];
595 while (list ($junk, $y) = each($matches))
596 if (empty($this->in_seq
[$y])) {
597 $k = $this->_lcs_pos($y);
598 USE_ASSERTS
&& assert($k > 0);
599 $ymids[$k] = $ymids[$k-1];
602 while (list ($junk, $y) = each($matches)) {
603 if ($y > $this->seq
[$k-1]) {
604 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
605 // Optimization: this is a common case:
606 // next match is just replacing previous match.
607 $this->in_seq
[$this->seq
[$k]] = false;
609 $this->in_seq
[$y] = 1;
611 else if (empty($this->in_seq
[$y])) {
612 $k = $this->_lcs_pos($y);
613 USE_ASSERTS
&& assert($k > 0);
614 $ymids[$k] = $ymids[$k-1];
620 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
621 $ymid = $ymids[$this->lcs
];
622 for ($n = 0; $n < $nchunks - 1; $n++
) {
623 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
625 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
627 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
629 return array($this->lcs
, $seps);
632 function _lcs_pos ($ypos) {
634 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
635 $this->seq
[++
$this->lcs
] = $ypos;
636 $this->in_seq
[$ypos] = 1;
641 while ($beg < $end) {
642 $mid = (int)(($beg +
$end) / 2);
643 if ( $ypos > $this->seq
[$mid] )
649 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
651 $this->in_seq
[$this->seq
[$end]] = false;
652 $this->seq
[$end] = $ypos;
653 $this->in_seq
[$ypos] = 1;
657 /* Find LCS of two sequences.
659 * The results are recorded in the vectors $this->{x,y}changed[], by
660 * storing a 1 in the element for each line that is an insertion
661 * or deletion (ie. is not in the LCS).
663 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
665 * Note that XLIM, YLIM are exclusive bounds.
666 * All line numbers are origin-0 and discarded lines are not counted.
668 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
669 // Slide down the bottom initial diagonal.
670 while ($xoff < $xlim && $yoff < $ylim
671 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
676 // Slide up the top initial diagonal.
677 while ($xlim > $xoff && $ylim > $yoff
678 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
683 if ($xoff == $xlim ||
$yoff == $ylim)
686 // This is ad hoc but seems to work well.
687 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
688 //$nchunks = max(2,min(8,(int)$nchunks));
689 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
691 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
695 // X and Y sequences have no common subsequence:
697 while ($yoff < $ylim)
698 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
699 while ($xoff < $xlim)
700 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
703 // Use the partitions to split this problem into subproblems.
706 while ($pt2 = next($seps)) {
707 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
713 /* Adjust inserts/deletes of identical lines to join changes
714 * as much as possible.
716 * We do something when a run of changed lines include a
717 * line at one end and has an excluded, identical line at the other.
718 * We are free to choose which identical line is included.
719 * `compareseq' usually chooses the one at the beginning,
720 * but usually it is cleaner to consider the following identical line
721 * to be the "change".
723 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
725 function _shift_boundaries ($lines, &$changed, $other_changed) {
729 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
730 $len = sizeof($lines);
731 $other_len = sizeof($other_changed);
735 * Scan forwards to find beginning of another run of changes.
736 * Also keep track of the corresponding point in the other file.
738 * Throughout this code, $i and $j are adjusted together so that
739 * the first $i elements of $changed and the first $j elements
740 * of $other_changed both contain the same number of zeros
742 * Furthermore, $j is always kept so that $j == $other_len or
743 * $other_changed[$j] == false.
745 while ($j < $other_len && $other_changed[$j])
748 while ($i < $len && ! $changed[$i]) {
749 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
751 while ($j < $other_len && $other_changed[$j])
760 // Find the end of this run of changes.
761 while (++
$i < $len && $changed[$i])
766 * Record the length of this run of changes, so that
767 * we can later determine whether the run has grown.
769 $runlength = $i - $start;
772 * Move the changed region back, so long as the
773 * previous unchanged line matches the last changed one.
774 * This merges with previous changed regions.
776 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
777 $changed[--$start] = 1;
778 $changed[--$i] = false;
779 while ($start > 0 && $changed[$start - 1])
781 USE_ASSERTS
&& assert('$j > 0');
782 while ($other_changed[--$j])
784 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
788 * Set CORRESPONDING to the end of the changed run, at the last
789 * point where it corresponds to a changed run in the other file.
790 * CORRESPONDING == LEN means no such point has been found.
792 $corresponding = $j < $other_len ?
$i : $len;
795 * Move the changed region forward, so long as the
796 * first changed line matches the following unchanged one.
797 * This merges with following changed regions.
798 * Do this second, so that if there are no merges,
799 * the changed region is moved forward as far as possible.
801 while ($i < $len && $lines[$start] == $lines[$i]) {
802 $changed[$start++
] = false;
804 while ($i < $len && $changed[$i])
807 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
809 if ($j < $other_len && $other_changed[$j]) {
811 while ($j < $other_len && $other_changed[$j])
815 } while ($runlength != $i - $start);
818 * If possible, move the fully-merged run of changes
819 * back to a corresponding run in the other file.
821 while ($corresponding < $i) {
822 $changed[--$start] = 1;
824 USE_ASSERTS
&& assert('$j > 0');
825 while ($other_changed[--$j])
827 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
834 * Class representing a 'diff' between two sequences of strings.
844 * Computes diff between sequences of strings.
846 * @param $from_lines array An array of strings.
847 * (Typically these are lines from a file.)
848 * @param $to_lines array An array of strings.
850 function Diff($from_lines, $to_lines) {
851 $eng = new _DiffEngine
;
852 $this->edits
= $eng->diff($from_lines, $to_lines);
853 //$this->_check($from_lines, $to_lines);
857 * Compute reversed Diff.
861 * $diff = new Diff($lines1, $lines2);
862 * $rev = $diff->reverse();
863 * @return object A Diff object representing the inverse of the
866 function reverse () {
868 $rev->edits
= array();
869 foreach ($this->edits
as $edit) {
870 $rev->edits
[] = $edit->reverse();
876 * Check for empty diff.
878 * @return bool True iff two sequences were identical.
880 function isEmpty () {
881 foreach ($this->edits
as $edit) {
882 if ($edit->type
!= 'copy')
889 * Compute the length of the Longest Common Subsequence (LCS).
891 * This is mostly for diagnostic purposed.
893 * @return int The length of the LCS.
897 foreach ($this->edits
as $edit) {
898 if ($edit->type
== 'copy')
899 $lcs +
= sizeof($edit->orig
);
905 * Get the original set of lines.
907 * This reconstructs the $from_lines parameter passed to the
910 * @return array The original sequence of strings.
915 foreach ($this->edits
as $edit) {
917 array_splice($lines, sizeof($lines), 0, $edit->orig
);
923 * Get the closing set of lines.
925 * This reconstructs the $to_lines parameter passed to the
928 * @return array The sequence of strings.
933 foreach ($this->edits
as $edit) {
935 array_splice($lines, sizeof($lines), 0, $edit->closing
);
941 * Check a Diff for validity.
943 * This is here only for debugging purposes.
945 function _check ($from_lines, $to_lines) {
946 if (serialize($from_lines) != serialize($this->orig()))
947 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
948 if (serialize($to_lines) != serialize($this->closing()))
949 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
951 $rev = $this->reverse();
952 if (serialize($to_lines) != serialize($rev->orig()))
953 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
954 if (serialize($from_lines) != serialize($rev->closing()))
955 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
959 foreach ($this->edits
as $edit) {
960 if ( $prevtype == $edit->type
)
961 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
962 $prevtype = $edit->type
;
966 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
975 class MappedDiff
extends Diff
980 * Computes diff between sequences of strings.
982 * This can be used to compute things like
983 * case-insensitve diffs, or diffs which ignore
984 * changes in white-space.
986 * @param $from_lines array An array of strings.
987 * (Typically these are lines from a file.)
989 * @param $to_lines array An array of strings.
991 * @param $mapped_from_lines array This array should
992 * have the same size number of elements as $from_lines.
993 * The elements in $mapped_from_lines and
994 * $mapped_to_lines are what is actually compared
995 * when computing the diff.
997 * @param $mapped_to_lines array This array should
998 * have the same number of elements as $to_lines.
1000 function MappedDiff($from_lines, $to_lines,
1001 $mapped_from_lines, $mapped_to_lines) {
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);
1026 * A class to format Diffs
1028 * This class formats the diff in classic diff format.
1029 * It is intended that this class be customized via inheritance,
1030 * to obtain fancier outputs.
1037 * Number of leading context "lines" to preserve.
1039 * This should be left at zero for this class, but subclasses
1040 * may want to set this to other values.
1042 var $leading_context_lines = 0;
1045 * Number of trailing context "lines" to preserve.
1047 * This should be left at zero for this class, but subclasses
1048 * may want to set this to other values.
1050 var $trailing_context_lines = 0;
1055 * @param $diff object A Diff object.
1056 * @return string The formatted output.
1058 function format($diff) {
1064 $nlead = $this->leading_context_lines
;
1065 $ntrail = $this->trailing_context_lines
;
1067 $this->_start_diff();
1069 foreach ($diff->edits
as $edit) {
1070 if ($edit->type
== 'copy') {
1071 if (is_array($block)) {
1072 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1077 $context = array_slice($edit->orig
, 0, $ntrail);
1078 $block[] = new _DiffOp_Copy($context);
1080 $this->_block($x0, $ntrail +
$xi - $x0,
1081 $y0, $ntrail +
$yi - $y0,
1086 $context = $edit->orig
;
1089 if (! is_array($block)) {
1090 $context = array_slice($context, sizeof($context) - $nlead);
1091 $x0 = $xi - sizeof($context);
1092 $y0 = $yi - sizeof($context);
1095 $block[] = new _DiffOp_Copy($context);
1101 $xi +
= sizeof($edit->orig
);
1103 $yi +
= sizeof($edit->closing
);
1106 if (is_array($block))
1107 $this->_block($x0, $xi - $x0,
1111 return $this->_end_diff();
1114 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1115 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1116 foreach ($edits as $edit) {
1117 if ($edit->type
== 'copy')
1118 $this->_context($edit->orig
);
1119 elseif ($edit->type
== 'add')
1120 $this->_added($edit->closing
);
1121 elseif ($edit->type
== 'delete')
1122 $this->_deleted($edit->orig
);
1123 elseif ($edit->type
== 'change')
1124 $this->_changed($edit->orig
, $edit->closing
);
1126 trigger_error('Unknown edit type', E_USER_ERROR
);
1128 $this->_end_block();
1131 function _start_diff() {
1135 function _end_diff() {
1136 $val = ob_get_contents();
1141 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1143 $xbeg .= "," . ($xbeg +
$xlen - 1);
1145 $ybeg .= "," . ($ybeg +
$ylen - 1);
1147 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1150 function _start_block($header) {
1154 function _end_block() {
1157 function _lines($lines, $prefix = ' ') {
1158 foreach ($lines as $line)
1159 echo "$prefix $line\n";
1162 function _context($lines) {
1163 $this->_lines($lines);
1166 function _added($lines) {
1167 $this->_lines($lines, '>');
1169 function _deleted($lines) {
1170 $this->_lines($lines, '<');
1173 function _changed($orig, $closing) {
1174 $this->_deleted($orig);
1176 $this->_added($closing);
1182 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1186 define('NBSP', ' '); // iso-8859-x non-breaking space.
1192 class _HWLDF_WordAccumulator
{
1193 function _HWLDF_WordAccumulator () {
1194 $this->_lines
= array();
1200 function _flushGroup ($new_tag) {
1201 if ($this->_group
!== '') {
1202 if ($this->_tag
== 'mark')
1203 $this->_line
.= '<span class="diffchange">' .
1204 htmlspecialchars ( $this->_group
) . '</span>';
1206 $this->_line
.= htmlspecialchars ( $this->_group
);
1209 $this->_tag
= $new_tag;
1212 function _flushLine ($new_tag) {
1213 $this->_flushGroup($new_tag);
1214 if ($this->_line
!= '')
1215 array_push ( $this->_lines
, $this->_line
);
1217 # make empty lines visible by inserting an NBSP
1218 array_push ( $this->_lines
, NBSP
);
1222 function addWords ($words, $tag = '') {
1223 if ($tag != $this->_tag
)
1224 $this->_flushGroup($tag);
1226 foreach ($words as $word) {
1227 // new-line should only come as first char of word.
1230 if ($word[0] == "\n") {
1231 $this->_flushLine($tag);
1232 $word = substr($word, 1);
1234 assert(!strstr($word, "\n"));
1235 $this->_group
.= $word;
1239 function getLines() {
1240 $this->_flushLine('~done');
1241 return $this->_lines
;
1249 class WordLevelDiff
extends MappedDiff
1251 function WordLevelDiff ($orig_lines, $closing_lines) {
1252 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1253 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1256 $this->MappedDiff($orig_words, $closing_words,
1257 $orig_stripped, $closing_stripped);
1260 function _split($lines) {
1261 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1262 implode("\n", $lines),
1264 return array(array(''), array(''));
1266 return array($m[0], $m[1]);
1270 $orig = new _HWLDF_WordAccumulator
;
1272 foreach ($this->edits
as $edit) {
1273 if ($edit->type
== 'copy')
1274 $orig->addWords($edit->orig
);
1275 elseif ($edit->orig
)
1276 $orig->addWords($edit->orig
, 'mark');
1278 return $orig->getLines();
1281 function closing () {
1282 $closing = new _HWLDF_WordAccumulator
;
1284 foreach ($this->edits
as $edit) {
1285 if ($edit->type
== 'copy')
1286 $closing->addWords($edit->closing
);
1287 elseif ($edit->closing
)
1288 $closing->addWords($edit->closing
, 'mark');
1290 return $closing->getLines();
1295 * Wikipedia Table style diff formatter.
1299 class TableDiffFormatter
extends DiffFormatter
1301 function TableDiffFormatter() {
1302 $this->leading_context_lines
= 2;
1303 $this->trailing_context_lines
= 2;
1306 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1307 $l1 = wfMsg( 'lineno', $xbeg );
1308 $l2 = wfMsg( 'lineno', $ybeg );
1310 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1311 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1315 function _start_block( $header ) {
1320 function _end_block() {
1323 function _lines( $lines, $prefix=' ', $color='white' ) {
1326 # HTML-escape parameter before calling this
1327 function addedLine( $line ) {
1328 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1331 # HTML-escape parameter before calling this
1332 function deletedLine( $line ) {
1333 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1336 # HTML-escape parameter before calling this
1337 function contextLine( $line ) {
1338 return "<td> </td><td class='diff-context'>{$line}</td>";
1341 function emptyLine() {
1342 return '<td colspan="2"> </td>';
1345 function _added( $lines ) {
1346 foreach ($lines as $line) {
1347 echo '<tr>' . $this->emptyLine() .
1348 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1352 function _deleted($lines) {
1353 foreach ($lines as $line) {
1354 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1355 $this->emptyLine() . "</tr>\n";
1359 function _context( $lines ) {
1360 foreach ($lines as $line) {
1362 $this->contextLine( htmlspecialchars ( $line ) ) .
1363 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1367 function _changed( $orig, $closing ) {
1368 $diff = new WordLevelDiff( $orig, $closing );
1369 $del = $diff->orig();
1370 $add = $diff->closing();
1372 # Notice that WordLevelDiff returns HTML-escaped output.
1373 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1375 while ( $line = array_shift( $del ) ) {
1376 $aline = array_shift( $add );
1377 echo '<tr>' . $this->deletedLine( $line ) .
1378 $this->addedLine( $aline ) . "</tr>\n";
1380 foreach ($add as $line) { # If any leftovers
1381 echo '<tr>' . $this->emptyLine() .
1382 $this->addedLine( $line ) . "</tr>\n";