11 class DifferenceEngine
{
12 /* private */ var $mOldid, $mNewid;
13 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
14 /* private */ var $mOldtext, $mNewtext;
15 /* private */ var $mOldUser, $mNewUser;
16 /* private */ var $mOldComment, $mNewComment;
17 /* private */ var $mOldPage, $mNewPage;
18 /* private */ var $mRcidMarkPatrolled;
20 function DifferenceEngine( $old, $new, $rcid = 0 )
23 if ( 'prev' == $new ) {
24 # Show diff between revision $old and the previous one.
25 # Get previous one from DB.
27 $this->mNewid
= intval($old);
28 $dbr =& wfGetDB( DB_SLAVE
);
29 $this->mOldid
= $dbr->selectField( 'old', 'old_id',
30 "old_articleid = " . $wgTitle->getArticleID() .
31 " AND old_id<{$this->mNewid} ORDER BY old_id DESC" );
33 } elseif ( 'next' == $new ) {
35 # Show diff between revision $old and the previous one.
36 # Get previous one from DB.
38 $this->mOldid
= intval($old);
39 $dbr =& wfGetDB( DB_SLAVE
);
40 $this->mNewid
= $dbr->selectField( 'old', 'old_id',
41 "old_articleid = " . $wgTitle->getArticleID() .
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, $wgContLang, $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 = $wgContLang->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 ) {
265 wfDebug( "Unable to load cur_id $id\n" );
269 $this->mNewPage
= &$wgTitle;
270 $this->mNewtext
= $s->cur_text
;
271 $this->mNewUser
= $s->cur_user_text
;
272 $this->mNewComment
= $s->cur_comment
;
274 $s = $dbr->getArray( 'old', array( 'old_articleid', 'old_timestamp', 'old_text',
275 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
277 if ( $s === false ) {
278 wfDebug( "Unable to load old_id {$this->mNewid}\n" );
282 $this->mNewtext
= Article
::getRevisionText( $s );
284 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
285 $this->mNewPage
= Title
::newFromID( $s->old_articleid
);
286 $newLink = $wgTitle->getLocalUrl ('oldid=' . $this->mNewid
);
287 $this->mPagetitle
= wfMsg( 'revisionasof', $t );
288 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
289 $this->mNewUser
= $s->old_user_text
;
290 $this->mNewComment
= $s->old_comment
;
292 if ( 0 == $this->mOldid
) {
293 $s = $dbr->getArray( 'old',
294 array( 'old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
296 'old_articleid' => $this->mNewPage
->getArticleID(),
297 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'articleid_timestamp' )
299 if ( $s === false ) {
300 wfDebug( 'Unable to load ' . $this->mNewPage
->getPrefixedDBkey
. " from old\n" );
304 $s = $dbr->getArray( 'old',
305 array( 'old_timestamp','old_text','old_flags','old_user_text','old_comment'),
306 array( 'old_id' => $this->mOldid
),
309 if ( $s === false ) {
310 wfDebug( "Unable to load old_id {$this->mOldid}\n" );
314 $this->mOldPage
= Title
::newFromID( $wgTitle->getArticleID() );
315 $this->mOldtext
= Article
::getRevisionText( $s );
317 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
318 $oldLink = $this->mOldPage
->getLocalUrl ('oldid=' . $this->mOldid
);
319 $this->mOldtitle
= "<a href='$oldLink'>" . wfMsg( 'revisionasof', $t ) . '</a>';
320 $this->mOldUser
= $s->old_user_text
;
321 $this->mOldComment
= $s->old_comment
;
327 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
329 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
330 // You may copy this code freely under the conditions of the GPL.
333 define('USE_ASSERTS', function_exists('assert'));
345 trigger_error('pure virtual', E_USER_ERROR
);
349 return $this->orig ?
sizeof($this->orig
) : 0;
352 function nclosing() {
353 return $this->closing ?
sizeof($this->closing
) : 0;
361 class _DiffOp_Copy
extends _DiffOp
{
364 function _DiffOp_Copy ($orig, $closing = false) {
365 if (!is_array($closing))
368 $this->closing
= $closing;
372 return new _DiffOp_Copy($this->closing
, $this->orig
);
380 class _DiffOp_Delete
extends _DiffOp
{
381 var $type = 'delete';
383 function _DiffOp_Delete ($lines) {
384 $this->orig
= $lines;
385 $this->closing
= false;
389 return new _DiffOp_Add($this->orig
);
397 class _DiffOp_Add
extends _DiffOp
{
400 function _DiffOp_Add ($lines) {
401 $this->closing
= $lines;
406 return new _DiffOp_Delete($this->closing
);
414 class _DiffOp_Change
extends _DiffOp
{
415 var $type = 'change';
417 function _DiffOp_Change ($orig, $closing) {
419 $this->closing
= $closing;
423 return new _DiffOp_Change($this->closing
, $this->orig
);
429 * Class used internally by Diff to actually compute the diffs.
431 * The algorithm used here is mostly lifted from the perl module
432 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
433 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
435 * More ideas are taken from:
436 * http://www.ics.uci.edu/~eppstein/161/960229.html
438 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
439 * diffutils-2.7, which can be found at:
440 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
442 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
445 * @author Geoffrey T. Dairiki
451 function diff ($from_lines, $to_lines) {
452 $n_from = sizeof($from_lines);
453 $n_to = sizeof($to_lines);
455 $this->xchanged
= $this->ychanged
= array();
456 $this->xv
= $this->yv
= array();
457 $this->xind
= $this->yind
= array();
459 unset($this->in_seq
);
462 // Skip leading common lines.
463 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
464 if ($from_lines[$skip] != $to_lines[$skip])
466 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
468 // Skip trailing common lines.
469 $xi = $n_from; $yi = $n_to;
470 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
471 if ($from_lines[$xi] != $to_lines[$yi])
473 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
476 // Ignore lines which do not exist in both files.
477 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
478 $xhash[$from_lines[$xi]] = 1;
479 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
480 $line = $to_lines[$yi];
481 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
487 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
488 $line = $from_lines[$xi];
489 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
496 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
498 // Merge edits when possible
499 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
500 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
502 // Compute the edit operations.
505 while ($xi < $n_from ||
$yi < $n_to) {
506 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
507 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
509 // Skip matching "snake".
511 while ( $xi < $n_from && $yi < $n_to
512 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
513 $copy[] = $from_lines[$xi++
];
517 $edits[] = new _DiffOp_Copy($copy);
519 // Find deletes & adds.
521 while ($xi < $n_from && $this->xchanged
[$xi])
522 $delete[] = $from_lines[$xi++
];
525 while ($yi < $n_to && $this->ychanged
[$yi])
526 $add[] = $to_lines[$yi++
];
529 $edits[] = new _DiffOp_Change($delete, $add);
531 $edits[] = new _DiffOp_Delete($delete);
533 $edits[] = new _DiffOp_Add($add);
539 /* Divide the Largest Common Subsequence (LCS) of the sequences
540 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
543 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
544 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
545 * sub sequences. The first sub-sequence is contained in [X0, X1),
546 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
547 * that (X0, Y0) == (XOFF, YOFF) and
548 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
550 * This function assumes that the first lines of the specified portions
551 * of the two files do not match, and likewise that the last lines do not
552 * match. The caller must trim matching lines from the beginning and end
553 * of the portions it is going to specify.
555 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
558 if ($xlim - $xoff > $ylim - $yoff) {
559 // Things seems faster (I'm not sure I understand why)
560 // when the shortest sequence in X.
562 list ($xoff, $xlim, $yoff, $ylim)
563 = array( $yoff, $ylim, $xoff, $xlim);
567 for ($i = $ylim - 1; $i >= $yoff; $i--)
568 $ymatches[$this->xv
[$i]][] = $i;
570 for ($i = $ylim - 1; $i >= $yoff; $i--)
571 $ymatches[$this->yv
[$i]][] = $i;
574 $this->seq
[0]= $yoff - 1;
575 $this->in_seq
= array();
578 $numer = $xlim - $xoff +
$nchunks - 1;
580 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
582 for ($i = 0; $i <= $this->lcs
; $i++
)
583 $ymids[$i][$chunk-1] = $this->seq
[$i];
585 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
586 for ( ; $x < $x1; $x++
) {
587 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
588 if (empty($ymatches[$line]))
590 $matches = $ymatches[$line];
592 while (list ($junk, $y) = each($matches))
593 if (empty($this->in_seq
[$y])) {
594 $k = $this->_lcs_pos($y);
595 USE_ASSERTS
&& assert($k > 0);
596 $ymids[$k] = $ymids[$k-1];
599 while (list ($junk, $y) = each($matches)) {
600 if ($y > $this->seq
[$k-1]) {
601 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
602 // Optimization: this is a common case:
603 // next match is just replacing previous match.
604 $this->in_seq
[$this->seq
[$k]] = false;
606 $this->in_seq
[$y] = 1;
608 else if (empty($this->in_seq
[$y])) {
609 $k = $this->_lcs_pos($y);
610 USE_ASSERTS
&& assert($k > 0);
611 $ymids[$k] = $ymids[$k-1];
617 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
618 $ymid = $ymids[$this->lcs
];
619 for ($n = 0; $n < $nchunks - 1; $n++
) {
620 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
622 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
624 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
626 return array($this->lcs
, $seps);
629 function _lcs_pos ($ypos) {
631 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
632 $this->seq
[++
$this->lcs
] = $ypos;
633 $this->in_seq
[$ypos] = 1;
638 while ($beg < $end) {
639 $mid = (int)(($beg +
$end) / 2);
640 if ( $ypos > $this->seq
[$mid] )
646 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
648 $this->in_seq
[$this->seq
[$end]] = false;
649 $this->seq
[$end] = $ypos;
650 $this->in_seq
[$ypos] = 1;
654 /* Find LCS of two sequences.
656 * The results are recorded in the vectors $this->{x,y}changed[], by
657 * storing a 1 in the element for each line that is an insertion
658 * or deletion (ie. is not in the LCS).
660 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
662 * Note that XLIM, YLIM are exclusive bounds.
663 * All line numbers are origin-0 and discarded lines are not counted.
665 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
666 // Slide down the bottom initial diagonal.
667 while ($xoff < $xlim && $yoff < $ylim
668 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
673 // Slide up the top initial diagonal.
674 while ($xlim > $xoff && $ylim > $yoff
675 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
680 if ($xoff == $xlim ||
$yoff == $ylim)
683 // This is ad hoc but seems to work well.
684 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
685 //$nchunks = max(2,min(8,(int)$nchunks));
686 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
688 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
692 // X and Y sequences have no common subsequence:
694 while ($yoff < $ylim)
695 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
696 while ($xoff < $xlim)
697 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
700 // Use the partitions to split this problem into subproblems.
703 while ($pt2 = next($seps)) {
704 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
710 /* Adjust inserts/deletes of identical lines to join changes
711 * as much as possible.
713 * We do something when a run of changed lines include a
714 * line at one end and has an excluded, identical line at the other.
715 * We are free to choose which identical line is included.
716 * `compareseq' usually chooses the one at the beginning,
717 * but usually it is cleaner to consider the following identical line
718 * to be the "change".
720 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
722 function _shift_boundaries ($lines, &$changed, $other_changed) {
726 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
727 $len = sizeof($lines);
728 $other_len = sizeof($other_changed);
732 * Scan forwards to find beginning of another run of changes.
733 * Also keep track of the corresponding point in the other file.
735 * Throughout this code, $i and $j are adjusted together so that
736 * the first $i elements of $changed and the first $j elements
737 * of $other_changed both contain the same number of zeros
739 * Furthermore, $j is always kept so that $j == $other_len or
740 * $other_changed[$j] == false.
742 while ($j < $other_len && $other_changed[$j])
745 while ($i < $len && ! $changed[$i]) {
746 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
748 while ($j < $other_len && $other_changed[$j])
757 // Find the end of this run of changes.
758 while (++
$i < $len && $changed[$i])
763 * Record the length of this run of changes, so that
764 * we can later determine whether the run has grown.
766 $runlength = $i - $start;
769 * Move the changed region back, so long as the
770 * previous unchanged line matches the last changed one.
771 * This merges with previous changed regions.
773 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
774 $changed[--$start] = 1;
775 $changed[--$i] = false;
776 while ($start > 0 && $changed[$start - 1])
778 USE_ASSERTS
&& assert('$j > 0');
779 while ($other_changed[--$j])
781 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
785 * Set CORRESPONDING to the end of the changed run, at the last
786 * point where it corresponds to a changed run in the other file.
787 * CORRESPONDING == LEN means no such point has been found.
789 $corresponding = $j < $other_len ?
$i : $len;
792 * Move the changed region forward, so long as the
793 * first changed line matches the following unchanged one.
794 * This merges with following changed regions.
795 * Do this second, so that if there are no merges,
796 * the changed region is moved forward as far as possible.
798 while ($i < $len && $lines[$start] == $lines[$i]) {
799 $changed[$start++
] = false;
801 while ($i < $len && $changed[$i])
804 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
806 if ($j < $other_len && $other_changed[$j]) {
808 while ($j < $other_len && $other_changed[$j])
812 } while ($runlength != $i - $start);
815 * If possible, move the fully-merged run of changes
816 * back to a corresponding run in the other file.
818 while ($corresponding < $i) {
819 $changed[--$start] = 1;
821 USE_ASSERTS
&& assert('$j > 0');
822 while ($other_changed[--$j])
824 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
831 * Class representing a 'diff' between two sequences of strings.
841 * Computes diff between sequences of strings.
843 * @param $from_lines array An array of strings.
844 * (Typically these are lines from a file.)
845 * @param $to_lines array An array of strings.
847 function Diff($from_lines, $to_lines) {
848 $eng = new _DiffEngine
;
849 $this->edits
= $eng->diff($from_lines, $to_lines);
850 //$this->_check($from_lines, $to_lines);
854 * Compute reversed Diff.
858 * $diff = new Diff($lines1, $lines2);
859 * $rev = $diff->reverse();
860 * @return object A Diff object representing the inverse of the
863 function reverse () {
865 $rev->edits
= array();
866 foreach ($this->edits
as $edit) {
867 $rev->edits
[] = $edit->reverse();
873 * Check for empty diff.
875 * @return bool True iff two sequences were identical.
877 function isEmpty () {
878 foreach ($this->edits
as $edit) {
879 if ($edit->type
!= 'copy')
886 * Compute the length of the Longest Common Subsequence (LCS).
888 * This is mostly for diagnostic purposed.
890 * @return int The length of the LCS.
894 foreach ($this->edits
as $edit) {
895 if ($edit->type
== 'copy')
896 $lcs +
= sizeof($edit->orig
);
902 * Get the original set of lines.
904 * This reconstructs the $from_lines parameter passed to the
907 * @return array The original sequence of strings.
912 foreach ($this->edits
as $edit) {
914 array_splice($lines, sizeof($lines), 0, $edit->orig
);
920 * Get the closing set of lines.
922 * This reconstructs the $to_lines parameter passed to the
925 * @return array The sequence of strings.
930 foreach ($this->edits
as $edit) {
932 array_splice($lines, sizeof($lines), 0, $edit->closing
);
938 * Check a Diff for validity.
940 * This is here only for debugging purposes.
942 function _check ($from_lines, $to_lines) {
943 if (serialize($from_lines) != serialize($this->orig()))
944 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
945 if (serialize($to_lines) != serialize($this->closing()))
946 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
948 $rev = $this->reverse();
949 if (serialize($to_lines) != serialize($rev->orig()))
950 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
951 if (serialize($from_lines) != serialize($rev->closing()))
952 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
956 foreach ($this->edits
as $edit) {
957 if ( $prevtype == $edit->type
)
958 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
959 $prevtype = $edit->type
;
963 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
972 class MappedDiff
extends Diff
977 * Computes diff between sequences of strings.
979 * This can be used to compute things like
980 * case-insensitve diffs, or diffs which ignore
981 * changes in white-space.
983 * @param $from_lines array An array of strings.
984 * (Typically these are lines from a file.)
986 * @param $to_lines array An array of strings.
988 * @param $mapped_from_lines array This array should
989 * have the same size number of elements as $from_lines.
990 * The elements in $mapped_from_lines and
991 * $mapped_to_lines are what is actually compared
992 * when computing the diff.
994 * @param $mapped_to_lines array This array should
995 * have the same number of elements as $to_lines.
997 function MappedDiff($from_lines, $to_lines,
998 $mapped_from_lines, $mapped_to_lines) {
1000 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1001 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1003 $this->Diff($mapped_from_lines, $mapped_to_lines);
1006 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1007 $orig = &$this->edits
[$i]->orig
;
1008 if (is_array($orig)) {
1009 $orig = array_slice($from_lines, $xi, sizeof($orig));
1010 $xi +
= sizeof($orig);
1013 $closing = &$this->edits
[$i]->closing
;
1014 if (is_array($closing)) {
1015 $closing = array_slice($to_lines, $yi, sizeof($closing));
1016 $yi +
= sizeof($closing);
1023 * A class to format Diffs
1025 * This class formats the diff in classic diff format.
1026 * It is intended that this class be customized via inheritance,
1027 * to obtain fancier outputs.
1029 * @package MediaWiki
1034 * Number of leading context "lines" to preserve.
1036 * This should be left at zero for this class, but subclasses
1037 * may want to set this to other values.
1039 var $leading_context_lines = 0;
1042 * Number of trailing context "lines" to preserve.
1044 * This should be left at zero for this class, but subclasses
1045 * may want to set this to other values.
1047 var $trailing_context_lines = 0;
1052 * @param $diff object A Diff object.
1053 * @return string The formatted output.
1055 function format($diff) {
1061 $nlead = $this->leading_context_lines
;
1062 $ntrail = $this->trailing_context_lines
;
1064 $this->_start_diff();
1066 foreach ($diff->edits
as $edit) {
1067 if ($edit->type
== 'copy') {
1068 if (is_array($block)) {
1069 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1074 $context = array_slice($edit->orig
, 0, $ntrail);
1075 $block[] = new _DiffOp_Copy($context);
1077 $this->_block($x0, $ntrail +
$xi - $x0,
1078 $y0, $ntrail +
$yi - $y0,
1083 $context = $edit->orig
;
1086 if (! is_array($block)) {
1087 $context = array_slice($context, sizeof($context) - $nlead);
1088 $x0 = $xi - sizeof($context);
1089 $y0 = $yi - sizeof($context);
1092 $block[] = new _DiffOp_Copy($context);
1098 $xi +
= sizeof($edit->orig
);
1100 $yi +
= sizeof($edit->closing
);
1103 if (is_array($block))
1104 $this->_block($x0, $xi - $x0,
1108 return $this->_end_diff();
1111 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1112 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1113 foreach ($edits as $edit) {
1114 if ($edit->type
== 'copy')
1115 $this->_context($edit->orig
);
1116 elseif ($edit->type
== 'add')
1117 $this->_added($edit->closing
);
1118 elseif ($edit->type
== 'delete')
1119 $this->_deleted($edit->orig
);
1120 elseif ($edit->type
== 'change')
1121 $this->_changed($edit->orig
, $edit->closing
);
1123 trigger_error('Unknown edit type', E_USER_ERROR
);
1125 $this->_end_block();
1128 function _start_diff() {
1132 function _end_diff() {
1133 $val = ob_get_contents();
1138 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1140 $xbeg .= "," . ($xbeg +
$xlen - 1);
1142 $ybeg .= "," . ($ybeg +
$ylen - 1);
1144 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1147 function _start_block($header) {
1151 function _end_block() {
1154 function _lines($lines, $prefix = ' ') {
1155 foreach ($lines as $line)
1156 echo "$prefix $line\n";
1159 function _context($lines) {
1160 $this->_lines($lines);
1163 function _added($lines) {
1164 $this->_lines($lines, '>');
1166 function _deleted($lines) {
1167 $this->_lines($lines, '<');
1170 function _changed($orig, $closing) {
1171 $this->_deleted($orig);
1173 $this->_added($closing);
1179 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1183 define('NBSP', ' '); // iso-8859-x non-breaking space.
1187 * @package MediaWiki
1189 class _HWLDF_WordAccumulator
{
1190 function _HWLDF_WordAccumulator () {
1191 $this->_lines
= array();
1197 function _flushGroup ($new_tag) {
1198 if ($this->_group
!== '') {
1199 if ($this->_tag
== 'mark')
1200 $this->_line
.= '<span class="diffchange">' .
1201 htmlspecialchars ( $this->_group
) . '</span>';
1203 $this->_line
.= htmlspecialchars ( $this->_group
);
1206 $this->_tag
= $new_tag;
1209 function _flushLine ($new_tag) {
1210 $this->_flushGroup($new_tag);
1211 if ($this->_line
!= '')
1212 array_push ( $this->_lines
, $this->_line
);
1214 # make empty lines visible by inserting an NBSP
1215 array_push ( $this->_lines
, NBSP
);
1219 function addWords ($words, $tag = '') {
1220 if ($tag != $this->_tag
)
1221 $this->_flushGroup($tag);
1223 foreach ($words as $word) {
1224 // new-line should only come as first char of word.
1227 if ($word[0] == "\n") {
1228 $this->_flushLine($tag);
1229 $word = substr($word, 1);
1231 assert(!strstr($word, "\n"));
1232 $this->_group
.= $word;
1236 function getLines() {
1237 $this->_flushLine('~done');
1238 return $this->_lines
;
1244 * @package MediaWiki
1246 class WordLevelDiff
extends MappedDiff
1248 function WordLevelDiff ($orig_lines, $closing_lines) {
1249 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1250 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1253 $this->MappedDiff($orig_words, $closing_words,
1254 $orig_stripped, $closing_stripped);
1257 function _split($lines) {
1258 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1259 implode("\n", $lines),
1261 return array(array(''), array(''));
1263 return array($m[0], $m[1]);
1267 $orig = new _HWLDF_WordAccumulator
;
1269 foreach ($this->edits
as $edit) {
1270 if ($edit->type
== 'copy')
1271 $orig->addWords($edit->orig
);
1272 elseif ($edit->orig
)
1273 $orig->addWords($edit->orig
, 'mark');
1275 return $orig->getLines();
1278 function closing () {
1279 $closing = new _HWLDF_WordAccumulator
;
1281 foreach ($this->edits
as $edit) {
1282 if ($edit->type
== 'copy')
1283 $closing->addWords($edit->closing
);
1284 elseif ($edit->closing
)
1285 $closing->addWords($edit->closing
, 'mark');
1287 return $closing->getLines();
1292 * Wikipedia Table style diff formatter.
1294 * @package MediaWiki
1296 class TableDiffFormatter
extends DiffFormatter
1298 function TableDiffFormatter() {
1299 $this->leading_context_lines
= 2;
1300 $this->trailing_context_lines
= 2;
1303 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1304 $l1 = wfMsg( 'lineno', $xbeg );
1305 $l2 = wfMsg( 'lineno', $ybeg );
1307 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1308 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1312 function _start_block( $header ) {
1314 $wgOut->addHTML( $header );
1317 function _end_block() {
1320 function _lines( $lines, $prefix=' ', $color='white' ) {
1323 # HTML-escape parameter before calling this
1324 function addedLine( $line ) {
1325 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1328 # HTML-escape parameter before calling this
1329 function deletedLine( $line ) {
1330 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1333 # HTML-escape parameter before calling this
1334 function contextLine( $line ) {
1335 return "<td> </td><td class='diff-context'>{$line}</td>";
1338 function emptyLine() {
1339 return '<td colspan="2"> </td>';
1342 function _added( $lines ) {
1344 foreach ($lines as $line) {
1345 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1346 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1350 function _deleted($lines) {
1352 foreach ($lines as $line) {
1353 $wgOut->addHTML( '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1354 $this->emptyLine() . "</tr>\n" );
1358 function _context( $lines ) {
1360 foreach ($lines as $line) {
1361 $wgOut->addHTML( '<tr>' .
1362 $this->contextLine( htmlspecialchars ( $line ) ) .
1363 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1367 function _changed( $orig, $closing ) {
1369 $diff = new WordLevelDiff( $orig, $closing );
1370 $del = $diff->orig();
1371 $add = $diff->closing();
1373 # Notice that WordLevelDiff returns HTML-escaped output.
1374 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1376 while ( $line = array_shift( $del ) ) {
1377 $aline = array_shift( $add );
1378 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1379 $this->addedLine( $aline ) . "</tr>\n" );
1381 foreach ($add as $line) { # If any leftovers
1382 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1383 $this->addedLine( $line ) . "</tr>\n" );