5 * @subpackage DifferenceEngine
9 require_once( 'Revision.php' );
15 * @subpackage DifferenceEngine
17 class DifferenceEngine
{
22 var $mOldtitle, $mNewtitle, $mPagetitle;
23 var $mOldtext, $mNewtext;
24 var $mOldUser, $mNewUser;
25 var $mOldComment, $mNewComment;
26 var $mOldPage, $mNewPage;
27 var $mRcidMarkPatrolled;
32 * @param integer $old Old ID we want to show and diff with.
33 * @param string $new Either 'prev' or 'next'.
34 * @param integer $rcid ??? (default 0)
36 function DifferenceEngine( $old, $new, $rcid = 0 ) {
39 if ( 'prev' == $new ) {
40 # Show diff between revision $old and the previous one.
41 # Get previous one from DB.
43 $this->mNewid
= intval($old);
45 $this->mOldid
= $wgTitle->getPreviousRevisionID( $this->mNewid
);
47 } elseif ( 'next' == $new ) {
48 # Show diff between revision $old and the previous one.
49 # Get previous one from DB.
51 $this->mOldid
= intval($old);
52 $this->mNewid
= $wgTitle->getNextRevisionID( $this->mOldid
);
53 if ( false === $this->mNewid
) {
54 # if no result, NewId points to the newest old revision. The only newer
55 # revision is cur, which is "0".
60 $this->mOldid
= intval($old);
61 $this->mNewid
= intval($new);
63 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
66 function showDiffPage() {
67 global $wgUser, $wgTitle, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol,
68 $wgUseExternalEditor, $wgUseRCPatrol;
69 $fname = 'DifferenceEngine::showDiffPage';
70 wfProfileIn( $fname );
72 # If external diffs are enabled both globally and for the user,
73 # we'll use the application/x-external-editor interface to call
74 # an external diff tool like kompare, kdiff3, etc.
75 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
76 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
78 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
79 $url1=$wgTitle->getFullURL("action=raw&oldid=".$this->mOldid
);
80 $url2=$wgTitle->getFullURL("action=raw&oldid=".$this->mNewid
);
81 $special=$wgLang->getNsText(NS_SPECIAL
);
86 Script={$wgServer}{$wgScript}
87 Special namespace={$special}
101 # mOldid is false if the difference engine is called with a "vague" query for
102 # a diff between a version V and its previous version V' AND the version V
103 # is the first version of that article. In that case, V' does not exist.
104 if ( $this->mOldid
=== false ) {
105 $this->showFirstRevision();
106 wfProfileOut( $fname );
110 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
112 $mtext = wfMsg( 'missingarticle', $t );
114 $wgOut->setArticleFlag( false );
115 if ( ! $this->loadText() ) {
116 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
117 $wgOut->addHTML( $mtext );
118 wfProfileOut( $fname );
121 $wgOut->suppressQuickbar();
123 $oldTitle = $this->mOldPage
->getPrefixedText();
124 $newTitle = $this->mNewPage
->getPrefixedText();
125 if( $oldTitle == $newTitle ) {
126 $wgOut->setPageTitle( $newTitle );
128 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
130 $wgOut->setSubtitle( wfMsg( 'difference' ) );
131 $wgOut->setRobotpolicy( 'noindex,follow' );
133 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
134 $wgOut->loginToUse();
136 wfProfileOut( $fname );
140 $sk = $wgUser->getSkin();
141 $talk = $wgContLang->getNsText( NS_TALK
);
142 $contribs = wfMsg( 'contribslink' );
144 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
145 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
147 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
148 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
149 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
150 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
151 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
152 'target=' . urlencode($this->mOldUser
) );
153 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
154 'target=' . urlencode($this->mNewUser
) );
155 if ( !$this->mNewid
&& $wgUser->isAllowed('rollback') ) {
156 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
157 'action=rollback&from=' . urlencode($this->mNewUser
) .
158 '&token=' . urlencode( $wgUser->editToken( array( $wgTitle->getPrefixedText(), $this->mNewUser
) ) ) ) .
163 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isLoggedIn() &&
164 ( $wgUser->isAllowed('rollback') ||
!$wgOnlySysopsCanPatrol ) )
166 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
167 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
172 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
173 if ( $this->mNewid
== 0 ) {
176 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
179 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
180 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
181 '<br />' . $prevlink;
182 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
183 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
184 '<br />' . $nextlink . $patrol;
186 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
187 $oldHeader, $newHeader );
188 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
189 $wgOut->addWikiText( $this->mNewtext
);
191 wfProfileOut( $fname );
195 * Show the first revision of an article. Uses normal diff headers in
196 * contrast to normal "old revision" display style.
198 function showFirstRevision() {
199 global $wgOut, $wgTitle, $wgUser, $wgLang;
201 $fname = 'DifferenceEngine::showFirstRevision';
202 wfProfileIn( $fname );
205 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
207 # Get article text from the DB
209 if ( ! $this->loadText() ) {
210 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
212 $mtext = wfMsg( 'missingarticle', $t );
213 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
214 $wgOut->addHTML( $mtext );
215 wfProfileOut( $fname );
219 # Check if user is allowed to look at this page. If not, bail out.
221 if ( !( $this->mOldPage
->userCanRead() ) ) {
222 $wgOut->loginToUse();
224 wfProfileOut( $fname );
228 # Prepare the header box
230 $sk = $wgUser->getSkin();
232 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
233 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
234 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
235 'target=' . urlencode($this->mOldUser
) );
236 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
237 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
238 "($uTLink | $contribs)<br />" . $this->mOldComment
.
239 '<br />' . $nextlink. "</div>\n";
241 $wgOut->addHTML( $header );
243 $wgOut->setSubtitle( wfMsg( 'difference' ) );
244 $wgOut->setRobotpolicy( 'noindex,follow' );
247 # Show current revision
249 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
250 $wgOut->addWikiText( $this->mNewtext
);
252 wfProfileOut( $fname );
255 function showDiff( $otext, $ntext, $otitle, $ntitle ) {
257 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
260 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
261 global $wgUseExternalDiffEngine, $wgContLang;
263 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
265 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
266 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
269 $otext = $wgContLang->segmentForDiff($otext);
270 $ntext = $wgContLang->segmentForDiff($ntext);
272 if ( $wgUseExternalDiffEngine ) {
273 # For historical reasons, external diff engine expects
274 # input text to be HTML-escaped already
275 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
276 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
277 if( !function_exists( 'wikidiff_do_diff' ) ) {
278 dl('php_wikidiff.so');
280 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
282 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
283 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
284 $diffs =& new Diff( $ota, $nta );
285 $formatter =& new TableDiffFormatter();
286 $difftext = $formatter->format( $diffs );
288 $difftext = $wgContLang->unsegmentForDiff($difftext);
289 $out .= $difftext."</table>\n";
294 * Load the text of the articles to compare. If newid is 0, then compare
295 * the old article in oldid to the current article; if oldid is 0, then
296 * compare the current article to the immediately previous one (ignoring the
299 function loadText() {
300 global $wgTitle, $wgOut, $wgLang;
301 $fname = 'DifferenceEngine::loadText';
303 $dbr =& wfGetDB( DB_SLAVE
);
304 if( $this->mNewid
) {
305 $this->newRev
=& Revision
::newFromId( $this->mNewid
);
307 $this->newRev
=& Revision
::newFromTitle( $wgTitle );
309 if( is_null( $this->newRev
) ) {
313 if( $this->newRev
->isCurrent() ) {
314 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
315 $this->mNewPage
= $wgTitle;
316 $newLink = $this->mNewPage
->escapeLocalUrl();
317 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
319 $this->mNewPage
= $this->newRev
->getTitle();
320 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
321 $t = $wgLang->timeanddate( $this->newRev
->getTimestamp(), true );
322 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
323 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
326 if( $this->mOldid
) {
327 $this->oldRev
=& Revision
::newFromId( $this->mOldid
);
329 $this->oldRev
=& $this->newRev
->getPrevious();
330 $this->mOldid
= $this->oldRev
->getId();
332 if( is_null( $this->oldRev
) ) {
336 $this->mOldPage
= $this->oldRev
->getTitle();
338 $t = $wgLang->timeanddate( $this->oldRev
->getTimestamp(), true );
339 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
340 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
342 $this->mNewUser
= $this->newRev
->getUserText();
343 $this->mNewComment
= $this->newRev
->getComment();
344 $this->mNewtext
= $this->newRev
->getText();
346 $this->mOldUser
= $this->oldRev
->getUserText();
347 $this->mOldComment
= $this->oldRev
->getComment();
348 $this->mOldtext
= $this->oldRev
->getText();
354 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
356 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
357 // You may copy this code freely under the conditions of the GPL.
360 define('USE_ASSERTS', function_exists('assert'));
366 * @subpackage DifferenceEngine
374 trigger_error('pure virtual', E_USER_ERROR
);
378 return $this->orig ?
sizeof($this->orig
) : 0;
381 function nclosing() {
382 return $this->closing ?
sizeof($this->closing
) : 0;
390 * @subpackage DifferenceEngine
392 class _DiffOp_Copy
extends _DiffOp
{
395 function _DiffOp_Copy ($orig, $closing = false) {
396 if (!is_array($closing))
399 $this->closing
= $closing;
403 return new _DiffOp_Copy($this->closing
, $this->orig
);
411 * @subpackage DifferenceEngine
413 class _DiffOp_Delete
extends _DiffOp
{
414 var $type = 'delete';
416 function _DiffOp_Delete ($lines) {
417 $this->orig
= $lines;
418 $this->closing
= false;
422 return new _DiffOp_Add($this->orig
);
430 * @subpackage DifferenceEngine
432 class _DiffOp_Add
extends _DiffOp
{
435 function _DiffOp_Add ($lines) {
436 $this->closing
= $lines;
441 return new _DiffOp_Delete($this->closing
);
449 * @subpackage DifferenceEngine
451 class _DiffOp_Change
extends _DiffOp
{
452 var $type = 'change';
454 function _DiffOp_Change ($orig, $closing) {
456 $this->closing
= $closing;
460 return new _DiffOp_Change($this->closing
, $this->orig
);
466 * Class used internally by Diff to actually compute the diffs.
468 * The algorithm used here is mostly lifted from the perl module
469 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
470 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
472 * More ideas are taken from:
473 * http://www.ics.uci.edu/~eppstein/161/960229.html
475 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
476 * diffutils-2.7, which can be found at:
477 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
479 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
482 * @author Geoffrey T. Dairiki
485 * @subpackage DifferenceEngine
489 function diff ($from_lines, $to_lines) {
490 $fname = '_DiffEngine::diff';
491 wfProfileIn( $fname );
493 $n_from = sizeof($from_lines);
494 $n_to = sizeof($to_lines);
496 $this->xchanged
= $this->ychanged
= array();
497 $this->xv
= $this->yv
= array();
498 $this->xind
= $this->yind
= array();
500 unset($this->in_seq
);
503 // Skip leading common lines.
504 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
505 if ($from_lines[$skip] != $to_lines[$skip])
507 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
509 // Skip trailing common lines.
510 $xi = $n_from; $yi = $n_to;
511 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
512 if ($from_lines[$xi] != $to_lines[$yi])
514 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
517 // Ignore lines which do not exist in both files.
518 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
519 $xhash[$from_lines[$xi]] = 1;
520 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
521 $line = $to_lines[$yi];
522 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
528 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
529 $line = $from_lines[$xi];
530 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
537 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
539 // Merge edits when possible
540 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
541 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
543 // Compute the edit operations.
546 while ($xi < $n_from ||
$yi < $n_to) {
547 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
548 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
550 // Skip matching "snake".
552 while ( $xi < $n_from && $yi < $n_to
553 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
554 $copy[] = $from_lines[$xi++
];
558 $edits[] = new _DiffOp_Copy($copy);
560 // Find deletes & adds.
562 while ($xi < $n_from && $this->xchanged
[$xi])
563 $delete[] = $from_lines[$xi++
];
566 while ($yi < $n_to && $this->ychanged
[$yi])
567 $add[] = $to_lines[$yi++
];
570 $edits[] = new _DiffOp_Change($delete, $add);
572 $edits[] = new _DiffOp_Delete($delete);
574 $edits[] = new _DiffOp_Add($add);
576 wfProfileOut( $fname );
581 /* Divide the Largest Common Subsequence (LCS) of the sequences
582 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
585 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
586 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
587 * sub sequences. The first sub-sequence is contained in [X0, X1),
588 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
589 * that (X0, Y0) == (XOFF, YOFF) and
590 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
592 * This function assumes that the first lines of the specified portions
593 * of the two files do not match, and likewise that the last lines do not
594 * match. The caller must trim matching lines from the beginning and end
595 * of the portions it is going to specify.
597 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
598 $fname = '_DiffEngine::_diag';
599 wfProfileIn( $fname );
602 if ($xlim - $xoff > $ylim - $yoff) {
603 // Things seems faster (I'm not sure I understand why)
604 // when the shortest sequence in X.
606 list ($xoff, $xlim, $yoff, $ylim)
607 = array( $yoff, $ylim, $xoff, $xlim);
611 for ($i = $ylim - 1; $i >= $yoff; $i--)
612 $ymatches[$this->xv
[$i]][] = $i;
614 for ($i = $ylim - 1; $i >= $yoff; $i--)
615 $ymatches[$this->yv
[$i]][] = $i;
618 $this->seq
[0]= $yoff - 1;
619 $this->in_seq
= array();
622 $numer = $xlim - $xoff +
$nchunks - 1;
624 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
625 wfProfileIn( "$fname-chunk" );
627 for ($i = 0; $i <= $this->lcs
; $i++
)
628 $ymids[$i][$chunk-1] = $this->seq
[$i];
630 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
631 for ( ; $x < $x1; $x++
) {
632 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
633 if (empty($ymatches[$line]))
635 $matches = $ymatches[$line];
637 while (list ($junk, $y) = each($matches))
638 if (empty($this->in_seq
[$y])) {
639 $k = $this->_lcs_pos($y);
640 USE_ASSERTS
&& assert($k > 0);
641 $ymids[$k] = $ymids[$k-1];
644 while (list ($junk, $y) = each($matches)) {
645 if ($y > $this->seq
[$k-1]) {
646 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
647 // Optimization: this is a common case:
648 // next match is just replacing previous match.
649 $this->in_seq
[$this->seq
[$k]] = false;
651 $this->in_seq
[$y] = 1;
652 } else if (empty($this->in_seq
[$y])) {
653 $k = $this->_lcs_pos($y);
654 USE_ASSERTS
&& assert($k > 0);
655 $ymids[$k] = $ymids[$k-1];
659 wfProfileOut( "$fname-chunk" );
662 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
663 $ymid = $ymids[$this->lcs
];
664 for ($n = 0; $n < $nchunks - 1; $n++
) {
665 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
667 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
669 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
671 wfProfileOut( $fname );
672 return array($this->lcs
, $seps);
675 function _lcs_pos ($ypos) {
676 $fname = '_DiffEngine::_lcs_pos';
677 wfProfileIn( $fname );
680 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
681 $this->seq
[++
$this->lcs
] = $ypos;
682 $this->in_seq
[$ypos] = 1;
683 wfProfileOut( $fname );
688 while ($beg < $end) {
689 $mid = (int)(($beg +
$end) / 2);
690 if ( $ypos > $this->seq
[$mid] )
696 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
698 $this->in_seq
[$this->seq
[$end]] = false;
699 $this->seq
[$end] = $ypos;
700 $this->in_seq
[$ypos] = 1;
701 wfProfileOut( $fname );
705 /* Find LCS of two sequences.
707 * The results are recorded in the vectors $this->{x,y}changed[], by
708 * storing a 1 in the element for each line that is an insertion
709 * or deletion (ie. is not in the LCS).
711 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
713 * Note that XLIM, YLIM are exclusive bounds.
714 * All line numbers are origin-0 and discarded lines are not counted.
716 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
717 $fname = '_DiffEngine::_compareseq';
718 wfProfileIn( $fname );
720 // Slide down the bottom initial diagonal.
721 while ($xoff < $xlim && $yoff < $ylim
722 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
727 // Slide up the top initial diagonal.
728 while ($xlim > $xoff && $ylim > $yoff
729 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
734 if ($xoff == $xlim ||
$yoff == $ylim)
737 // This is ad hoc but seems to work well.
738 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
739 //$nchunks = max(2,min(8,(int)$nchunks));
740 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
742 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
746 // X and Y sequences have no common subsequence:
748 while ($yoff < $ylim)
749 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
750 while ($xoff < $xlim)
751 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
753 // Use the partitions to split this problem into subproblems.
756 while ($pt2 = next($seps)) {
757 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
761 wfProfileOut( $fname );
764 /* Adjust inserts/deletes of identical lines to join changes
765 * as much as possible.
767 * We do something when a run of changed lines include a
768 * line at one end and has an excluded, identical line at the other.
769 * We are free to choose which identical line is included.
770 * `compareseq' usually chooses the one at the beginning,
771 * but usually it is cleaner to consider the following identical line
772 * to be the "change".
774 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
776 function _shift_boundaries ($lines, &$changed, $other_changed) {
777 $fname = '_DiffEngine::_shift_boundaries';
778 wfProfileIn( $fname );
782 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
783 $len = sizeof($lines);
784 $other_len = sizeof($other_changed);
788 * Scan forwards to find beginning of another run of changes.
789 * Also keep track of the corresponding point in the other file.
791 * Throughout this code, $i and $j are adjusted together so that
792 * the first $i elements of $changed and the first $j elements
793 * of $other_changed both contain the same number of zeros
795 * Furthermore, $j is always kept so that $j == $other_len or
796 * $other_changed[$j] == false.
798 while ($j < $other_len && $other_changed[$j])
801 while ($i < $len && ! $changed[$i]) {
802 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
804 while ($j < $other_len && $other_changed[$j])
813 // Find the end of this run of changes.
814 while (++
$i < $len && $changed[$i])
819 * Record the length of this run of changes, so that
820 * we can later determine whether the run has grown.
822 $runlength = $i - $start;
825 * Move the changed region back, so long as the
826 * previous unchanged line matches the last changed one.
827 * This merges with previous changed regions.
829 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
830 $changed[--$start] = 1;
831 $changed[--$i] = false;
832 while ($start > 0 && $changed[$start - 1])
834 USE_ASSERTS
&& assert('$j > 0');
835 while ($other_changed[--$j])
837 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
841 * Set CORRESPONDING to the end of the changed run, at the last
842 * point where it corresponds to a changed run in the other file.
843 * CORRESPONDING == LEN means no such point has been found.
845 $corresponding = $j < $other_len ?
$i : $len;
848 * Move the changed region forward, so long as the
849 * first changed line matches the following unchanged one.
850 * This merges with following changed regions.
851 * Do this second, so that if there are no merges,
852 * the changed region is moved forward as far as possible.
854 while ($i < $len && $lines[$start] == $lines[$i]) {
855 $changed[$start++
] = false;
857 while ($i < $len && $changed[$i])
860 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
862 if ($j < $other_len && $other_changed[$j]) {
864 while ($j < $other_len && $other_changed[$j])
868 } while ($runlength != $i - $start);
871 * If possible, move the fully-merged run of changes
872 * back to a corresponding run in the other file.
874 while ($corresponding < $i) {
875 $changed[--$start] = 1;
877 USE_ASSERTS
&& assert('$j > 0');
878 while ($other_changed[--$j])
880 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
883 wfProfileOut( $fname );
888 * Class representing a 'diff' between two sequences of strings.
892 * @subpackage DifferenceEngine
900 * Computes diff between sequences of strings.
902 * @param $from_lines array An array of strings.
903 * (Typically these are lines from a file.)
904 * @param $to_lines array An array of strings.
906 function Diff($from_lines, $to_lines) {
907 $eng = new _DiffEngine
;
908 $this->edits
= $eng->diff($from_lines, $to_lines);
909 //$this->_check($from_lines, $to_lines);
913 * Compute reversed Diff.
917 * $diff = new Diff($lines1, $lines2);
918 * $rev = $diff->reverse();
919 * @return object A Diff object representing the inverse of the
922 function reverse () {
924 $rev->edits
= array();
925 foreach ($this->edits
as $edit) {
926 $rev->edits
[] = $edit->reverse();
932 * Check for empty diff.
934 * @return bool True iff two sequences were identical.
936 function isEmpty () {
937 foreach ($this->edits
as $edit) {
938 if ($edit->type
!= 'copy')
945 * Compute the length of the Longest Common Subsequence (LCS).
947 * This is mostly for diagnostic purposed.
949 * @return int The length of the LCS.
953 foreach ($this->edits
as $edit) {
954 if ($edit->type
== 'copy')
955 $lcs +
= sizeof($edit->orig
);
961 * Get the original set of lines.
963 * This reconstructs the $from_lines parameter passed to the
966 * @return array The original sequence of strings.
971 foreach ($this->edits
as $edit) {
973 array_splice($lines, sizeof($lines), 0, $edit->orig
);
979 * Get the closing set of lines.
981 * This reconstructs the $to_lines parameter passed to the
984 * @return array The sequence of strings.
989 foreach ($this->edits
as $edit) {
991 array_splice($lines, sizeof($lines), 0, $edit->closing
);
997 * Check a Diff for validity.
999 * This is here only for debugging purposes.
1001 function _check ($from_lines, $to_lines) {
1002 $fname = 'Diff::_check';
1003 wfProfileIn( $fname );
1004 if (serialize($from_lines) != serialize($this->orig()))
1005 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1006 if (serialize($to_lines) != serialize($this->closing()))
1007 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1009 $rev = $this->reverse();
1010 if (serialize($to_lines) != serialize($rev->orig()))
1011 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1012 if (serialize($from_lines) != serialize($rev->closing()))
1013 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1017 foreach ($this->edits
as $edit) {
1018 if ( $prevtype == $edit->type
)
1019 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1020 $prevtype = $edit->type
;
1023 $lcs = $this->lcs();
1024 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1025 wfProfileOut( $fname );
1033 * @package MediaWiki
1034 * @subpackage DifferenceEngine
1036 class MappedDiff
extends Diff
1041 * Computes diff between sequences of strings.
1043 * This can be used to compute things like
1044 * case-insensitve diffs, or diffs which ignore
1045 * changes in white-space.
1047 * @param $from_lines array An array of strings.
1048 * (Typically these are lines from a file.)
1050 * @param $to_lines array An array of strings.
1052 * @param $mapped_from_lines array This array should
1053 * have the same size number of elements as $from_lines.
1054 * The elements in $mapped_from_lines and
1055 * $mapped_to_lines are what is actually compared
1056 * when computing the diff.
1058 * @param $mapped_to_lines array This array should
1059 * have the same number of elements as $to_lines.
1061 function MappedDiff($from_lines, $to_lines,
1062 $mapped_from_lines, $mapped_to_lines) {
1063 $fname = 'MappedDiff::MappedDiff';
1064 wfProfileIn( $fname );
1066 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1067 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1069 $this->Diff($mapped_from_lines, $mapped_to_lines);
1072 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1073 $orig = &$this->edits
[$i]->orig
;
1074 if (is_array($orig)) {
1075 $orig = array_slice($from_lines, $xi, sizeof($orig));
1076 $xi +
= sizeof($orig);
1079 $closing = &$this->edits
[$i]->closing
;
1080 if (is_array($closing)) {
1081 $closing = array_slice($to_lines, $yi, sizeof($closing));
1082 $yi +
= sizeof($closing);
1085 wfProfileOut( $fname );
1090 * A class to format Diffs
1092 * This class formats the diff in classic diff format.
1093 * It is intended that this class be customized via inheritance,
1094 * to obtain fancier outputs.
1097 * @package MediaWiki
1098 * @subpackage DifferenceEngine
1103 * Number of leading context "lines" to preserve.
1105 * This should be left at zero for this class, but subclasses
1106 * may want to set this to other values.
1108 var $leading_context_lines = 0;
1111 * Number of trailing context "lines" to preserve.
1113 * This should be left at zero for this class, but subclasses
1114 * may want to set this to other values.
1116 var $trailing_context_lines = 0;
1121 * @param $diff object A Diff object.
1122 * @return string The formatted output.
1124 function format($diff) {
1125 $fname = 'DiffFormatter::format';
1126 wfProfileIn( $fname );
1132 $nlead = $this->leading_context_lines
;
1133 $ntrail = $this->trailing_context_lines
;
1135 $this->_start_diff();
1137 foreach ($diff->edits
as $edit) {
1138 if ($edit->type
== 'copy') {
1139 if (is_array($block)) {
1140 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1145 $context = array_slice($edit->orig
, 0, $ntrail);
1146 $block[] = new _DiffOp_Copy($context);
1148 $this->_block($x0, $ntrail +
$xi - $x0,
1149 $y0, $ntrail +
$yi - $y0,
1154 $context = $edit->orig
;
1157 if (! is_array($block)) {
1158 $context = array_slice($context, sizeof($context) - $nlead);
1159 $x0 = $xi - sizeof($context);
1160 $y0 = $yi - sizeof($context);
1163 $block[] = new _DiffOp_Copy($context);
1169 $xi +
= sizeof($edit->orig
);
1171 $yi +
= sizeof($edit->closing
);
1174 if (is_array($block))
1175 $this->_block($x0, $xi - $x0,
1179 $end = $this->_end_diff();
1180 wfProfileOut( $fname );
1184 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1185 $fname = 'DiffFormatter::_block';
1186 wfProfileIn( $fname );
1187 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1188 foreach ($edits as $edit) {
1189 if ($edit->type
== 'copy')
1190 $this->_context($edit->orig
);
1191 elseif ($edit->type
== 'add')
1192 $this->_added($edit->closing
);
1193 elseif ($edit->type
== 'delete')
1194 $this->_deleted($edit->orig
);
1195 elseif ($edit->type
== 'change')
1196 $this->_changed($edit->orig
, $edit->closing
);
1198 trigger_error('Unknown edit type', E_USER_ERROR
);
1200 $this->_end_block();
1201 wfProfileOut( $fname );
1204 function _start_diff() {
1208 function _end_diff() {
1209 $val = ob_get_contents();
1214 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1216 $xbeg .= "," . ($xbeg +
$xlen - 1);
1218 $ybeg .= "," . ($ybeg +
$ylen - 1);
1220 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1223 function _start_block($header) {
1227 function _end_block() {
1230 function _lines($lines, $prefix = ' ') {
1231 foreach ($lines as $line)
1232 echo "$prefix $line\n";
1235 function _context($lines) {
1236 $this->_lines($lines);
1239 function _added($lines) {
1240 $this->_lines($lines, '>');
1242 function _deleted($lines) {
1243 $this->_lines($lines, '<');
1246 function _changed($orig, $closing) {
1247 $this->_deleted($orig);
1249 $this->_added($closing);
1255 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1259 define('NBSP', ' '); // iso-8859-x non-breaking space.
1264 * @package MediaWiki
1265 * @subpackage DifferenceEngine
1267 class _HWLDF_WordAccumulator
{
1268 function _HWLDF_WordAccumulator () {
1269 $this->_lines
= array();
1275 function _flushGroup ($new_tag) {
1276 if ($this->_group
!== '') {
1277 if ($this->_tag
== 'mark')
1278 $this->_line
.= '<span class="diffchange">' .
1279 htmlspecialchars ( $this->_group
) . '</span>';
1281 $this->_line
.= htmlspecialchars ( $this->_group
);
1284 $this->_tag
= $new_tag;
1287 function _flushLine ($new_tag) {
1288 $this->_flushGroup($new_tag);
1289 if ($this->_line
!= '')
1290 array_push ( $this->_lines
, $this->_line
);
1292 # make empty lines visible by inserting an NBSP
1293 array_push ( $this->_lines
, NBSP
);
1297 function addWords ($words, $tag = '') {
1298 if ($tag != $this->_tag
)
1299 $this->_flushGroup($tag);
1301 foreach ($words as $word) {
1302 // new-line should only come as first char of word.
1305 if ($word[0] == "\n") {
1306 $this->_flushLine($tag);
1307 $word = substr($word, 1);
1309 assert(!strstr($word, "\n"));
1310 $this->_group
.= $word;
1314 function getLines() {
1315 $this->_flushLine('~done');
1316 return $this->_lines
;
1323 * @package MediaWiki
1324 * @subpackage DifferenceEngine
1326 class WordLevelDiff
extends MappedDiff
1328 function WordLevelDiff ($orig_lines, $closing_lines) {
1329 $fname = 'WordLevelDiff::WordLevelDiff';
1330 wfProfileIn( $fname );
1332 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1333 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1336 $this->MappedDiff($orig_words, $closing_words,
1337 $orig_stripped, $closing_stripped);
1338 wfProfileOut( $fname );
1341 function _split($lines) {
1342 $fname = 'WordLevelDiff::_split';
1343 wfProfileIn( $fname );
1344 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1345 implode("\n", $lines),
1347 wfProfileOut( $fname );
1348 return array(array(''), array(''));
1350 wfProfileOut( $fname );
1351 return array($m[0], $m[1]);
1355 $fname = 'WordLevelDiff::orig';
1356 wfProfileIn( $fname );
1357 $orig = new _HWLDF_WordAccumulator
;
1359 foreach ($this->edits
as $edit) {
1360 if ($edit->type
== 'copy')
1361 $orig->addWords($edit->orig
);
1362 elseif ($edit->orig
)
1363 $orig->addWords($edit->orig
, 'mark');
1365 $lines = $orig->getLines();
1366 wfProfileOut( $fname );
1370 function closing () {
1371 $fname = 'WordLevelDiff::closing';
1372 wfProfileIn( $fname );
1373 $closing = new _HWLDF_WordAccumulator
;
1375 foreach ($this->edits
as $edit) {
1376 if ($edit->type
== 'copy')
1377 $closing->addWords($edit->closing
);
1378 elseif ($edit->closing
)
1379 $closing->addWords($edit->closing
, 'mark');
1381 $lines = $closing->getLines();
1382 wfProfileOut( $fname );
1388 * Wikipedia Table style diff formatter.
1391 * @package MediaWiki
1392 * @subpackage DifferenceEngine
1394 class TableDiffFormatter
extends DiffFormatter
1396 function TableDiffFormatter() {
1397 $this->leading_context_lines
= 2;
1398 $this->trailing_context_lines
= 2;
1401 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1402 $l1 = wfMsg( 'lineno', $xbeg );
1403 $l2 = wfMsg( 'lineno', $ybeg );
1405 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1406 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1410 function _start_block( $header ) {
1415 function _end_block() {
1418 function _lines( $lines, $prefix=' ', $color='white' ) {
1421 # HTML-escape parameter before calling this
1422 function addedLine( $line ) {
1423 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1426 # HTML-escape parameter before calling this
1427 function deletedLine( $line ) {
1428 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1431 # HTML-escape parameter before calling this
1432 function contextLine( $line ) {
1433 return "<td> </td><td class='diff-context'>{$line}</td>";
1436 function emptyLine() {
1437 return '<td colspan="2"> </td>';
1440 function _added( $lines ) {
1441 foreach ($lines as $line) {
1442 echo '<tr>' . $this->emptyLine() .
1443 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1447 function _deleted($lines) {
1448 foreach ($lines as $line) {
1449 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1450 $this->emptyLine() . "</tr>\n";
1454 function _context( $lines ) {
1455 foreach ($lines as $line) {
1457 $this->contextLine( htmlspecialchars ( $line ) ) .
1458 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1462 function _changed( $orig, $closing ) {
1463 $fname = 'TableDiffFormatter::_changed';
1464 wfProfileIn( $fname );
1466 $diff = new WordLevelDiff( $orig, $closing );
1467 $del = $diff->orig();
1468 $add = $diff->closing();
1470 # Notice that WordLevelDiff returns HTML-escaped output.
1471 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1473 while ( $line = array_shift( $del ) ) {
1474 $aline = array_shift( $add );
1475 echo '<tr>' . $this->deletedLine( $line ) .
1476 $this->addedLine( $aline ) . "</tr>\n";
1478 foreach ($add as $line) { # If any leftovers
1479 echo '<tr>' . $this->emptyLine() .
1480 $this->addedLine( $line ) . "</tr>\n";
1482 wfProfileOut( $fname );