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, $wgContLang;
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>
226 $otext = $wgContLang->segmentForDiff($otext);
227 $ntext = $wgContLang->segmentForDiff($ntext);
229 if ( $wgUseExternalDiffEngine ) {
230 # For historical reasons, external diff engine expects
231 # input text to be HTML-escaped already
232 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
233 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
234 if( !function_exists( 'wikidiff_do_diff' ) ) {
235 dl('php_wikidiff.so');
237 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
239 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
240 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
241 $diffs =& new Diff( $ota, $nta );
242 $formatter =& new TableDiffFormatter();
243 $difftext = $formatter->format( $diffs );
245 $difftext = $wgContLang->unsegmentForDiff($difftext);
246 $out .= $difftext."</table>\n";
250 # Load the text of the articles to compare. If newid is 0, then compare
251 # the old article in oldid to the current article; if oldid is 0, then
252 # compare the current article to the immediately previous one (ignoring
253 # the value of newid).
257 global $wgTitle, $wgOut, $wgLang;
258 $fname = 'DifferenceEngine::loadText';
260 $dbr =& wfGetDB( DB_SLAVE
);
261 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
262 $wgOut->setArticleFlag( true );
263 $newLink = $wgTitle->escapeLocalUrl();
264 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
265 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
266 $id = $wgTitle->getArticleID();
268 $s = $dbr->selectRow( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
269 array( 'cur_id' => $id ), $fname );
270 if ( $s === false ) {
271 wfDebug( "Unable to load cur_id $id\n" );
275 $this->mNewPage
= &$wgTitle;
276 $this->mNewtext
= $s->cur_text
;
277 $this->mNewUser
= $s->cur_user_text
;
278 $this->mNewComment
= $s->cur_comment
;
280 $s = $dbr->selectRow( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
281 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
283 if ( $s === false ) {
284 wfDebug( "Unable to load old_id {$this->mNewid}\n" );
288 $this->mNewtext
= Article
::getRevisionText( $s );
290 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
291 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
292 $newLink = $wgTitle->escapeLocalUrl ('oldid=' . $this->mNewid
);
293 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
294 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
295 $this->mNewUser
= $s->old_user_text
;
296 $this->mNewComment
= $s->old_comment
;
298 if ( 0 == $this->mOldid
) {
299 $s = $dbr->selectRow( 'old',
300 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
302 'old_namespace' => $this->mNewPage
->getNamespace(),
303 'old_title' => $this->mNewPage
->getDBkey()
304 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
306 if ( $s === false ) {
307 wfDebug( 'Unable to load ' . $this->mNewPage
->getPrefixedDBkey() . " from old\n" );
311 $s = $dbr->selectRow( 'old',
312 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
313 array( 'old_id' => $this->mOldid
),
316 if ( $s === false ) {
317 wfDebug( "Unable to load old_id {$this->mOldid}\n" );
321 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
322 $this->mOldtext
= Article
::getRevisionText( $s );
324 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
325 $oldLink = $this->mOldPage
->escapeLocalUrl ('oldid=' . $this->mOldid
);
326 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
327 $this->mOldUser
= $s->old_user_text
;
328 $this->mOldComment
= $s->old_comment
;
334 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
336 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
337 // You may copy this code freely under the conditions of the GPL.
340 define('USE_ASSERTS', function_exists('assert'));
352 trigger_error('pure virtual', E_USER_ERROR
);
356 return $this->orig ?
sizeof($this->orig
) : 0;
359 function nclosing() {
360 return $this->closing ?
sizeof($this->closing
) : 0;
368 class _DiffOp_Copy
extends _DiffOp
{
371 function _DiffOp_Copy ($orig, $closing = false) {
372 if (!is_array($closing))
375 $this->closing
= $closing;
379 return new _DiffOp_Copy($this->closing
, $this->orig
);
387 class _DiffOp_Delete
extends _DiffOp
{
388 var $type = 'delete';
390 function _DiffOp_Delete ($lines) {
391 $this->orig
= $lines;
392 $this->closing
= false;
396 return new _DiffOp_Add($this->orig
);
404 class _DiffOp_Add
extends _DiffOp
{
407 function _DiffOp_Add ($lines) {
408 $this->closing
= $lines;
413 return new _DiffOp_Delete($this->closing
);
421 class _DiffOp_Change
extends _DiffOp
{
422 var $type = 'change';
424 function _DiffOp_Change ($orig, $closing) {
426 $this->closing
= $closing;
430 return new _DiffOp_Change($this->closing
, $this->orig
);
436 * Class used internally by Diff to actually compute the diffs.
438 * The algorithm used here is mostly lifted from the perl module
439 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
440 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
442 * More ideas are taken from:
443 * http://www.ics.uci.edu/~eppstein/161/960229.html
445 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
446 * diffutils-2.7, which can be found at:
447 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
449 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
452 * @author Geoffrey T. Dairiki
457 function diff ($from_lines, $to_lines) {
458 $fname = '_DiffEngine::diff';
459 wfProfileIn( $fname );
461 $n_from = sizeof($from_lines);
462 $n_to = sizeof($to_lines);
464 $this->xchanged
= $this->ychanged
= array();
465 $this->xv
= $this->yv
= array();
466 $this->xind
= $this->yind
= array();
468 unset($this->in_seq
);
471 // Skip leading common lines.
472 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
473 if ($from_lines[$skip] != $to_lines[$skip])
475 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
477 // Skip trailing common lines.
478 $xi = $n_from; $yi = $n_to;
479 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
480 if ($from_lines[$xi] != $to_lines[$yi])
482 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
485 // Ignore lines which do not exist in both files.
486 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
487 $xhash[$from_lines[$xi]] = 1;
488 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
489 $line = $to_lines[$yi];
490 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
496 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
497 $line = $from_lines[$xi];
498 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
505 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
507 // Merge edits when possible
508 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
509 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
511 // Compute the edit operations.
514 while ($xi < $n_from ||
$yi < $n_to) {
515 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
516 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
518 // Skip matching "snake".
520 while ( $xi < $n_from && $yi < $n_to
521 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
522 $copy[] = $from_lines[$xi++
];
526 $edits[] = new _DiffOp_Copy($copy);
528 // Find deletes & adds.
530 while ($xi < $n_from && $this->xchanged
[$xi])
531 $delete[] = $from_lines[$xi++
];
534 while ($yi < $n_to && $this->ychanged
[$yi])
535 $add[] = $to_lines[$yi++
];
538 $edits[] = new _DiffOp_Change($delete, $add);
540 $edits[] = new _DiffOp_Delete($delete);
542 $edits[] = new _DiffOp_Add($add);
544 wfProfileOut( $fname );
549 /* Divide the Largest Common Subsequence (LCS) of the sequences
550 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
553 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
554 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
555 * sub sequences. The first sub-sequence is contained in [X0, X1),
556 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
557 * that (X0, Y0) == (XOFF, YOFF) and
558 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
560 * This function assumes that the first lines of the specified portions
561 * of the two files do not match, and likewise that the last lines do not
562 * match. The caller must trim matching lines from the beginning and end
563 * of the portions it is going to specify.
565 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
566 $fname = '_DiffEngine::_diag';
567 wfProfileIn( $fname );
570 if ($xlim - $xoff > $ylim - $yoff) {
571 // Things seems faster (I'm not sure I understand why)
572 // when the shortest sequence in X.
574 list ($xoff, $xlim, $yoff, $ylim)
575 = array( $yoff, $ylim, $xoff, $xlim);
579 for ($i = $ylim - 1; $i >= $yoff; $i--)
580 $ymatches[$this->xv
[$i]][] = $i;
582 for ($i = $ylim - 1; $i >= $yoff; $i--)
583 $ymatches[$this->yv
[$i]][] = $i;
586 $this->seq
[0]= $yoff - 1;
587 $this->in_seq
= array();
590 $numer = $xlim - $xoff +
$nchunks - 1;
592 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
593 wfProfileIn( "$fname-chunk" );
595 for ($i = 0; $i <= $this->lcs
; $i++
)
596 $ymids[$i][$chunk-1] = $this->seq
[$i];
598 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
599 for ( ; $x < $x1; $x++
) {
600 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
601 if (empty($ymatches[$line]))
603 $matches = $ymatches[$line];
605 while (list ($junk, $y) = each($matches))
606 if (empty($this->in_seq
[$y])) {
607 $k = $this->_lcs_pos($y);
608 USE_ASSERTS
&& assert($k > 0);
609 $ymids[$k] = $ymids[$k-1];
612 while (list ($junk, $y) = each($matches)) {
613 if ($y > $this->seq
[$k-1]) {
614 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
615 // Optimization: this is a common case:
616 // next match is just replacing previous match.
617 $this->in_seq
[$this->seq
[$k]] = false;
619 $this->in_seq
[$y] = 1;
620 } else if (empty($this->in_seq
[$y])) {
621 $k = $this->_lcs_pos($y);
622 USE_ASSERTS
&& assert($k > 0);
623 $ymids[$k] = $ymids[$k-1];
627 wfProfileOut( "$fname-chunk" );
630 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
631 $ymid = $ymids[$this->lcs
];
632 for ($n = 0; $n < $nchunks - 1; $n++
) {
633 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
635 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
637 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
639 wfProfileOut( $fname );
640 return array($this->lcs
, $seps);
643 function _lcs_pos ($ypos) {
644 $fname = '_DiffEngine::_lcs_pos';
645 wfProfileIn( $fname );
648 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
649 $this->seq
[++
$this->lcs
] = $ypos;
650 $this->in_seq
[$ypos] = 1;
651 wfProfileOut( $fname );
656 while ($beg < $end) {
657 $mid = (int)(($beg +
$end) / 2);
658 if ( $ypos > $this->seq
[$mid] )
664 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
666 $this->in_seq
[$this->seq
[$end]] = false;
667 $this->seq
[$end] = $ypos;
668 $this->in_seq
[$ypos] = 1;
669 wfProfileOut( $fname );
673 /* Find LCS of two sequences.
675 * The results are recorded in the vectors $this->{x,y}changed[], by
676 * storing a 1 in the element for each line that is an insertion
677 * or deletion (ie. is not in the LCS).
679 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
681 * Note that XLIM, YLIM are exclusive bounds.
682 * All line numbers are origin-0 and discarded lines are not counted.
684 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
685 $fname = '_DiffEngine::_compareseq';
686 wfProfileIn( $fname );
688 // Slide down the bottom initial diagonal.
689 while ($xoff < $xlim && $yoff < $ylim
690 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
695 // Slide up the top initial diagonal.
696 while ($xlim > $xoff && $ylim > $yoff
697 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
702 if ($xoff == $xlim ||
$yoff == $ylim)
705 // This is ad hoc but seems to work well.
706 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
707 //$nchunks = max(2,min(8,(int)$nchunks));
708 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
710 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
714 // X and Y sequences have no common subsequence:
716 while ($yoff < $ylim)
717 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
718 while ($xoff < $xlim)
719 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
721 // Use the partitions to split this problem into subproblems.
724 while ($pt2 = next($seps)) {
725 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
729 wfProfileOut( $fname );
732 /* Adjust inserts/deletes of identical lines to join changes
733 * as much as possible.
735 * We do something when a run of changed lines include a
736 * line at one end and has an excluded, identical line at the other.
737 * We are free to choose which identical line is included.
738 * `compareseq' usually chooses the one at the beginning,
739 * but usually it is cleaner to consider the following identical line
740 * to be the "change".
742 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
744 function _shift_boundaries ($lines, &$changed, $other_changed) {
745 $fname = '_DiffEngine::_shift_boundaries';
746 wfProfileIn( $fname );
750 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
751 $len = sizeof($lines);
752 $other_len = sizeof($other_changed);
756 * Scan forwards to find beginning of another run of changes.
757 * Also keep track of the corresponding point in the other file.
759 * Throughout this code, $i and $j are adjusted together so that
760 * the first $i elements of $changed and the first $j elements
761 * of $other_changed both contain the same number of zeros
763 * Furthermore, $j is always kept so that $j == $other_len or
764 * $other_changed[$j] == false.
766 while ($j < $other_len && $other_changed[$j])
769 while ($i < $len && ! $changed[$i]) {
770 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
772 while ($j < $other_len && $other_changed[$j])
781 // Find the end of this run of changes.
782 while (++
$i < $len && $changed[$i])
787 * Record the length of this run of changes, so that
788 * we can later determine whether the run has grown.
790 $runlength = $i - $start;
793 * Move the changed region back, so long as the
794 * previous unchanged line matches the last changed one.
795 * This merges with previous changed regions.
797 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
798 $changed[--$start] = 1;
799 $changed[--$i] = false;
800 while ($start > 0 && $changed[$start - 1])
802 USE_ASSERTS
&& assert('$j > 0');
803 while ($other_changed[--$j])
805 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
809 * Set CORRESPONDING to the end of the changed run, at the last
810 * point where it corresponds to a changed run in the other file.
811 * CORRESPONDING == LEN means no such point has been found.
813 $corresponding = $j < $other_len ?
$i : $len;
816 * Move the changed region forward, so long as the
817 * first changed line matches the following unchanged one.
818 * This merges with following changed regions.
819 * Do this second, so that if there are no merges,
820 * the changed region is moved forward as far as possible.
822 while ($i < $len && $lines[$start] == $lines[$i]) {
823 $changed[$start++
] = false;
825 while ($i < $len && $changed[$i])
828 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
830 if ($j < $other_len && $other_changed[$j]) {
832 while ($j < $other_len && $other_changed[$j])
836 } while ($runlength != $i - $start);
839 * If possible, move the fully-merged run of changes
840 * back to a corresponding run in the other file.
842 while ($corresponding < $i) {
843 $changed[--$start] = 1;
845 USE_ASSERTS
&& assert('$j > 0');
846 while ($other_changed[--$j])
848 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
851 wfProfileOut( $fname );
856 * Class representing a 'diff' between two sequences of strings.
866 * Computes diff between sequences of strings.
868 * @param $from_lines array An array of strings.
869 * (Typically these are lines from a file.)
870 * @param $to_lines array An array of strings.
872 function Diff($from_lines, $to_lines) {
873 $eng = new _DiffEngine
;
874 $this->edits
= $eng->diff($from_lines, $to_lines);
875 //$this->_check($from_lines, $to_lines);
879 * Compute reversed Diff.
883 * $diff = new Diff($lines1, $lines2);
884 * $rev = $diff->reverse();
885 * @return object A Diff object representing the inverse of the
888 function reverse () {
890 $rev->edits
= array();
891 foreach ($this->edits
as $edit) {
892 $rev->edits
[] = $edit->reverse();
898 * Check for empty diff.
900 * @return bool True iff two sequences were identical.
902 function isEmpty () {
903 foreach ($this->edits
as $edit) {
904 if ($edit->type
!= 'copy')
911 * Compute the length of the Longest Common Subsequence (LCS).
913 * This is mostly for diagnostic purposed.
915 * @return int The length of the LCS.
919 foreach ($this->edits
as $edit) {
920 if ($edit->type
== 'copy')
921 $lcs +
= sizeof($edit->orig
);
927 * Get the original set of lines.
929 * This reconstructs the $from_lines parameter passed to the
932 * @return array The original sequence of strings.
937 foreach ($this->edits
as $edit) {
939 array_splice($lines, sizeof($lines), 0, $edit->orig
);
945 * Get the closing set of lines.
947 * This reconstructs the $to_lines parameter passed to the
950 * @return array The sequence of strings.
955 foreach ($this->edits
as $edit) {
957 array_splice($lines, sizeof($lines), 0, $edit->closing
);
963 * Check a Diff for validity.
965 * This is here only for debugging purposes.
967 function _check ($from_lines, $to_lines) {
968 $fname = 'Diff::_check';
969 wfProfileIn( $fname );
970 if (serialize($from_lines) != serialize($this->orig()))
971 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
972 if (serialize($to_lines) != serialize($this->closing()))
973 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
975 $rev = $this->reverse();
976 if (serialize($to_lines) != serialize($rev->orig()))
977 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
978 if (serialize($from_lines) != serialize($rev->closing()))
979 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
983 foreach ($this->edits
as $edit) {
984 if ( $prevtype == $edit->type
)
985 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
986 $prevtype = $edit->type
;
990 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
991 wfProfileOut( $fname );
1000 class MappedDiff
extends Diff
1005 * Computes diff between sequences of strings.
1007 * This can be used to compute things like
1008 * case-insensitve diffs, or diffs which ignore
1009 * changes in white-space.
1011 * @param $from_lines array An array of strings.
1012 * (Typically these are lines from a file.)
1014 * @param $to_lines array An array of strings.
1016 * @param $mapped_from_lines array This array should
1017 * have the same size number of elements as $from_lines.
1018 * The elements in $mapped_from_lines and
1019 * $mapped_to_lines are what is actually compared
1020 * when computing the diff.
1022 * @param $mapped_to_lines array This array should
1023 * have the same number of elements as $to_lines.
1025 function MappedDiff($from_lines, $to_lines,
1026 $mapped_from_lines, $mapped_to_lines) {
1027 $fname = 'MappedDiff::MappedDiff';
1028 wfProfileIn( $fname );
1030 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1031 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1033 $this->Diff($mapped_from_lines, $mapped_to_lines);
1036 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1037 $orig = &$this->edits
[$i]->orig
;
1038 if (is_array($orig)) {
1039 $orig = array_slice($from_lines, $xi, sizeof($orig));
1040 $xi +
= sizeof($orig);
1043 $closing = &$this->edits
[$i]->closing
;
1044 if (is_array($closing)) {
1045 $closing = array_slice($to_lines, $yi, sizeof($closing));
1046 $yi +
= sizeof($closing);
1049 wfProfileOut( $fname );
1054 * A class to format Diffs
1056 * This class formats the diff in classic diff format.
1057 * It is intended that this class be customized via inheritance,
1058 * to obtain fancier outputs.
1065 * Number of leading context "lines" to preserve.
1067 * This should be left at zero for this class, but subclasses
1068 * may want to set this to other values.
1070 var $leading_context_lines = 0;
1073 * Number of trailing context "lines" to preserve.
1075 * This should be left at zero for this class, but subclasses
1076 * may want to set this to other values.
1078 var $trailing_context_lines = 0;
1083 * @param $diff object A Diff object.
1084 * @return string The formatted output.
1086 function format($diff) {
1087 $fname = 'DiffFormatter::format';
1088 wfProfileIn( $fname );
1094 $nlead = $this->leading_context_lines
;
1095 $ntrail = $this->trailing_context_lines
;
1097 $this->_start_diff();
1099 foreach ($diff->edits
as $edit) {
1100 if ($edit->type
== 'copy') {
1101 if (is_array($block)) {
1102 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1107 $context = array_slice($edit->orig
, 0, $ntrail);
1108 $block[] = new _DiffOp_Copy($context);
1110 $this->_block($x0, $ntrail +
$xi - $x0,
1111 $y0, $ntrail +
$yi - $y0,
1116 $context = $edit->orig
;
1119 if (! is_array($block)) {
1120 $context = array_slice($context, sizeof($context) - $nlead);
1121 $x0 = $xi - sizeof($context);
1122 $y0 = $yi - sizeof($context);
1125 $block[] = new _DiffOp_Copy($context);
1131 $xi +
= sizeof($edit->orig
);
1133 $yi +
= sizeof($edit->closing
);
1136 if (is_array($block))
1137 $this->_block($x0, $xi - $x0,
1141 $end = $this->_end_diff();
1142 wfProfileOut( $fname );
1146 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1147 $fname = 'DiffFormatter::_block';
1148 wfProfileIn( $fname );
1149 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1150 foreach ($edits as $edit) {
1151 if ($edit->type
== 'copy')
1152 $this->_context($edit->orig
);
1153 elseif ($edit->type
== 'add')
1154 $this->_added($edit->closing
);
1155 elseif ($edit->type
== 'delete')
1156 $this->_deleted($edit->orig
);
1157 elseif ($edit->type
== 'change')
1158 $this->_changed($edit->orig
, $edit->closing
);
1160 trigger_error('Unknown edit type', E_USER_ERROR
);
1162 $this->_end_block();
1163 wfProfileOut( $fname );
1166 function _start_diff() {
1170 function _end_diff() {
1171 $val = ob_get_contents();
1176 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1178 $xbeg .= "," . ($xbeg +
$xlen - 1);
1180 $ybeg .= "," . ($ybeg +
$ylen - 1);
1182 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1185 function _start_block($header) {
1189 function _end_block() {
1192 function _lines($lines, $prefix = ' ') {
1193 foreach ($lines as $line)
1194 echo "$prefix $line\n";
1197 function _context($lines) {
1198 $this->_lines($lines);
1201 function _added($lines) {
1202 $this->_lines($lines, '>');
1204 function _deleted($lines) {
1205 $this->_lines($lines, '<');
1208 function _changed($orig, $closing) {
1209 $this->_deleted($orig);
1211 $this->_added($closing);
1217 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1221 define('NBSP', ' '); // iso-8859-x non-breaking space.
1227 class _HWLDF_WordAccumulator
{
1228 function _HWLDF_WordAccumulator () {
1229 $this->_lines
= array();
1235 function _flushGroup ($new_tag) {
1236 if ($this->_group
!== '') {
1237 if ($this->_tag
== 'mark')
1238 $this->_line
.= '<span class="diffchange">' .
1239 htmlspecialchars ( $this->_group
) . '</span>';
1241 $this->_line
.= htmlspecialchars ( $this->_group
);
1244 $this->_tag
= $new_tag;
1247 function _flushLine ($new_tag) {
1248 $this->_flushGroup($new_tag);
1249 if ($this->_line
!= '')
1250 array_push ( $this->_lines
, $this->_line
);
1252 # make empty lines visible by inserting an NBSP
1253 array_push ( $this->_lines
, NBSP
);
1257 function addWords ($words, $tag = '') {
1258 if ($tag != $this->_tag
)
1259 $this->_flushGroup($tag);
1261 foreach ($words as $word) {
1262 // new-line should only come as first char of word.
1265 if ($word[0] == "\n") {
1266 $this->_flushLine($tag);
1267 $word = substr($word, 1);
1269 assert(!strstr($word, "\n"));
1270 $this->_group
.= $word;
1274 function getLines() {
1275 $this->_flushLine('~done');
1276 return $this->_lines
;
1284 class WordLevelDiff
extends MappedDiff
1286 function WordLevelDiff ($orig_lines, $closing_lines) {
1287 $fname = 'WordLevelDiff::WordLevelDiff';
1288 wfProfileIn( $fname );
1290 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1291 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1294 $this->MappedDiff($orig_words, $closing_words,
1295 $orig_stripped, $closing_stripped);
1296 wfProfileOut( $fname );
1299 function _split($lines) {
1300 $fname = 'WordLevelDiff::_split';
1301 wfProfileIn( $fname );
1302 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1303 implode("\n", $lines),
1305 wfProfileOut( $fname );
1306 return array(array(''), array(''));
1308 wfProfileOut( $fname );
1309 return array($m[0], $m[1]);
1313 $fname = 'WordLevelDiff::orig';
1314 wfProfileIn( $fname );
1315 $orig = new _HWLDF_WordAccumulator
;
1317 foreach ($this->edits
as $edit) {
1318 if ($edit->type
== 'copy')
1319 $orig->addWords($edit->orig
);
1320 elseif ($edit->orig
)
1321 $orig->addWords($edit->orig
, 'mark');
1323 $lines = $orig->getLines();
1324 wfProfileOut( $fname );
1328 function closing () {
1329 $fname = 'WordLevelDiff::closing';
1330 wfProfileIn( $fname );
1331 $closing = new _HWLDF_WordAccumulator
;
1333 foreach ($this->edits
as $edit) {
1334 if ($edit->type
== 'copy')
1335 $closing->addWords($edit->closing
);
1336 elseif ($edit->closing
)
1337 $closing->addWords($edit->closing
, 'mark');
1339 $lines = $closing->getLines();
1340 wfProfileOut( $fname );
1346 * Wikipedia Table style diff formatter.
1350 class TableDiffFormatter
extends DiffFormatter
1352 function TableDiffFormatter() {
1353 $this->leading_context_lines
= 2;
1354 $this->trailing_context_lines
= 2;
1357 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1358 $l1 = wfMsg( 'lineno', $xbeg );
1359 $l2 = wfMsg( 'lineno', $ybeg );
1361 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1362 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1366 function _start_block( $header ) {
1371 function _end_block() {
1374 function _lines( $lines, $prefix=' ', $color='white' ) {
1377 # HTML-escape parameter before calling this
1378 function addedLine( $line ) {
1379 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1382 # HTML-escape parameter before calling this
1383 function deletedLine( $line ) {
1384 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1387 # HTML-escape parameter before calling this
1388 function contextLine( $line ) {
1389 return "<td> </td><td class='diff-context'>{$line}</td>";
1392 function emptyLine() {
1393 return '<td colspan="2"> </td>';
1396 function _added( $lines ) {
1397 foreach ($lines as $line) {
1398 echo '<tr>' . $this->emptyLine() .
1399 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1403 function _deleted($lines) {
1404 foreach ($lines as $line) {
1405 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1406 $this->emptyLine() . "</tr>\n";
1410 function _context( $lines ) {
1411 foreach ($lines as $line) {
1413 $this->contextLine( htmlspecialchars ( $line ) ) .
1414 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1418 function _changed( $orig, $closing ) {
1419 $fname = 'TableDiffFormatter::_changed';
1420 wfProfileIn( $fname );
1422 $diff = new WordLevelDiff( $orig, $closing );
1423 $del = $diff->orig();
1424 $add = $diff->closing();
1426 # Notice that WordLevelDiff returns HTML-escaped output.
1427 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1429 while ( $line = array_shift( $del ) ) {
1430 $aline = array_shift( $add );
1431 echo '<tr>' . $this->deletedLine( $line ) .
1432 $this->addedLine( $aline ) . "</tr>\n";
1434 foreach ($add as $line) { # If any leftovers
1435 echo '<tr>' . $this->emptyLine() .
1436 $this->addedLine( $line ) . "</tr>\n";
1438 wfProfileOut( $fname );