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->newRev
->isCurrent() && $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, wfMsgHtml( 'previousdiff' ),
173 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
174 if ( $this->newRev
->isCurrent() ) {
177 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsgHtml( 'nextdiff' ),
178 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
181 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
182 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
183 '<br />' . $prevlink;
184 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
185 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
186 '<br />' . $nextlink . $patrol;
188 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
189 $oldHeader, $newHeader );
190 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
192 if( !$this->newRev
->isCurrent() ) {
193 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
195 $wgOut->addWikiText( $this->mNewtext
);
196 if( !$this->newRev
->isCurrent() ) {
197 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
200 wfProfileOut( $fname );
204 * Show the first revision of an article. Uses normal diff headers in
205 * contrast to normal "old revision" display style.
207 function showFirstRevision() {
208 global $wgOut, $wgTitle, $wgUser, $wgLang;
210 $fname = 'DifferenceEngine::showFirstRevision';
211 wfProfileIn( $fname );
214 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
216 # Get article text from the DB
218 if ( ! $this->loadText() ) {
219 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
221 $mtext = wfMsg( 'missingarticle', $t );
222 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
223 $wgOut->addHTML( $mtext );
224 wfProfileOut( $fname );
228 # Check if user is allowed to look at this page. If not, bail out.
230 if ( !( $this->mOldPage
->userCanRead() ) ) {
231 $wgOut->loginToUse();
233 wfProfileOut( $fname );
237 # Prepare the header box
239 $sk = $wgUser->getSkin();
241 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
242 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
243 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
244 'target=' . urlencode($this->mOldUser
) );
245 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
246 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
247 "($uTLink | $contribs)<br />" . $this->mOldComment
.
248 '<br />' . $nextlink. "</div>\n";
250 $wgOut->addHTML( $header );
252 $wgOut->setSubtitle( wfMsg( 'difference' ) );
253 $wgOut->setRobotpolicy( 'noindex,follow' );
256 # Show current revision
258 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
259 $wgOut->addWikiText( $this->mNewtext
);
261 wfProfileOut( $fname );
264 function showDiff( $otext, $ntext, $otitle, $ntitle ) {
266 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
269 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
270 global $wgUseExternalDiffEngine, $wgContLang;
272 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
274 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
275 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
278 $otext = $wgContLang->segmentForDiff($otext);
279 $ntext = $wgContLang->segmentForDiff($ntext);
281 if ( $wgUseExternalDiffEngine ) {
282 # For historical reasons, external diff engine expects
283 # input text to be HTML-escaped already
284 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
285 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
286 if( !function_exists( 'wikidiff_do_diff' ) ) {
287 dl('php_wikidiff.so');
289 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
291 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
292 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
293 $diffs =& new Diff( $ota, $nta );
294 $formatter =& new TableDiffFormatter();
295 $difftext = $formatter->format( $diffs );
297 $difftext = $wgContLang->unsegmentForDiff($difftext);
298 $out .= $difftext."</table>\n";
303 * Load the text of the articles to compare. If newid is 0, then compare
304 * the old article in oldid to the current article; if oldid is 0, then
305 * compare the current article to the immediately previous one (ignoring the
308 function loadText() {
309 global $wgTitle, $wgOut, $wgLang;
310 $fname = 'DifferenceEngine::loadText';
312 $dbr =& wfGetDB( DB_SLAVE
);
313 if( $this->mNewid
) {
314 $this->newRev
= Revision
::newFromId( $this->mNewid
);
316 $this->newRev
= Revision
::newFromTitle( $wgTitle );
318 if( is_null( $this->newRev
) ) {
322 if( $this->newRev
->isCurrent() ) {
323 $wgOut->setArticleFlag( true );
324 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
325 $this->mNewPage
= $wgTitle;
326 $newLink = $this->mNewPage
->escapeLocalUrl();
327 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
329 $this->mNewPage
= $this->newRev
->getTitle();
330 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
331 $t = $wgLang->timeanddate( $this->newRev
->getTimestamp(), true );
332 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
333 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
336 if( $this->mOldid
) {
337 $this->oldRev
= Revision
::newFromId( $this->mOldid
);
339 $this->oldRev
= $this->newRev
->getPrevious();
340 $this->mOldid
= $this->oldRev
->getId();
342 if( is_null( $this->oldRev
) ) {
346 $this->mOldPage
= $this->oldRev
->getTitle();
348 $t = $wgLang->timeanddate( $this->oldRev
->getTimestamp(), true );
349 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
350 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
352 $this->mNewUser
= $this->newRev
->getUserText();
353 $this->mNewComment
= $this->newRev
->getComment();
354 $this->mNewtext
= $this->newRev
->getText();
356 $this->mOldUser
= $this->oldRev
->getUserText();
357 $this->mOldComment
= $this->oldRev
->getComment();
358 $this->mOldtext
= $this->oldRev
->getText();
364 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
366 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
367 // You may copy this code freely under the conditions of the GPL.
370 define('USE_ASSERTS', function_exists('assert'));
376 * @subpackage DifferenceEngine
384 trigger_error('pure virtual', E_USER_ERROR
);
388 return $this->orig ?
sizeof($this->orig
) : 0;
391 function nclosing() {
392 return $this->closing ?
sizeof($this->closing
) : 0;
400 * @subpackage DifferenceEngine
402 class _DiffOp_Copy
extends _DiffOp
{
405 function _DiffOp_Copy ($orig, $closing = false) {
406 if (!is_array($closing))
409 $this->closing
= $closing;
413 return new _DiffOp_Copy($this->closing
, $this->orig
);
421 * @subpackage DifferenceEngine
423 class _DiffOp_Delete
extends _DiffOp
{
424 var $type = 'delete';
426 function _DiffOp_Delete ($lines) {
427 $this->orig
= $lines;
428 $this->closing
= false;
432 return new _DiffOp_Add($this->orig
);
440 * @subpackage DifferenceEngine
442 class _DiffOp_Add
extends _DiffOp
{
445 function _DiffOp_Add ($lines) {
446 $this->closing
= $lines;
451 return new _DiffOp_Delete($this->closing
);
459 * @subpackage DifferenceEngine
461 class _DiffOp_Change
extends _DiffOp
{
462 var $type = 'change';
464 function _DiffOp_Change ($orig, $closing) {
466 $this->closing
= $closing;
470 return new _DiffOp_Change($this->closing
, $this->orig
);
476 * Class used internally by Diff to actually compute the diffs.
478 * The algorithm used here is mostly lifted from the perl module
479 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
480 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
482 * More ideas are taken from:
483 * http://www.ics.uci.edu/~eppstein/161/960229.html
485 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
486 * diffutils-2.7, which can be found at:
487 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
489 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
492 * @author Geoffrey T. Dairiki
495 * @subpackage DifferenceEngine
499 function diff ($from_lines, $to_lines) {
500 $fname = '_DiffEngine::diff';
501 wfProfileIn( $fname );
503 $n_from = sizeof($from_lines);
504 $n_to = sizeof($to_lines);
506 $this->xchanged
= $this->ychanged
= array();
507 $this->xv
= $this->yv
= array();
508 $this->xind
= $this->yind
= array();
510 unset($this->in_seq
);
513 // Skip leading common lines.
514 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
515 if ($from_lines[$skip] != $to_lines[$skip])
517 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
519 // Skip trailing common lines.
520 $xi = $n_from; $yi = $n_to;
521 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
522 if ($from_lines[$xi] != $to_lines[$yi])
524 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
527 // Ignore lines which do not exist in both files.
528 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
529 $xhash[$from_lines[$xi]] = 1;
530 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
531 $line = $to_lines[$yi];
532 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
538 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
539 $line = $from_lines[$xi];
540 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
547 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
549 // Merge edits when possible
550 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
551 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
553 // Compute the edit operations.
556 while ($xi < $n_from ||
$yi < $n_to) {
557 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
558 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
560 // Skip matching "snake".
562 while ( $xi < $n_from && $yi < $n_to
563 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
564 $copy[] = $from_lines[$xi++
];
568 $edits[] = new _DiffOp_Copy($copy);
570 // Find deletes & adds.
572 while ($xi < $n_from && $this->xchanged
[$xi])
573 $delete[] = $from_lines[$xi++
];
576 while ($yi < $n_to && $this->ychanged
[$yi])
577 $add[] = $to_lines[$yi++
];
580 $edits[] = new _DiffOp_Change($delete, $add);
582 $edits[] = new _DiffOp_Delete($delete);
584 $edits[] = new _DiffOp_Add($add);
586 wfProfileOut( $fname );
591 /* Divide the Largest Common Subsequence (LCS) of the sequences
592 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
595 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
596 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
597 * sub sequences. The first sub-sequence is contained in [X0, X1),
598 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
599 * that (X0, Y0) == (XOFF, YOFF) and
600 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
602 * This function assumes that the first lines of the specified portions
603 * of the two files do not match, and likewise that the last lines do not
604 * match. The caller must trim matching lines from the beginning and end
605 * of the portions it is going to specify.
607 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
608 $fname = '_DiffEngine::_diag';
609 wfProfileIn( $fname );
612 if ($xlim - $xoff > $ylim - $yoff) {
613 // Things seems faster (I'm not sure I understand why)
614 // when the shortest sequence in X.
616 list ($xoff, $xlim, $yoff, $ylim)
617 = array( $yoff, $ylim, $xoff, $xlim);
621 for ($i = $ylim - 1; $i >= $yoff; $i--)
622 $ymatches[$this->xv
[$i]][] = $i;
624 for ($i = $ylim - 1; $i >= $yoff; $i--)
625 $ymatches[$this->yv
[$i]][] = $i;
628 $this->seq
[0]= $yoff - 1;
629 $this->in_seq
= array();
632 $numer = $xlim - $xoff +
$nchunks - 1;
634 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
635 wfProfileIn( "$fname-chunk" );
637 for ($i = 0; $i <= $this->lcs
; $i++
)
638 $ymids[$i][$chunk-1] = $this->seq
[$i];
640 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
641 for ( ; $x < $x1; $x++
) {
642 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
643 if (empty($ymatches[$line]))
645 $matches = $ymatches[$line];
647 while (list ($junk, $y) = each($matches))
648 if (empty($this->in_seq
[$y])) {
649 $k = $this->_lcs_pos($y);
650 USE_ASSERTS
&& assert($k > 0);
651 $ymids[$k] = $ymids[$k-1];
654 while (list ($junk, $y) = each($matches)) {
655 if ($y > $this->seq
[$k-1]) {
656 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
657 // Optimization: this is a common case:
658 // next match is just replacing previous match.
659 $this->in_seq
[$this->seq
[$k]] = false;
661 $this->in_seq
[$y] = 1;
662 } else if (empty($this->in_seq
[$y])) {
663 $k = $this->_lcs_pos($y);
664 USE_ASSERTS
&& assert($k > 0);
665 $ymids[$k] = $ymids[$k-1];
669 wfProfileOut( "$fname-chunk" );
672 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
673 $ymid = $ymids[$this->lcs
];
674 for ($n = 0; $n < $nchunks - 1; $n++
) {
675 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
677 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
679 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
681 wfProfileOut( $fname );
682 return array($this->lcs
, $seps);
685 function _lcs_pos ($ypos) {
686 $fname = '_DiffEngine::_lcs_pos';
687 wfProfileIn( $fname );
690 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
691 $this->seq
[++
$this->lcs
] = $ypos;
692 $this->in_seq
[$ypos] = 1;
693 wfProfileOut( $fname );
698 while ($beg < $end) {
699 $mid = (int)(($beg +
$end) / 2);
700 if ( $ypos > $this->seq
[$mid] )
706 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
708 $this->in_seq
[$this->seq
[$end]] = false;
709 $this->seq
[$end] = $ypos;
710 $this->in_seq
[$ypos] = 1;
711 wfProfileOut( $fname );
715 /* Find LCS of two sequences.
717 * The results are recorded in the vectors $this->{x,y}changed[], by
718 * storing a 1 in the element for each line that is an insertion
719 * or deletion (ie. is not in the LCS).
721 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
723 * Note that XLIM, YLIM are exclusive bounds.
724 * All line numbers are origin-0 and discarded lines are not counted.
726 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
727 $fname = '_DiffEngine::_compareseq';
728 wfProfileIn( $fname );
730 // Slide down the bottom initial diagonal.
731 while ($xoff < $xlim && $yoff < $ylim
732 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
737 // Slide up the top initial diagonal.
738 while ($xlim > $xoff && $ylim > $yoff
739 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
744 if ($xoff == $xlim ||
$yoff == $ylim)
747 // This is ad hoc but seems to work well.
748 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
749 //$nchunks = max(2,min(8,(int)$nchunks));
750 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
752 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
756 // X and Y sequences have no common subsequence:
758 while ($yoff < $ylim)
759 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
760 while ($xoff < $xlim)
761 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
763 // Use the partitions to split this problem into subproblems.
766 while ($pt2 = next($seps)) {
767 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
771 wfProfileOut( $fname );
774 /* Adjust inserts/deletes of identical lines to join changes
775 * as much as possible.
777 * We do something when a run of changed lines include a
778 * line at one end and has an excluded, identical line at the other.
779 * We are free to choose which identical line is included.
780 * `compareseq' usually chooses the one at the beginning,
781 * but usually it is cleaner to consider the following identical line
782 * to be the "change".
784 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
786 function _shift_boundaries ($lines, &$changed, $other_changed) {
787 $fname = '_DiffEngine::_shift_boundaries';
788 wfProfileIn( $fname );
792 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
793 $len = sizeof($lines);
794 $other_len = sizeof($other_changed);
798 * Scan forwards to find beginning of another run of changes.
799 * Also keep track of the corresponding point in the other file.
801 * Throughout this code, $i and $j are adjusted together so that
802 * the first $i elements of $changed and the first $j elements
803 * of $other_changed both contain the same number of zeros
805 * Furthermore, $j is always kept so that $j == $other_len or
806 * $other_changed[$j] == false.
808 while ($j < $other_len && $other_changed[$j])
811 while ($i < $len && ! $changed[$i]) {
812 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
814 while ($j < $other_len && $other_changed[$j])
823 // Find the end of this run of changes.
824 while (++
$i < $len && $changed[$i])
829 * Record the length of this run of changes, so that
830 * we can later determine whether the run has grown.
832 $runlength = $i - $start;
835 * Move the changed region back, so long as the
836 * previous unchanged line matches the last changed one.
837 * This merges with previous changed regions.
839 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
840 $changed[--$start] = 1;
841 $changed[--$i] = false;
842 while ($start > 0 && $changed[$start - 1])
844 USE_ASSERTS
&& assert('$j > 0');
845 while ($other_changed[--$j])
847 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
851 * Set CORRESPONDING to the end of the changed run, at the last
852 * point where it corresponds to a changed run in the other file.
853 * CORRESPONDING == LEN means no such point has been found.
855 $corresponding = $j < $other_len ?
$i : $len;
858 * Move the changed region forward, so long as the
859 * first changed line matches the following unchanged one.
860 * This merges with following changed regions.
861 * Do this second, so that if there are no merges,
862 * the changed region is moved forward as far as possible.
864 while ($i < $len && $lines[$start] == $lines[$i]) {
865 $changed[$start++
] = false;
867 while ($i < $len && $changed[$i])
870 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
872 if ($j < $other_len && $other_changed[$j]) {
874 while ($j < $other_len && $other_changed[$j])
878 } while ($runlength != $i - $start);
881 * If possible, move the fully-merged run of changes
882 * back to a corresponding run in the other file.
884 while ($corresponding < $i) {
885 $changed[--$start] = 1;
887 USE_ASSERTS
&& assert('$j > 0');
888 while ($other_changed[--$j])
890 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
893 wfProfileOut( $fname );
898 * Class representing a 'diff' between two sequences of strings.
902 * @subpackage DifferenceEngine
910 * Computes diff between sequences of strings.
912 * @param $from_lines array An array of strings.
913 * (Typically these are lines from a file.)
914 * @param $to_lines array An array of strings.
916 function Diff($from_lines, $to_lines) {
917 $eng = new _DiffEngine
;
918 $this->edits
= $eng->diff($from_lines, $to_lines);
919 //$this->_check($from_lines, $to_lines);
923 * Compute reversed Diff.
927 * $diff = new Diff($lines1, $lines2);
928 * $rev = $diff->reverse();
929 * @return object A Diff object representing the inverse of the
932 function reverse () {
934 $rev->edits
= array();
935 foreach ($this->edits
as $edit) {
936 $rev->edits
[] = $edit->reverse();
942 * Check for empty diff.
944 * @return bool True iff two sequences were identical.
946 function isEmpty () {
947 foreach ($this->edits
as $edit) {
948 if ($edit->type
!= 'copy')
955 * Compute the length of the Longest Common Subsequence (LCS).
957 * This is mostly for diagnostic purposed.
959 * @return int The length of the LCS.
963 foreach ($this->edits
as $edit) {
964 if ($edit->type
== 'copy')
965 $lcs +
= sizeof($edit->orig
);
971 * Get the original set of lines.
973 * This reconstructs the $from_lines parameter passed to the
976 * @return array The original sequence of strings.
981 foreach ($this->edits
as $edit) {
983 array_splice($lines, sizeof($lines), 0, $edit->orig
);
989 * Get the closing set of lines.
991 * This reconstructs the $to_lines parameter passed to the
994 * @return array The sequence of strings.
999 foreach ($this->edits
as $edit) {
1001 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1007 * Check a Diff for validity.
1009 * This is here only for debugging purposes.
1011 function _check ($from_lines, $to_lines) {
1012 $fname = 'Diff::_check';
1013 wfProfileIn( $fname );
1014 if (serialize($from_lines) != serialize($this->orig()))
1015 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1016 if (serialize($to_lines) != serialize($this->closing()))
1017 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1019 $rev = $this->reverse();
1020 if (serialize($to_lines) != serialize($rev->orig()))
1021 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1022 if (serialize($from_lines) != serialize($rev->closing()))
1023 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1027 foreach ($this->edits
as $edit) {
1028 if ( $prevtype == $edit->type
)
1029 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1030 $prevtype = $edit->type
;
1033 $lcs = $this->lcs();
1034 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1035 wfProfileOut( $fname );
1043 * @package MediaWiki
1044 * @subpackage DifferenceEngine
1046 class MappedDiff
extends Diff
1051 * Computes diff between sequences of strings.
1053 * This can be used to compute things like
1054 * case-insensitve diffs, or diffs which ignore
1055 * changes in white-space.
1057 * @param $from_lines array An array of strings.
1058 * (Typically these are lines from a file.)
1060 * @param $to_lines array An array of strings.
1062 * @param $mapped_from_lines array This array should
1063 * have the same size number of elements as $from_lines.
1064 * The elements in $mapped_from_lines and
1065 * $mapped_to_lines are what is actually compared
1066 * when computing the diff.
1068 * @param $mapped_to_lines array This array should
1069 * have the same number of elements as $to_lines.
1071 function MappedDiff($from_lines, $to_lines,
1072 $mapped_from_lines, $mapped_to_lines) {
1073 $fname = 'MappedDiff::MappedDiff';
1074 wfProfileIn( $fname );
1076 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1077 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1079 $this->Diff($mapped_from_lines, $mapped_to_lines);
1082 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1083 $orig = &$this->edits
[$i]->orig
;
1084 if (is_array($orig)) {
1085 $orig = array_slice($from_lines, $xi, sizeof($orig));
1086 $xi +
= sizeof($orig);
1089 $closing = &$this->edits
[$i]->closing
;
1090 if (is_array($closing)) {
1091 $closing = array_slice($to_lines, $yi, sizeof($closing));
1092 $yi +
= sizeof($closing);
1095 wfProfileOut( $fname );
1100 * A class to format Diffs
1102 * This class formats the diff in classic diff format.
1103 * It is intended that this class be customized via inheritance,
1104 * to obtain fancier outputs.
1107 * @package MediaWiki
1108 * @subpackage DifferenceEngine
1113 * Number of leading context "lines" to preserve.
1115 * This should be left at zero for this class, but subclasses
1116 * may want to set this to other values.
1118 var $leading_context_lines = 0;
1121 * Number of trailing context "lines" to preserve.
1123 * This should be left at zero for this class, but subclasses
1124 * may want to set this to other values.
1126 var $trailing_context_lines = 0;
1131 * @param $diff object A Diff object.
1132 * @return string The formatted output.
1134 function format($diff) {
1135 $fname = 'DiffFormatter::format';
1136 wfProfileIn( $fname );
1142 $nlead = $this->leading_context_lines
;
1143 $ntrail = $this->trailing_context_lines
;
1145 $this->_start_diff();
1147 foreach ($diff->edits
as $edit) {
1148 if ($edit->type
== 'copy') {
1149 if (is_array($block)) {
1150 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1155 $context = array_slice($edit->orig
, 0, $ntrail);
1156 $block[] = new _DiffOp_Copy($context);
1158 $this->_block($x0, $ntrail +
$xi - $x0,
1159 $y0, $ntrail +
$yi - $y0,
1164 $context = $edit->orig
;
1167 if (! is_array($block)) {
1168 $context = array_slice($context, sizeof($context) - $nlead);
1169 $x0 = $xi - sizeof($context);
1170 $y0 = $yi - sizeof($context);
1173 $block[] = new _DiffOp_Copy($context);
1179 $xi +
= sizeof($edit->orig
);
1181 $yi +
= sizeof($edit->closing
);
1184 if (is_array($block))
1185 $this->_block($x0, $xi - $x0,
1189 $end = $this->_end_diff();
1190 wfProfileOut( $fname );
1194 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1195 $fname = 'DiffFormatter::_block';
1196 wfProfileIn( $fname );
1197 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1198 foreach ($edits as $edit) {
1199 if ($edit->type
== 'copy')
1200 $this->_context($edit->orig
);
1201 elseif ($edit->type
== 'add')
1202 $this->_added($edit->closing
);
1203 elseif ($edit->type
== 'delete')
1204 $this->_deleted($edit->orig
);
1205 elseif ($edit->type
== 'change')
1206 $this->_changed($edit->orig
, $edit->closing
);
1208 trigger_error('Unknown edit type', E_USER_ERROR
);
1210 $this->_end_block();
1211 wfProfileOut( $fname );
1214 function _start_diff() {
1218 function _end_diff() {
1219 $val = ob_get_contents();
1224 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1226 $xbeg .= "," . ($xbeg +
$xlen - 1);
1228 $ybeg .= "," . ($ybeg +
$ylen - 1);
1230 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1233 function _start_block($header) {
1237 function _end_block() {
1240 function _lines($lines, $prefix = ' ') {
1241 foreach ($lines as $line)
1242 echo "$prefix $line\n";
1245 function _context($lines) {
1246 $this->_lines($lines);
1249 function _added($lines) {
1250 $this->_lines($lines, '>');
1252 function _deleted($lines) {
1253 $this->_lines($lines, '<');
1256 function _changed($orig, $closing) {
1257 $this->_deleted($orig);
1259 $this->_added($closing);
1265 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1269 define('NBSP', ' '); // iso-8859-x non-breaking space.
1274 * @package MediaWiki
1275 * @subpackage DifferenceEngine
1277 class _HWLDF_WordAccumulator
{
1278 function _HWLDF_WordAccumulator () {
1279 $this->_lines
= array();
1285 function _flushGroup ($new_tag) {
1286 if ($this->_group
!== '') {
1287 if ($this->_tag
== 'mark')
1288 $this->_line
.= '<span class="diffchange">' .
1289 htmlspecialchars ( $this->_group
) . '</span>';
1291 $this->_line
.= htmlspecialchars ( $this->_group
);
1294 $this->_tag
= $new_tag;
1297 function _flushLine ($new_tag) {
1298 $this->_flushGroup($new_tag);
1299 if ($this->_line
!= '')
1300 array_push ( $this->_lines
, $this->_line
);
1302 # make empty lines visible by inserting an NBSP
1303 array_push ( $this->_lines
, NBSP
);
1307 function addWords ($words, $tag = '') {
1308 if ($tag != $this->_tag
)
1309 $this->_flushGroup($tag);
1311 foreach ($words as $word) {
1312 // new-line should only come as first char of word.
1315 if ($word[0] == "\n") {
1316 $this->_flushLine($tag);
1317 $word = substr($word, 1);
1319 assert(!strstr($word, "\n"));
1320 $this->_group
.= $word;
1324 function getLines() {
1325 $this->_flushLine('~done');
1326 return $this->_lines
;
1333 * @package MediaWiki
1334 * @subpackage DifferenceEngine
1336 class WordLevelDiff
extends MappedDiff
1338 function WordLevelDiff ($orig_lines, $closing_lines) {
1339 $fname = 'WordLevelDiff::WordLevelDiff';
1340 wfProfileIn( $fname );
1342 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1343 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1346 $this->MappedDiff($orig_words, $closing_words,
1347 $orig_stripped, $closing_stripped);
1348 wfProfileOut( $fname );
1351 function _split($lines) {
1352 $fname = 'WordLevelDiff::_split';
1353 wfProfileIn( $fname );
1354 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1355 implode("\n", $lines),
1357 wfProfileOut( $fname );
1358 return array(array(''), array(''));
1360 wfProfileOut( $fname );
1361 return array($m[0], $m[1]);
1365 $fname = 'WordLevelDiff::orig';
1366 wfProfileIn( $fname );
1367 $orig = new _HWLDF_WordAccumulator
;
1369 foreach ($this->edits
as $edit) {
1370 if ($edit->type
== 'copy')
1371 $orig->addWords($edit->orig
);
1372 elseif ($edit->orig
)
1373 $orig->addWords($edit->orig
, 'mark');
1375 $lines = $orig->getLines();
1376 wfProfileOut( $fname );
1380 function closing () {
1381 $fname = 'WordLevelDiff::closing';
1382 wfProfileIn( $fname );
1383 $closing = new _HWLDF_WordAccumulator
;
1385 foreach ($this->edits
as $edit) {
1386 if ($edit->type
== 'copy')
1387 $closing->addWords($edit->closing
);
1388 elseif ($edit->closing
)
1389 $closing->addWords($edit->closing
, 'mark');
1391 $lines = $closing->getLines();
1392 wfProfileOut( $fname );
1398 * Wikipedia Table style diff formatter.
1401 * @package MediaWiki
1402 * @subpackage DifferenceEngine
1404 class TableDiffFormatter
extends DiffFormatter
1406 function TableDiffFormatter() {
1407 $this->leading_context_lines
= 2;
1408 $this->trailing_context_lines
= 2;
1411 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1412 $l1 = wfMsg( 'lineno', $xbeg );
1413 $l2 = wfMsg( 'lineno', $ybeg );
1415 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1416 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1420 function _start_block( $header ) {
1425 function _end_block() {
1428 function _lines( $lines, $prefix=' ', $color='white' ) {
1431 # HTML-escape parameter before calling this
1432 function addedLine( $line ) {
1433 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1436 # HTML-escape parameter before calling this
1437 function deletedLine( $line ) {
1438 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1441 # HTML-escape parameter before calling this
1442 function contextLine( $line ) {
1443 return "<td> </td><td class='diff-context'>{$line}</td>";
1446 function emptyLine() {
1447 return '<td colspan="2"> </td>';
1450 function _added( $lines ) {
1451 foreach ($lines as $line) {
1452 echo '<tr>' . $this->emptyLine() .
1453 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1457 function _deleted($lines) {
1458 foreach ($lines as $line) {
1459 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1460 $this->emptyLine() . "</tr>\n";
1464 function _context( $lines ) {
1465 foreach ($lines as $line) {
1467 $this->contextLine( htmlspecialchars ( $line ) ) .
1468 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1472 function _changed( $orig, $closing ) {
1473 $fname = 'TableDiffFormatter::_changed';
1474 wfProfileIn( $fname );
1476 $diff = new WordLevelDiff( $orig, $closing );
1477 $del = $diff->orig();
1478 $add = $diff->closing();
1480 # Notice that WordLevelDiff returns HTML-escaped output.
1481 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1483 while ( $line = array_shift( $del ) ) {
1484 $aline = array_shift( $add );
1485 echo '<tr>' . $this->deletedLine( $line ) .
1486 $this->addedLine( $aline ) . "</tr>\n";
1488 foreach ($add as $line) { # If any leftovers
1489 echo '<tr>' . $this->emptyLine() .
1490 $this->addedLine( $line ) . "</tr>\n";
1492 wfProfileOut( $fname );