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) {
76 global $wgInputEncoding,$wgServer,$wgScript;
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
);
85 Script={$wgServer}{$wgScript}
99 # mOldid is false if the difference engine is called with a "vague" query for
100 # a diff between a version V and its previous version V' AND the version V
101 # is the first version of that article. In that case, V' does not exist.
102 if ( $this->mOldid
=== false ) {
103 $this->showFirstRevision();
104 wfProfileOut( $fname );
108 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
110 $mtext = wfMsg( 'missingarticle', $t );
112 $wgOut->setArticleFlag( false );
113 if ( ! $this->loadText() ) {
114 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
115 $wgOut->addHTML( $mtext );
116 wfProfileOut( $fname );
119 $wgOut->suppressQuickbar();
121 $oldTitle = $this->mOldPage
->getPrefixedText();
122 $newTitle = $this->mNewPage
->getPrefixedText();
123 if( $oldTitle == $newTitle ) {
124 $wgOut->setPageTitle( $newTitle );
126 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
128 $wgOut->setSubtitle( wfMsg( 'difference' ) );
129 $wgOut->setRobotpolicy( 'noindex,follow' );
131 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
132 $wgOut->loginToUse();
134 wfProfileOut( $fname );
138 $sk = $wgUser->getSkin();
139 $talk = $wgContLang->getNsText( NS_TALK
);
140 $contribs = wfMsg( 'contribslink' );
142 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
143 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
145 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
146 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
147 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
148 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
149 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
150 'target=' . urlencode($this->mOldUser
) );
151 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
152 'target=' . urlencode($this->mNewUser
) );
153 if ( !$this->mNewid
&& $wgUser->isAllowed('rollback') ) {
154 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
155 'action=rollback&from=' . urlencode($this->mNewUser
) .
156 '&token=' . urlencode( $wgUser->editToken( array( $wgTitle->getPrefixedText(), $this->mNewUser
) ) ) ) .
161 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isLoggedIn() &&
162 ( $wgUser->isAllowed('rollback') ||
!$wgOnlySysopsCanPatrol ) )
164 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
165 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
170 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
171 if ( $this->mNewid
== 0 ) {
174 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
177 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
178 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
179 '<br />' . $prevlink;
180 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
181 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
182 '<br />' . $nextlink . $patrol;
184 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
185 $oldHeader, $newHeader );
186 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
187 $wgOut->addWikiText( $this->mNewtext
);
189 wfProfileOut( $fname );
193 * Show the first revision of an article. Uses normal diff headers in
194 * contrast to normal "old revision" display style.
196 function showFirstRevision() {
197 global $wgOut, $wgTitle, $wgUser, $wgLang;
199 $fname = 'DifferenceEngine::showFirstRevision';
200 wfProfileIn( $fname );
203 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
205 # Get article text from the DB
207 if ( ! $this->loadText() ) {
208 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
210 $mtext = wfMsg( 'missingarticle', $t );
211 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
212 $wgOut->addHTML( $mtext );
213 wfProfileOut( $fname );
217 # Check if user is allowed to look at this page. If not, bail out.
219 if ( !( $this->mOldPage
->userCanRead() ) ) {
220 $wgOut->loginToUse();
222 wfProfileOut( $fname );
226 # Prepare the header box
228 $sk = $wgUser->getSkin();
230 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
231 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
232 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
233 'target=' . urlencode($this->mOldUser
) );
234 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
235 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
236 "($uTLink | $contribs)<br />" . $this->mOldComment
.
237 '<br />' . $nextlink. "</div>\n";
239 $wgOut->addHTML( $header );
241 $wgOut->setSubtitle( wfMsg( 'difference' ) );
242 $wgOut->setRobotpolicy( 'noindex,follow' );
245 # Show current revision
247 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
248 $wgOut->addWikiText( $this->mNewtext
);
250 wfProfileOut( $fname );
253 function showDiff( $otext, $ntext, $otitle, $ntitle ) {
255 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
258 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
259 global $wgUseExternalDiffEngine, $wgContLang;
261 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
263 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
264 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
267 $otext = $wgContLang->segmentForDiff($otext);
268 $ntext = $wgContLang->segmentForDiff($ntext);
270 if ( $wgUseExternalDiffEngine ) {
271 # For historical reasons, external diff engine expects
272 # input text to be HTML-escaped already
273 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
274 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
275 if( !function_exists( 'wikidiff_do_diff' ) ) {
276 dl('php_wikidiff.so');
278 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
280 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
281 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
282 $diffs =& new Diff( $ota, $nta );
283 $formatter =& new TableDiffFormatter();
284 $difftext = $formatter->format( $diffs );
286 $difftext = $wgContLang->unsegmentForDiff($difftext);
287 $out .= $difftext."</table>\n";
292 * Load the text of the articles to compare. If newid is 0, then compare
293 * the old article in oldid to the current article; if oldid is 0, then
294 * compare the current article to the immediately previous one (ignoring the
297 function loadText() {
298 global $wgTitle, $wgOut, $wgLang;
299 $fname = 'DifferenceEngine::loadText';
301 $dbr =& wfGetDB( DB_SLAVE
);
302 if( $this->mNewid
) {
303 $this->newRev
=& Revision
::newFromId( $this->mNewid
);
305 $this->newRev
=& Revision
::newFromTitle( $wgTitle );
307 if( is_null( $this->newRev
) ) {
311 if( $this->newRev
->isCurrent() ) {
312 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
313 $this->mNewPage
= $wgTitle;
314 $newLink = $this->mNewPage
->escapeLocalUrl();
315 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
317 $this->mNewPage
= $this->newRev
->getTitle();
318 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
319 $t = $wgLang->timeanddate( $this->newRev
->getTimestamp(), true );
320 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
321 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
324 if( $this->mOldid
) {
325 $this->oldRev
=& Revision
::newFromId( $this->mOldid
);
327 $this->oldRev
=& $this->newRev
->getPrevious();
328 $this->mOldid
= $this->oldRev
->getId();
330 if( is_null( $this->oldRev
) ) {
334 $this->mOldPage
= $this->oldRev
->getTitle();
336 $t = $wgLang->timeanddate( $this->oldRev
->getTimestamp(), true );
337 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
338 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
340 $this->mNewUser
= $this->newRev
->getUserText();
341 $this->mNewComment
= $this->newRev
->getComment();
342 $this->mNewtext
= $this->newRev
->getText();
344 $this->mOldUser
= $this->oldRev
->getUserText();
345 $this->mOldComment
= $this->oldRev
->getComment();
346 $this->mOldtext
= $this->oldRev
->getText();
352 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
354 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
355 // You may copy this code freely under the conditions of the GPL.
358 define('USE_ASSERTS', function_exists('assert'));
364 * @subpackage DifferenceEngine
372 trigger_error('pure virtual', E_USER_ERROR
);
376 return $this->orig ?
sizeof($this->orig
) : 0;
379 function nclosing() {
380 return $this->closing ?
sizeof($this->closing
) : 0;
388 * @subpackage DifferenceEngine
390 class _DiffOp_Copy
extends _DiffOp
{
393 function _DiffOp_Copy ($orig, $closing = false) {
394 if (!is_array($closing))
397 $this->closing
= $closing;
401 return new _DiffOp_Copy($this->closing
, $this->orig
);
409 * @subpackage DifferenceEngine
411 class _DiffOp_Delete
extends _DiffOp
{
412 var $type = 'delete';
414 function _DiffOp_Delete ($lines) {
415 $this->orig
= $lines;
416 $this->closing
= false;
420 return new _DiffOp_Add($this->orig
);
428 * @subpackage DifferenceEngine
430 class _DiffOp_Add
extends _DiffOp
{
433 function _DiffOp_Add ($lines) {
434 $this->closing
= $lines;
439 return new _DiffOp_Delete($this->closing
);
447 * @subpackage DifferenceEngine
449 class _DiffOp_Change
extends _DiffOp
{
450 var $type = 'change';
452 function _DiffOp_Change ($orig, $closing) {
454 $this->closing
= $closing;
458 return new _DiffOp_Change($this->closing
, $this->orig
);
464 * Class used internally by Diff to actually compute the diffs.
466 * The algorithm used here is mostly lifted from the perl module
467 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
468 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
470 * More ideas are taken from:
471 * http://www.ics.uci.edu/~eppstein/161/960229.html
473 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
474 * diffutils-2.7, which can be found at:
475 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
477 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
480 * @author Geoffrey T. Dairiki
483 * @subpackage DifferenceEngine
487 function diff ($from_lines, $to_lines) {
488 $fname = '_DiffEngine::diff';
489 wfProfileIn( $fname );
491 $n_from = sizeof($from_lines);
492 $n_to = sizeof($to_lines);
494 $this->xchanged
= $this->ychanged
= array();
495 $this->xv
= $this->yv
= array();
496 $this->xind
= $this->yind
= array();
498 unset($this->in_seq
);
501 // Skip leading common lines.
502 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
503 if ($from_lines[$skip] != $to_lines[$skip])
505 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
507 // Skip trailing common lines.
508 $xi = $n_from; $yi = $n_to;
509 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
510 if ($from_lines[$xi] != $to_lines[$yi])
512 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
515 // Ignore lines which do not exist in both files.
516 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
517 $xhash[$from_lines[$xi]] = 1;
518 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
519 $line = $to_lines[$yi];
520 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
526 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
527 $line = $from_lines[$xi];
528 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
535 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
537 // Merge edits when possible
538 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
539 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
541 // Compute the edit operations.
544 while ($xi < $n_from ||
$yi < $n_to) {
545 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
546 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
548 // Skip matching "snake".
550 while ( $xi < $n_from && $yi < $n_to
551 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
552 $copy[] = $from_lines[$xi++
];
556 $edits[] = new _DiffOp_Copy($copy);
558 // Find deletes & adds.
560 while ($xi < $n_from && $this->xchanged
[$xi])
561 $delete[] = $from_lines[$xi++
];
564 while ($yi < $n_to && $this->ychanged
[$yi])
565 $add[] = $to_lines[$yi++
];
568 $edits[] = new _DiffOp_Change($delete, $add);
570 $edits[] = new _DiffOp_Delete($delete);
572 $edits[] = new _DiffOp_Add($add);
574 wfProfileOut( $fname );
579 /* Divide the Largest Common Subsequence (LCS) of the sequences
580 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
583 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
584 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
585 * sub sequences. The first sub-sequence is contained in [X0, X1),
586 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
587 * that (X0, Y0) == (XOFF, YOFF) and
588 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
590 * This function assumes that the first lines of the specified portions
591 * of the two files do not match, and likewise that the last lines do not
592 * match. The caller must trim matching lines from the beginning and end
593 * of the portions it is going to specify.
595 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
596 $fname = '_DiffEngine::_diag';
597 wfProfileIn( $fname );
600 if ($xlim - $xoff > $ylim - $yoff) {
601 // Things seems faster (I'm not sure I understand why)
602 // when the shortest sequence in X.
604 list ($xoff, $xlim, $yoff, $ylim)
605 = array( $yoff, $ylim, $xoff, $xlim);
609 for ($i = $ylim - 1; $i >= $yoff; $i--)
610 $ymatches[$this->xv
[$i]][] = $i;
612 for ($i = $ylim - 1; $i >= $yoff; $i--)
613 $ymatches[$this->yv
[$i]][] = $i;
616 $this->seq
[0]= $yoff - 1;
617 $this->in_seq
= array();
620 $numer = $xlim - $xoff +
$nchunks - 1;
622 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
623 wfProfileIn( "$fname-chunk" );
625 for ($i = 0; $i <= $this->lcs
; $i++
)
626 $ymids[$i][$chunk-1] = $this->seq
[$i];
628 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
629 for ( ; $x < $x1; $x++
) {
630 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
631 if (empty($ymatches[$line]))
633 $matches = $ymatches[$line];
635 while (list ($junk, $y) = each($matches))
636 if (empty($this->in_seq
[$y])) {
637 $k = $this->_lcs_pos($y);
638 USE_ASSERTS
&& assert($k > 0);
639 $ymids[$k] = $ymids[$k-1];
642 while (list ($junk, $y) = each($matches)) {
643 if ($y > $this->seq
[$k-1]) {
644 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
645 // Optimization: this is a common case:
646 // next match is just replacing previous match.
647 $this->in_seq
[$this->seq
[$k]] = false;
649 $this->in_seq
[$y] = 1;
650 } else if (empty($this->in_seq
[$y])) {
651 $k = $this->_lcs_pos($y);
652 USE_ASSERTS
&& assert($k > 0);
653 $ymids[$k] = $ymids[$k-1];
657 wfProfileOut( "$fname-chunk" );
660 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
661 $ymid = $ymids[$this->lcs
];
662 for ($n = 0; $n < $nchunks - 1; $n++
) {
663 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
665 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
667 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
669 wfProfileOut( $fname );
670 return array($this->lcs
, $seps);
673 function _lcs_pos ($ypos) {
674 $fname = '_DiffEngine::_lcs_pos';
675 wfProfileIn( $fname );
678 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
679 $this->seq
[++
$this->lcs
] = $ypos;
680 $this->in_seq
[$ypos] = 1;
681 wfProfileOut( $fname );
686 while ($beg < $end) {
687 $mid = (int)(($beg +
$end) / 2);
688 if ( $ypos > $this->seq
[$mid] )
694 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
696 $this->in_seq
[$this->seq
[$end]] = false;
697 $this->seq
[$end] = $ypos;
698 $this->in_seq
[$ypos] = 1;
699 wfProfileOut( $fname );
703 /* Find LCS of two sequences.
705 * The results are recorded in the vectors $this->{x,y}changed[], by
706 * storing a 1 in the element for each line that is an insertion
707 * or deletion (ie. is not in the LCS).
709 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
711 * Note that XLIM, YLIM are exclusive bounds.
712 * All line numbers are origin-0 and discarded lines are not counted.
714 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
715 $fname = '_DiffEngine::_compareseq';
716 wfProfileIn( $fname );
718 // Slide down the bottom initial diagonal.
719 while ($xoff < $xlim && $yoff < $ylim
720 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
725 // Slide up the top initial diagonal.
726 while ($xlim > $xoff && $ylim > $yoff
727 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
732 if ($xoff == $xlim ||
$yoff == $ylim)
735 // This is ad hoc but seems to work well.
736 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
737 //$nchunks = max(2,min(8,(int)$nchunks));
738 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
740 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
744 // X and Y sequences have no common subsequence:
746 while ($yoff < $ylim)
747 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
748 while ($xoff < $xlim)
749 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
751 // Use the partitions to split this problem into subproblems.
754 while ($pt2 = next($seps)) {
755 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
759 wfProfileOut( $fname );
762 /* Adjust inserts/deletes of identical lines to join changes
763 * as much as possible.
765 * We do something when a run of changed lines include a
766 * line at one end and has an excluded, identical line at the other.
767 * We are free to choose which identical line is included.
768 * `compareseq' usually chooses the one at the beginning,
769 * but usually it is cleaner to consider the following identical line
770 * to be the "change".
772 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
774 function _shift_boundaries ($lines, &$changed, $other_changed) {
775 $fname = '_DiffEngine::_shift_boundaries';
776 wfProfileIn( $fname );
780 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
781 $len = sizeof($lines);
782 $other_len = sizeof($other_changed);
786 * Scan forwards to find beginning of another run of changes.
787 * Also keep track of the corresponding point in the other file.
789 * Throughout this code, $i and $j are adjusted together so that
790 * the first $i elements of $changed and the first $j elements
791 * of $other_changed both contain the same number of zeros
793 * Furthermore, $j is always kept so that $j == $other_len or
794 * $other_changed[$j] == false.
796 while ($j < $other_len && $other_changed[$j])
799 while ($i < $len && ! $changed[$i]) {
800 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
802 while ($j < $other_len && $other_changed[$j])
811 // Find the end of this run of changes.
812 while (++
$i < $len && $changed[$i])
817 * Record the length of this run of changes, so that
818 * we can later determine whether the run has grown.
820 $runlength = $i - $start;
823 * Move the changed region back, so long as the
824 * previous unchanged line matches the last changed one.
825 * This merges with previous changed regions.
827 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
828 $changed[--$start] = 1;
829 $changed[--$i] = false;
830 while ($start > 0 && $changed[$start - 1])
832 USE_ASSERTS
&& assert('$j > 0');
833 while ($other_changed[--$j])
835 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
839 * Set CORRESPONDING to the end of the changed run, at the last
840 * point where it corresponds to a changed run in the other file.
841 * CORRESPONDING == LEN means no such point has been found.
843 $corresponding = $j < $other_len ?
$i : $len;
846 * Move the changed region forward, so long as the
847 * first changed line matches the following unchanged one.
848 * This merges with following changed regions.
849 * Do this second, so that if there are no merges,
850 * the changed region is moved forward as far as possible.
852 while ($i < $len && $lines[$start] == $lines[$i]) {
853 $changed[$start++
] = false;
855 while ($i < $len && $changed[$i])
858 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
860 if ($j < $other_len && $other_changed[$j]) {
862 while ($j < $other_len && $other_changed[$j])
866 } while ($runlength != $i - $start);
869 * If possible, move the fully-merged run of changes
870 * back to a corresponding run in the other file.
872 while ($corresponding < $i) {
873 $changed[--$start] = 1;
875 USE_ASSERTS
&& assert('$j > 0');
876 while ($other_changed[--$j])
878 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
881 wfProfileOut( $fname );
886 * Class representing a 'diff' between two sequences of strings.
890 * @subpackage DifferenceEngine
898 * Computes diff between sequences of strings.
900 * @param $from_lines array An array of strings.
901 * (Typically these are lines from a file.)
902 * @param $to_lines array An array of strings.
904 function Diff($from_lines, $to_lines) {
905 $eng = new _DiffEngine
;
906 $this->edits
= $eng->diff($from_lines, $to_lines);
907 //$this->_check($from_lines, $to_lines);
911 * Compute reversed Diff.
915 * $diff = new Diff($lines1, $lines2);
916 * $rev = $diff->reverse();
917 * @return object A Diff object representing the inverse of the
920 function reverse () {
922 $rev->edits
= array();
923 foreach ($this->edits
as $edit) {
924 $rev->edits
[] = $edit->reverse();
930 * Check for empty diff.
932 * @return bool True iff two sequences were identical.
934 function isEmpty () {
935 foreach ($this->edits
as $edit) {
936 if ($edit->type
!= 'copy')
943 * Compute the length of the Longest Common Subsequence (LCS).
945 * This is mostly for diagnostic purposed.
947 * @return int The length of the LCS.
951 foreach ($this->edits
as $edit) {
952 if ($edit->type
== 'copy')
953 $lcs +
= sizeof($edit->orig
);
959 * Get the original set of lines.
961 * This reconstructs the $from_lines parameter passed to the
964 * @return array The original sequence of strings.
969 foreach ($this->edits
as $edit) {
971 array_splice($lines, sizeof($lines), 0, $edit->orig
);
977 * Get the closing set of lines.
979 * This reconstructs the $to_lines parameter passed to the
982 * @return array The sequence of strings.
987 foreach ($this->edits
as $edit) {
989 array_splice($lines, sizeof($lines), 0, $edit->closing
);
995 * Check a Diff for validity.
997 * This is here only for debugging purposes.
999 function _check ($from_lines, $to_lines) {
1000 $fname = 'Diff::_check';
1001 wfProfileIn( $fname );
1002 if (serialize($from_lines) != serialize($this->orig()))
1003 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1004 if (serialize($to_lines) != serialize($this->closing()))
1005 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1007 $rev = $this->reverse();
1008 if (serialize($to_lines) != serialize($rev->orig()))
1009 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1010 if (serialize($from_lines) != serialize($rev->closing()))
1011 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1015 foreach ($this->edits
as $edit) {
1016 if ( $prevtype == $edit->type
)
1017 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1018 $prevtype = $edit->type
;
1021 $lcs = $this->lcs();
1022 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1023 wfProfileOut( $fname );
1031 * @package MediaWiki
1032 * @subpackage DifferenceEngine
1034 class MappedDiff
extends Diff
1039 * Computes diff between sequences of strings.
1041 * This can be used to compute things like
1042 * case-insensitve diffs, or diffs which ignore
1043 * changes in white-space.
1045 * @param $from_lines array An array of strings.
1046 * (Typically these are lines from a file.)
1048 * @param $to_lines array An array of strings.
1050 * @param $mapped_from_lines array This array should
1051 * have the same size number of elements as $from_lines.
1052 * The elements in $mapped_from_lines and
1053 * $mapped_to_lines are what is actually compared
1054 * when computing the diff.
1056 * @param $mapped_to_lines array This array should
1057 * have the same number of elements as $to_lines.
1059 function MappedDiff($from_lines, $to_lines,
1060 $mapped_from_lines, $mapped_to_lines) {
1061 $fname = 'MappedDiff::MappedDiff';
1062 wfProfileIn( $fname );
1064 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1065 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1067 $this->Diff($mapped_from_lines, $mapped_to_lines);
1070 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1071 $orig = &$this->edits
[$i]->orig
;
1072 if (is_array($orig)) {
1073 $orig = array_slice($from_lines, $xi, sizeof($orig));
1074 $xi +
= sizeof($orig);
1077 $closing = &$this->edits
[$i]->closing
;
1078 if (is_array($closing)) {
1079 $closing = array_slice($to_lines, $yi, sizeof($closing));
1080 $yi +
= sizeof($closing);
1083 wfProfileOut( $fname );
1088 * A class to format Diffs
1090 * This class formats the diff in classic diff format.
1091 * It is intended that this class be customized via inheritance,
1092 * to obtain fancier outputs.
1095 * @package MediaWiki
1096 * @subpackage DifferenceEngine
1101 * Number of leading context "lines" to preserve.
1103 * This should be left at zero for this class, but subclasses
1104 * may want to set this to other values.
1106 var $leading_context_lines = 0;
1109 * Number of trailing context "lines" to preserve.
1111 * This should be left at zero for this class, but subclasses
1112 * may want to set this to other values.
1114 var $trailing_context_lines = 0;
1119 * @param $diff object A Diff object.
1120 * @return string The formatted output.
1122 function format($diff) {
1123 $fname = 'DiffFormatter::format';
1124 wfProfileIn( $fname );
1130 $nlead = $this->leading_context_lines
;
1131 $ntrail = $this->trailing_context_lines
;
1133 $this->_start_diff();
1135 foreach ($diff->edits
as $edit) {
1136 if ($edit->type
== 'copy') {
1137 if (is_array($block)) {
1138 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1143 $context = array_slice($edit->orig
, 0, $ntrail);
1144 $block[] = new _DiffOp_Copy($context);
1146 $this->_block($x0, $ntrail +
$xi - $x0,
1147 $y0, $ntrail +
$yi - $y0,
1152 $context = $edit->orig
;
1155 if (! is_array($block)) {
1156 $context = array_slice($context, sizeof($context) - $nlead);
1157 $x0 = $xi - sizeof($context);
1158 $y0 = $yi - sizeof($context);
1161 $block[] = new _DiffOp_Copy($context);
1167 $xi +
= sizeof($edit->orig
);
1169 $yi +
= sizeof($edit->closing
);
1172 if (is_array($block))
1173 $this->_block($x0, $xi - $x0,
1177 $end = $this->_end_diff();
1178 wfProfileOut( $fname );
1182 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1183 $fname = 'DiffFormatter::_block';
1184 wfProfileIn( $fname );
1185 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1186 foreach ($edits as $edit) {
1187 if ($edit->type
== 'copy')
1188 $this->_context($edit->orig
);
1189 elseif ($edit->type
== 'add')
1190 $this->_added($edit->closing
);
1191 elseif ($edit->type
== 'delete')
1192 $this->_deleted($edit->orig
);
1193 elseif ($edit->type
== 'change')
1194 $this->_changed($edit->orig
, $edit->closing
);
1196 trigger_error('Unknown edit type', E_USER_ERROR
);
1198 $this->_end_block();
1199 wfProfileOut( $fname );
1202 function _start_diff() {
1206 function _end_diff() {
1207 $val = ob_get_contents();
1212 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1214 $xbeg .= "," . ($xbeg +
$xlen - 1);
1216 $ybeg .= "," . ($ybeg +
$ylen - 1);
1218 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1221 function _start_block($header) {
1225 function _end_block() {
1228 function _lines($lines, $prefix = ' ') {
1229 foreach ($lines as $line)
1230 echo "$prefix $line\n";
1233 function _context($lines) {
1234 $this->_lines($lines);
1237 function _added($lines) {
1238 $this->_lines($lines, '>');
1240 function _deleted($lines) {
1241 $this->_lines($lines, '<');
1244 function _changed($orig, $closing) {
1245 $this->_deleted($orig);
1247 $this->_added($closing);
1253 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1257 define('NBSP', ' '); // iso-8859-x non-breaking space.
1262 * @package MediaWiki
1263 * @subpackage DifferenceEngine
1265 class _HWLDF_WordAccumulator
{
1266 function _HWLDF_WordAccumulator () {
1267 $this->_lines
= array();
1273 function _flushGroup ($new_tag) {
1274 if ($this->_group
!== '') {
1275 if ($this->_tag
== 'mark')
1276 $this->_line
.= '<span class="diffchange">' .
1277 htmlspecialchars ( $this->_group
) . '</span>';
1279 $this->_line
.= htmlspecialchars ( $this->_group
);
1282 $this->_tag
= $new_tag;
1285 function _flushLine ($new_tag) {
1286 $this->_flushGroup($new_tag);
1287 if ($this->_line
!= '')
1288 array_push ( $this->_lines
, $this->_line
);
1290 # make empty lines visible by inserting an NBSP
1291 array_push ( $this->_lines
, NBSP
);
1295 function addWords ($words, $tag = '') {
1296 if ($tag != $this->_tag
)
1297 $this->_flushGroup($tag);
1299 foreach ($words as $word) {
1300 // new-line should only come as first char of word.
1303 if ($word[0] == "\n") {
1304 $this->_flushLine($tag);
1305 $word = substr($word, 1);
1307 assert(!strstr($word, "\n"));
1308 $this->_group
.= $word;
1312 function getLines() {
1313 $this->_flushLine('~done');
1314 return $this->_lines
;
1321 * @package MediaWiki
1322 * @subpackage DifferenceEngine
1324 class WordLevelDiff
extends MappedDiff
1326 function WordLevelDiff ($orig_lines, $closing_lines) {
1327 $fname = 'WordLevelDiff::WordLevelDiff';
1328 wfProfileIn( $fname );
1330 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1331 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1334 $this->MappedDiff($orig_words, $closing_words,
1335 $orig_stripped, $closing_stripped);
1336 wfProfileOut( $fname );
1339 function _split($lines) {
1340 $fname = 'WordLevelDiff::_split';
1341 wfProfileIn( $fname );
1342 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1343 implode("\n", $lines),
1345 wfProfileOut( $fname );
1346 return array(array(''), array(''));
1348 wfProfileOut( $fname );
1349 return array($m[0], $m[1]);
1353 $fname = 'WordLevelDiff::orig';
1354 wfProfileIn( $fname );
1355 $orig = new _HWLDF_WordAccumulator
;
1357 foreach ($this->edits
as $edit) {
1358 if ($edit->type
== 'copy')
1359 $orig->addWords($edit->orig
);
1360 elseif ($edit->orig
)
1361 $orig->addWords($edit->orig
, 'mark');
1363 $lines = $orig->getLines();
1364 wfProfileOut( $fname );
1368 function closing () {
1369 $fname = 'WordLevelDiff::closing';
1370 wfProfileIn( $fname );
1371 $closing = new _HWLDF_WordAccumulator
;
1373 foreach ($this->edits
as $edit) {
1374 if ($edit->type
== 'copy')
1375 $closing->addWords($edit->closing
);
1376 elseif ($edit->closing
)
1377 $closing->addWords($edit->closing
, 'mark');
1379 $lines = $closing->getLines();
1380 wfProfileOut( $fname );
1386 * Wikipedia Table style diff formatter.
1389 * @package MediaWiki
1390 * @subpackage DifferenceEngine
1392 class TableDiffFormatter
extends DiffFormatter
1394 function TableDiffFormatter() {
1395 $this->leading_context_lines
= 2;
1396 $this->trailing_context_lines
= 2;
1399 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1400 $l1 = wfMsg( 'lineno', $xbeg );
1401 $l2 = wfMsg( 'lineno', $ybeg );
1403 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1404 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1408 function _start_block( $header ) {
1413 function _end_block() {
1416 function _lines( $lines, $prefix=' ', $color='white' ) {
1419 # HTML-escape parameter before calling this
1420 function addedLine( $line ) {
1421 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1424 # HTML-escape parameter before calling this
1425 function deletedLine( $line ) {
1426 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1429 # HTML-escape parameter before calling this
1430 function contextLine( $line ) {
1431 return "<td> </td><td class='diff-context'>{$line}</td>";
1434 function emptyLine() {
1435 return '<td colspan="2"> </td>';
1438 function _added( $lines ) {
1439 foreach ($lines as $line) {
1440 echo '<tr>' . $this->emptyLine() .
1441 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1445 function _deleted($lines) {
1446 foreach ($lines as $line) {
1447 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1448 $this->emptyLine() . "</tr>\n";
1452 function _context( $lines ) {
1453 foreach ($lines as $line) {
1455 $this->contextLine( htmlspecialchars ( $line ) ) .
1456 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1460 function _changed( $orig, $closing ) {
1461 $fname = 'TableDiffFormatter::_changed';
1462 wfProfileIn( $fname );
1464 $diff = new WordLevelDiff( $orig, $closing );
1465 $del = $diff->orig();
1466 $add = $diff->closing();
1468 # Notice that WordLevelDiff returns HTML-escaped output.
1469 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1471 while ( $line = array_shift( $del ) ) {
1472 $aline = array_shift( $add );
1473 echo '<tr>' . $this->deletedLine( $line ) .
1474 $this->addedLine( $aline ) . "</tr>\n";
1476 foreach ($add as $line) { # If any leftovers
1477 echo '<tr>' . $this->emptyLine() .
1478 $this->addedLine( $line ) . "</tr>\n";
1480 wfProfileOut( $fname );