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, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
173 if ( $this->newRev
->isCurrent() ) {
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" );
190 if( !$this->newRev
->isCurrent() ) {
191 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
193 $wgOut->addWikiText( $this->mNewtext
);
194 if( !$this->newRev
->isCurrent() ) {
195 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
198 wfProfileOut( $fname );
202 * Show the first revision of an article. Uses normal diff headers in
203 * contrast to normal "old revision" display style.
205 function showFirstRevision() {
206 global $wgOut, $wgTitle, $wgUser, $wgLang;
208 $fname = 'DifferenceEngine::showFirstRevision';
209 wfProfileIn( $fname );
212 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
214 # Get article text from the DB
216 if ( ! $this->loadText() ) {
217 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
219 $mtext = wfMsg( 'missingarticle', $t );
220 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
221 $wgOut->addHTML( $mtext );
222 wfProfileOut( $fname );
226 # Check if user is allowed to look at this page. If not, bail out.
228 if ( !( $this->mOldPage
->userCanRead() ) ) {
229 $wgOut->loginToUse();
231 wfProfileOut( $fname );
235 # Prepare the header box
237 $sk = $wgUser->getSkin();
239 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
240 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
241 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
242 'target=' . urlencode($this->mOldUser
) );
243 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
244 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
245 "($uTLink | $contribs)<br />" . $this->mOldComment
.
246 '<br />' . $nextlink. "</div>\n";
248 $wgOut->addHTML( $header );
250 $wgOut->setSubtitle( wfMsg( 'difference' ) );
251 $wgOut->setRobotpolicy( 'noindex,follow' );
254 # Show current revision
256 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
257 $wgOut->addWikiText( $this->mNewtext
);
259 wfProfileOut( $fname );
262 function showDiff( $otext, $ntext, $otitle, $ntitle ) {
264 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
267 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
268 global $wgUseExternalDiffEngine, $wgContLang;
270 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
272 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
273 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
276 $otext = $wgContLang->segmentForDiff($otext);
277 $ntext = $wgContLang->segmentForDiff($ntext);
279 if ( $wgUseExternalDiffEngine ) {
280 # For historical reasons, external diff engine expects
281 # input text to be HTML-escaped already
282 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
283 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
284 if( !function_exists( 'wikidiff_do_diff' ) ) {
285 dl('php_wikidiff.so');
287 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
289 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
290 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
291 $diffs =& new Diff( $ota, $nta );
292 $formatter =& new TableDiffFormatter();
293 $difftext = $formatter->format( $diffs );
295 $difftext = $wgContLang->unsegmentForDiff($difftext);
296 $out .= $difftext."</table>\n";
301 * Load the text of the articles to compare. If newid is 0, then compare
302 * the old article in oldid to the current article; if oldid is 0, then
303 * compare the current article to the immediately previous one (ignoring the
306 function loadText() {
307 global $wgTitle, $wgOut, $wgLang;
308 $fname = 'DifferenceEngine::loadText';
310 $dbr =& wfGetDB( DB_SLAVE
);
311 if( $this->mNewid
) {
312 $this->newRev
=& Revision
::newFromId( $this->mNewid
);
314 $this->newRev
=& Revision
::newFromTitle( $wgTitle );
316 if( is_null( $this->newRev
) ) {
320 if( $this->newRev
->isCurrent() ) {
321 $wgOut->setArticleFlag( true );
322 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
323 $this->mNewPage
= $wgTitle;
324 $newLink = $this->mNewPage
->escapeLocalUrl();
325 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
327 $this->mNewPage
= $this->newRev
->getTitle();
328 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
329 $t = $wgLang->timeanddate( $this->newRev
->getTimestamp(), true );
330 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
331 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
334 if( $this->mOldid
) {
335 $this->oldRev
=& Revision
::newFromId( $this->mOldid
);
337 $this->oldRev
=& $this->newRev
->getPrevious();
338 $this->mOldid
= $this->oldRev
->getId();
340 if( is_null( $this->oldRev
) ) {
344 $this->mOldPage
= $this->oldRev
->getTitle();
346 $t = $wgLang->timeanddate( $this->oldRev
->getTimestamp(), true );
347 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
348 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
350 $this->mNewUser
= $this->newRev
->getUserText();
351 $this->mNewComment
= $this->newRev
->getComment();
352 $this->mNewtext
= $this->newRev
->getText();
354 $this->mOldUser
= $this->oldRev
->getUserText();
355 $this->mOldComment
= $this->oldRev
->getComment();
356 $this->mOldtext
= $this->oldRev
->getText();
362 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
364 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
365 // You may copy this code freely under the conditions of the GPL.
368 define('USE_ASSERTS', function_exists('assert'));
374 * @subpackage DifferenceEngine
382 trigger_error('pure virtual', E_USER_ERROR
);
386 return $this->orig ?
sizeof($this->orig
) : 0;
389 function nclosing() {
390 return $this->closing ?
sizeof($this->closing
) : 0;
398 * @subpackage DifferenceEngine
400 class _DiffOp_Copy
extends _DiffOp
{
403 function _DiffOp_Copy ($orig, $closing = false) {
404 if (!is_array($closing))
407 $this->closing
= $closing;
411 return new _DiffOp_Copy($this->closing
, $this->orig
);
419 * @subpackage DifferenceEngine
421 class _DiffOp_Delete
extends _DiffOp
{
422 var $type = 'delete';
424 function _DiffOp_Delete ($lines) {
425 $this->orig
= $lines;
426 $this->closing
= false;
430 return new _DiffOp_Add($this->orig
);
438 * @subpackage DifferenceEngine
440 class _DiffOp_Add
extends _DiffOp
{
443 function _DiffOp_Add ($lines) {
444 $this->closing
= $lines;
449 return new _DiffOp_Delete($this->closing
);
457 * @subpackage DifferenceEngine
459 class _DiffOp_Change
extends _DiffOp
{
460 var $type = 'change';
462 function _DiffOp_Change ($orig, $closing) {
464 $this->closing
= $closing;
468 return new _DiffOp_Change($this->closing
, $this->orig
);
474 * Class used internally by Diff to actually compute the diffs.
476 * The algorithm used here is mostly lifted from the perl module
477 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
478 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
480 * More ideas are taken from:
481 * http://www.ics.uci.edu/~eppstein/161/960229.html
483 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
484 * diffutils-2.7, which can be found at:
485 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
487 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
490 * @author Geoffrey T. Dairiki
493 * @subpackage DifferenceEngine
497 function diff ($from_lines, $to_lines) {
498 $fname = '_DiffEngine::diff';
499 wfProfileIn( $fname );
501 $n_from = sizeof($from_lines);
502 $n_to = sizeof($to_lines);
504 $this->xchanged
= $this->ychanged
= array();
505 $this->xv
= $this->yv
= array();
506 $this->xind
= $this->yind
= array();
508 unset($this->in_seq
);
511 // Skip leading common lines.
512 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
513 if ($from_lines[$skip] != $to_lines[$skip])
515 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
517 // Skip trailing common lines.
518 $xi = $n_from; $yi = $n_to;
519 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
520 if ($from_lines[$xi] != $to_lines[$yi])
522 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
525 // Ignore lines which do not exist in both files.
526 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
527 $xhash[$from_lines[$xi]] = 1;
528 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
529 $line = $to_lines[$yi];
530 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
536 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
537 $line = $from_lines[$xi];
538 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
545 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
547 // Merge edits when possible
548 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
549 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
551 // Compute the edit operations.
554 while ($xi < $n_from ||
$yi < $n_to) {
555 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
556 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
558 // Skip matching "snake".
560 while ( $xi < $n_from && $yi < $n_to
561 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
562 $copy[] = $from_lines[$xi++
];
566 $edits[] = new _DiffOp_Copy($copy);
568 // Find deletes & adds.
570 while ($xi < $n_from && $this->xchanged
[$xi])
571 $delete[] = $from_lines[$xi++
];
574 while ($yi < $n_to && $this->ychanged
[$yi])
575 $add[] = $to_lines[$yi++
];
578 $edits[] = new _DiffOp_Change($delete, $add);
580 $edits[] = new _DiffOp_Delete($delete);
582 $edits[] = new _DiffOp_Add($add);
584 wfProfileOut( $fname );
589 /* Divide the Largest Common Subsequence (LCS) of the sequences
590 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
593 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
594 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
595 * sub sequences. The first sub-sequence is contained in [X0, X1),
596 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
597 * that (X0, Y0) == (XOFF, YOFF) and
598 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
600 * This function assumes that the first lines of the specified portions
601 * of the two files do not match, and likewise that the last lines do not
602 * match. The caller must trim matching lines from the beginning and end
603 * of the portions it is going to specify.
605 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
606 $fname = '_DiffEngine::_diag';
607 wfProfileIn( $fname );
610 if ($xlim - $xoff > $ylim - $yoff) {
611 // Things seems faster (I'm not sure I understand why)
612 // when the shortest sequence in X.
614 list ($xoff, $xlim, $yoff, $ylim)
615 = array( $yoff, $ylim, $xoff, $xlim);
619 for ($i = $ylim - 1; $i >= $yoff; $i--)
620 $ymatches[$this->xv
[$i]][] = $i;
622 for ($i = $ylim - 1; $i >= $yoff; $i--)
623 $ymatches[$this->yv
[$i]][] = $i;
626 $this->seq
[0]= $yoff - 1;
627 $this->in_seq
= array();
630 $numer = $xlim - $xoff +
$nchunks - 1;
632 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
633 wfProfileIn( "$fname-chunk" );
635 for ($i = 0; $i <= $this->lcs
; $i++
)
636 $ymids[$i][$chunk-1] = $this->seq
[$i];
638 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
639 for ( ; $x < $x1; $x++
) {
640 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
641 if (empty($ymatches[$line]))
643 $matches = $ymatches[$line];
645 while (list ($junk, $y) = each($matches))
646 if (empty($this->in_seq
[$y])) {
647 $k = $this->_lcs_pos($y);
648 USE_ASSERTS
&& assert($k > 0);
649 $ymids[$k] = $ymids[$k-1];
652 while (list ($junk, $y) = each($matches)) {
653 if ($y > $this->seq
[$k-1]) {
654 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
655 // Optimization: this is a common case:
656 // next match is just replacing previous match.
657 $this->in_seq
[$this->seq
[$k]] = false;
659 $this->in_seq
[$y] = 1;
660 } else if (empty($this->in_seq
[$y])) {
661 $k = $this->_lcs_pos($y);
662 USE_ASSERTS
&& assert($k > 0);
663 $ymids[$k] = $ymids[$k-1];
667 wfProfileOut( "$fname-chunk" );
670 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
671 $ymid = $ymids[$this->lcs
];
672 for ($n = 0; $n < $nchunks - 1; $n++
) {
673 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
675 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
677 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
679 wfProfileOut( $fname );
680 return array($this->lcs
, $seps);
683 function _lcs_pos ($ypos) {
684 $fname = '_DiffEngine::_lcs_pos';
685 wfProfileIn( $fname );
688 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
689 $this->seq
[++
$this->lcs
] = $ypos;
690 $this->in_seq
[$ypos] = 1;
691 wfProfileOut( $fname );
696 while ($beg < $end) {
697 $mid = (int)(($beg +
$end) / 2);
698 if ( $ypos > $this->seq
[$mid] )
704 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
706 $this->in_seq
[$this->seq
[$end]] = false;
707 $this->seq
[$end] = $ypos;
708 $this->in_seq
[$ypos] = 1;
709 wfProfileOut( $fname );
713 /* Find LCS of two sequences.
715 * The results are recorded in the vectors $this->{x,y}changed[], by
716 * storing a 1 in the element for each line that is an insertion
717 * or deletion (ie. is not in the LCS).
719 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
721 * Note that XLIM, YLIM are exclusive bounds.
722 * All line numbers are origin-0 and discarded lines are not counted.
724 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
725 $fname = '_DiffEngine::_compareseq';
726 wfProfileIn( $fname );
728 // Slide down the bottom initial diagonal.
729 while ($xoff < $xlim && $yoff < $ylim
730 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
735 // Slide up the top initial diagonal.
736 while ($xlim > $xoff && $ylim > $yoff
737 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
742 if ($xoff == $xlim ||
$yoff == $ylim)
745 // This is ad hoc but seems to work well.
746 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
747 //$nchunks = max(2,min(8,(int)$nchunks));
748 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
750 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
754 // X and Y sequences have no common subsequence:
756 while ($yoff < $ylim)
757 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
758 while ($xoff < $xlim)
759 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
761 // Use the partitions to split this problem into subproblems.
764 while ($pt2 = next($seps)) {
765 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
769 wfProfileOut( $fname );
772 /* Adjust inserts/deletes of identical lines to join changes
773 * as much as possible.
775 * We do something when a run of changed lines include a
776 * line at one end and has an excluded, identical line at the other.
777 * We are free to choose which identical line is included.
778 * `compareseq' usually chooses the one at the beginning,
779 * but usually it is cleaner to consider the following identical line
780 * to be the "change".
782 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
784 function _shift_boundaries ($lines, &$changed, $other_changed) {
785 $fname = '_DiffEngine::_shift_boundaries';
786 wfProfileIn( $fname );
790 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
791 $len = sizeof($lines);
792 $other_len = sizeof($other_changed);
796 * Scan forwards to find beginning of another run of changes.
797 * Also keep track of the corresponding point in the other file.
799 * Throughout this code, $i and $j are adjusted together so that
800 * the first $i elements of $changed and the first $j elements
801 * of $other_changed both contain the same number of zeros
803 * Furthermore, $j is always kept so that $j == $other_len or
804 * $other_changed[$j] == false.
806 while ($j < $other_len && $other_changed[$j])
809 while ($i < $len && ! $changed[$i]) {
810 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
812 while ($j < $other_len && $other_changed[$j])
821 // Find the end of this run of changes.
822 while (++
$i < $len && $changed[$i])
827 * Record the length of this run of changes, so that
828 * we can later determine whether the run has grown.
830 $runlength = $i - $start;
833 * Move the changed region back, so long as the
834 * previous unchanged line matches the last changed one.
835 * This merges with previous changed regions.
837 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
838 $changed[--$start] = 1;
839 $changed[--$i] = false;
840 while ($start > 0 && $changed[$start - 1])
842 USE_ASSERTS
&& assert('$j > 0');
843 while ($other_changed[--$j])
845 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
849 * Set CORRESPONDING to the end of the changed run, at the last
850 * point where it corresponds to a changed run in the other file.
851 * CORRESPONDING == LEN means no such point has been found.
853 $corresponding = $j < $other_len ?
$i : $len;
856 * Move the changed region forward, so long as the
857 * first changed line matches the following unchanged one.
858 * This merges with following changed regions.
859 * Do this second, so that if there are no merges,
860 * the changed region is moved forward as far as possible.
862 while ($i < $len && $lines[$start] == $lines[$i]) {
863 $changed[$start++
] = false;
865 while ($i < $len && $changed[$i])
868 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
870 if ($j < $other_len && $other_changed[$j]) {
872 while ($j < $other_len && $other_changed[$j])
876 } while ($runlength != $i - $start);
879 * If possible, move the fully-merged run of changes
880 * back to a corresponding run in the other file.
882 while ($corresponding < $i) {
883 $changed[--$start] = 1;
885 USE_ASSERTS
&& assert('$j > 0');
886 while ($other_changed[--$j])
888 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
891 wfProfileOut( $fname );
896 * Class representing a 'diff' between two sequences of strings.
900 * @subpackage DifferenceEngine
908 * Computes diff between sequences of strings.
910 * @param $from_lines array An array of strings.
911 * (Typically these are lines from a file.)
912 * @param $to_lines array An array of strings.
914 function Diff($from_lines, $to_lines) {
915 $eng = new _DiffEngine
;
916 $this->edits
= $eng->diff($from_lines, $to_lines);
917 //$this->_check($from_lines, $to_lines);
921 * Compute reversed Diff.
925 * $diff = new Diff($lines1, $lines2);
926 * $rev = $diff->reverse();
927 * @return object A Diff object representing the inverse of the
930 function reverse () {
932 $rev->edits
= array();
933 foreach ($this->edits
as $edit) {
934 $rev->edits
[] = $edit->reverse();
940 * Check for empty diff.
942 * @return bool True iff two sequences were identical.
944 function isEmpty () {
945 foreach ($this->edits
as $edit) {
946 if ($edit->type
!= 'copy')
953 * Compute the length of the Longest Common Subsequence (LCS).
955 * This is mostly for diagnostic purposed.
957 * @return int The length of the LCS.
961 foreach ($this->edits
as $edit) {
962 if ($edit->type
== 'copy')
963 $lcs +
= sizeof($edit->orig
);
969 * Get the original set of lines.
971 * This reconstructs the $from_lines parameter passed to the
974 * @return array The original sequence of strings.
979 foreach ($this->edits
as $edit) {
981 array_splice($lines, sizeof($lines), 0, $edit->orig
);
987 * Get the closing set of lines.
989 * This reconstructs the $to_lines parameter passed to the
992 * @return array The sequence of strings.
997 foreach ($this->edits
as $edit) {
999 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1005 * Check a Diff for validity.
1007 * This is here only for debugging purposes.
1009 function _check ($from_lines, $to_lines) {
1010 $fname = 'Diff::_check';
1011 wfProfileIn( $fname );
1012 if (serialize($from_lines) != serialize($this->orig()))
1013 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1014 if (serialize($to_lines) != serialize($this->closing()))
1015 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1017 $rev = $this->reverse();
1018 if (serialize($to_lines) != serialize($rev->orig()))
1019 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1020 if (serialize($from_lines) != serialize($rev->closing()))
1021 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1025 foreach ($this->edits
as $edit) {
1026 if ( $prevtype == $edit->type
)
1027 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1028 $prevtype = $edit->type
;
1031 $lcs = $this->lcs();
1032 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1033 wfProfileOut( $fname );
1041 * @package MediaWiki
1042 * @subpackage DifferenceEngine
1044 class MappedDiff
extends Diff
1049 * Computes diff between sequences of strings.
1051 * This can be used to compute things like
1052 * case-insensitve diffs, or diffs which ignore
1053 * changes in white-space.
1055 * @param $from_lines array An array of strings.
1056 * (Typically these are lines from a file.)
1058 * @param $to_lines array An array of strings.
1060 * @param $mapped_from_lines array This array should
1061 * have the same size number of elements as $from_lines.
1062 * The elements in $mapped_from_lines and
1063 * $mapped_to_lines are what is actually compared
1064 * when computing the diff.
1066 * @param $mapped_to_lines array This array should
1067 * have the same number of elements as $to_lines.
1069 function MappedDiff($from_lines, $to_lines,
1070 $mapped_from_lines, $mapped_to_lines) {
1071 $fname = 'MappedDiff::MappedDiff';
1072 wfProfileIn( $fname );
1074 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1075 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1077 $this->Diff($mapped_from_lines, $mapped_to_lines);
1080 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1081 $orig = &$this->edits
[$i]->orig
;
1082 if (is_array($orig)) {
1083 $orig = array_slice($from_lines, $xi, sizeof($orig));
1084 $xi +
= sizeof($orig);
1087 $closing = &$this->edits
[$i]->closing
;
1088 if (is_array($closing)) {
1089 $closing = array_slice($to_lines, $yi, sizeof($closing));
1090 $yi +
= sizeof($closing);
1093 wfProfileOut( $fname );
1098 * A class to format Diffs
1100 * This class formats the diff in classic diff format.
1101 * It is intended that this class be customized via inheritance,
1102 * to obtain fancier outputs.
1105 * @package MediaWiki
1106 * @subpackage DifferenceEngine
1111 * Number of leading 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 $leading_context_lines = 0;
1119 * Number of trailing context "lines" to preserve.
1121 * This should be left at zero for this class, but subclasses
1122 * may want to set this to other values.
1124 var $trailing_context_lines = 0;
1129 * @param $diff object A Diff object.
1130 * @return string The formatted output.
1132 function format($diff) {
1133 $fname = 'DiffFormatter::format';
1134 wfProfileIn( $fname );
1140 $nlead = $this->leading_context_lines
;
1141 $ntrail = $this->trailing_context_lines
;
1143 $this->_start_diff();
1145 foreach ($diff->edits
as $edit) {
1146 if ($edit->type
== 'copy') {
1147 if (is_array($block)) {
1148 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1153 $context = array_slice($edit->orig
, 0, $ntrail);
1154 $block[] = new _DiffOp_Copy($context);
1156 $this->_block($x0, $ntrail +
$xi - $x0,
1157 $y0, $ntrail +
$yi - $y0,
1162 $context = $edit->orig
;
1165 if (! is_array($block)) {
1166 $context = array_slice($context, sizeof($context) - $nlead);
1167 $x0 = $xi - sizeof($context);
1168 $y0 = $yi - sizeof($context);
1171 $block[] = new _DiffOp_Copy($context);
1177 $xi +
= sizeof($edit->orig
);
1179 $yi +
= sizeof($edit->closing
);
1182 if (is_array($block))
1183 $this->_block($x0, $xi - $x0,
1187 $end = $this->_end_diff();
1188 wfProfileOut( $fname );
1192 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1193 $fname = 'DiffFormatter::_block';
1194 wfProfileIn( $fname );
1195 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1196 foreach ($edits as $edit) {
1197 if ($edit->type
== 'copy')
1198 $this->_context($edit->orig
);
1199 elseif ($edit->type
== 'add')
1200 $this->_added($edit->closing
);
1201 elseif ($edit->type
== 'delete')
1202 $this->_deleted($edit->orig
);
1203 elseif ($edit->type
== 'change')
1204 $this->_changed($edit->orig
, $edit->closing
);
1206 trigger_error('Unknown edit type', E_USER_ERROR
);
1208 $this->_end_block();
1209 wfProfileOut( $fname );
1212 function _start_diff() {
1216 function _end_diff() {
1217 $val = ob_get_contents();
1222 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1224 $xbeg .= "," . ($xbeg +
$xlen - 1);
1226 $ybeg .= "," . ($ybeg +
$ylen - 1);
1228 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1231 function _start_block($header) {
1235 function _end_block() {
1238 function _lines($lines, $prefix = ' ') {
1239 foreach ($lines as $line)
1240 echo "$prefix $line\n";
1243 function _context($lines) {
1244 $this->_lines($lines);
1247 function _added($lines) {
1248 $this->_lines($lines, '>');
1250 function _deleted($lines) {
1251 $this->_lines($lines, '<');
1254 function _changed($orig, $closing) {
1255 $this->_deleted($orig);
1257 $this->_added($closing);
1263 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1267 define('NBSP', ' '); // iso-8859-x non-breaking space.
1272 * @package MediaWiki
1273 * @subpackage DifferenceEngine
1275 class _HWLDF_WordAccumulator
{
1276 function _HWLDF_WordAccumulator () {
1277 $this->_lines
= array();
1283 function _flushGroup ($new_tag) {
1284 if ($this->_group
!== '') {
1285 if ($this->_tag
== 'mark')
1286 $this->_line
.= '<span class="diffchange">' .
1287 htmlspecialchars ( $this->_group
) . '</span>';
1289 $this->_line
.= htmlspecialchars ( $this->_group
);
1292 $this->_tag
= $new_tag;
1295 function _flushLine ($new_tag) {
1296 $this->_flushGroup($new_tag);
1297 if ($this->_line
!= '')
1298 array_push ( $this->_lines
, $this->_line
);
1300 # make empty lines visible by inserting an NBSP
1301 array_push ( $this->_lines
, NBSP
);
1305 function addWords ($words, $tag = '') {
1306 if ($tag != $this->_tag
)
1307 $this->_flushGroup($tag);
1309 foreach ($words as $word) {
1310 // new-line should only come as first char of word.
1313 if ($word[0] == "\n") {
1314 $this->_flushLine($tag);
1315 $word = substr($word, 1);
1317 assert(!strstr($word, "\n"));
1318 $this->_group
.= $word;
1322 function getLines() {
1323 $this->_flushLine('~done');
1324 return $this->_lines
;
1331 * @package MediaWiki
1332 * @subpackage DifferenceEngine
1334 class WordLevelDiff
extends MappedDiff
1336 function WordLevelDiff ($orig_lines, $closing_lines) {
1337 $fname = 'WordLevelDiff::WordLevelDiff';
1338 wfProfileIn( $fname );
1340 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1341 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1344 $this->MappedDiff($orig_words, $closing_words,
1345 $orig_stripped, $closing_stripped);
1346 wfProfileOut( $fname );
1349 function _split($lines) {
1350 $fname = 'WordLevelDiff::_split';
1351 wfProfileIn( $fname );
1352 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1353 implode("\n", $lines),
1355 wfProfileOut( $fname );
1356 return array(array(''), array(''));
1358 wfProfileOut( $fname );
1359 return array($m[0], $m[1]);
1363 $fname = 'WordLevelDiff::orig';
1364 wfProfileIn( $fname );
1365 $orig = new _HWLDF_WordAccumulator
;
1367 foreach ($this->edits
as $edit) {
1368 if ($edit->type
== 'copy')
1369 $orig->addWords($edit->orig
);
1370 elseif ($edit->orig
)
1371 $orig->addWords($edit->orig
, 'mark');
1373 $lines = $orig->getLines();
1374 wfProfileOut( $fname );
1378 function closing () {
1379 $fname = 'WordLevelDiff::closing';
1380 wfProfileIn( $fname );
1381 $closing = new _HWLDF_WordAccumulator
;
1383 foreach ($this->edits
as $edit) {
1384 if ($edit->type
== 'copy')
1385 $closing->addWords($edit->closing
);
1386 elseif ($edit->closing
)
1387 $closing->addWords($edit->closing
, 'mark');
1389 $lines = $closing->getLines();
1390 wfProfileOut( $fname );
1396 * Wikipedia Table style diff formatter.
1399 * @package MediaWiki
1400 * @subpackage DifferenceEngine
1402 class TableDiffFormatter
extends DiffFormatter
1404 function TableDiffFormatter() {
1405 $this->leading_context_lines
= 2;
1406 $this->trailing_context_lines
= 2;
1409 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1410 $l1 = wfMsg( 'lineno', $xbeg );
1411 $l2 = wfMsg( 'lineno', $ybeg );
1413 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1414 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1418 function _start_block( $header ) {
1423 function _end_block() {
1426 function _lines( $lines, $prefix=' ', $color='white' ) {
1429 # HTML-escape parameter before calling this
1430 function addedLine( $line ) {
1431 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1434 # HTML-escape parameter before calling this
1435 function deletedLine( $line ) {
1436 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1439 # HTML-escape parameter before calling this
1440 function contextLine( $line ) {
1441 return "<td> </td><td class='diff-context'>{$line}</td>";
1444 function emptyLine() {
1445 return '<td colspan="2"> </td>';
1448 function _added( $lines ) {
1449 foreach ($lines as $line) {
1450 echo '<tr>' . $this->emptyLine() .
1451 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1455 function _deleted($lines) {
1456 foreach ($lines as $line) {
1457 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1458 $this->emptyLine() . "</tr>\n";
1462 function _context( $lines ) {
1463 foreach ($lines as $line) {
1465 $this->contextLine( htmlspecialchars ( $line ) ) .
1466 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1470 function _changed( $orig, $closing ) {
1471 $fname = 'TableDiffFormatter::_changed';
1472 wfProfileIn( $fname );
1474 $diff = new WordLevelDiff( $orig, $closing );
1475 $del = $diff->orig();
1476 $add = $diff->closing();
1478 # Notice that WordLevelDiff returns HTML-escaped output.
1479 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1481 while ( $line = array_shift( $del ) ) {
1482 $aline = array_shift( $add );
1483 echo '<tr>' . $this->deletedLine( $line ) .
1484 $this->addedLine( $aline ) . "</tr>\n";
1486 foreach ($add as $line) { # If any leftovers
1487 echo '<tr>' . $this->emptyLine() .
1488 $this->addedLine( $line ) . "</tr>\n";
1490 wfProfileOut( $fname );