5 * @subpackage DifferenceEngine
9 require_once( 'Revision.php' );
15 * @subpackage DifferenceEngine
17 class DifferenceEngine
{
18 /* private */ var $mOldid, $mNewid;
19 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
20 /* private */ var $mOldtext, $mNewtext;
21 /* private */ var $mOldUser, $mNewUser;
22 /* private */ var $mOldComment, $mNewComment;
23 /* private */ var $mOldPage, $mNewPage;
24 /* private */ var $mRcidMarkPatrolled;
26 function DifferenceEngine( $old, $new, $rcid = 0 )
29 if ( 'prev' == $new ) {
30 # Show diff between revision $old and the previous one.
31 # Get previous one from DB.
33 $this->mNewid
= intval($old);
35 $this->mOldid
= $wgTitle->getPreviousRevisionID( $this->mNewid
);
37 } elseif ( 'next' == $new ) {
39 # Show diff between revision $old and the previous one.
40 # Get previous one from DB.
42 $this->mOldid
= intval($old);
43 $this->mNewid
= $wgTitle->getNextRevisionID( $this->mOldid
);
44 if ( false === $this->mNewid
) {
45 # if no result, NewId points to the newest old revision. The only newer
46 # revision is cur, which is "0".
52 $this->mOldid
= intval($old);
53 $this->mNewid
= intval($new);
55 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
58 function showDiffPage()
60 global $wgUser, $wgTitle, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
61 $fname = 'DifferenceEngine::showDiffPage';
62 wfProfileIn( $fname );
64 # mOldid is false if the difference engine is called with a "vague" query for
65 # a diff between a version V and its previous version V' AND the version V
66 # is the first version of that article. In that case, V' does not exist.
67 if ( $this->mOldid
=== false ) {
68 $this->showFirstRevision();
69 wfProfileOut( $fname );
73 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
75 $mtext = wfMsg( 'missingarticle', $t );
77 $wgOut->setArticleFlag( false );
78 if ( ! $this->loadText() ) {
79 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
80 $wgOut->addHTML( $mtext );
81 wfProfileOut( $fname );
84 $wgOut->suppressQuickbar();
86 $oldTitle = $this->mOldPage
->getPrefixedText();
87 $newTitle = $this->mNewPage
->getPrefixedText();
88 if( $oldTitle == $newTitle ) {
89 $wgOut->setPageTitle( $newTitle );
91 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
93 $wgOut->setSubtitle( wfMsg( 'difference' ) );
94 $wgOut->setRobotpolicy( 'noindex,follow' );
96 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
99 wfProfileOut( $fname );
103 $sk = $wgUser->getSkin();
104 $talk = $wgContLang->getNsText( NS_TALK
);
105 $contribs = wfMsg( 'contribslink' );
107 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
108 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
110 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
111 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
112 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
113 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
114 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
115 'target=' . urlencode($this->mOldUser
) );
116 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
117 'target=' . urlencode($this->mNewUser
) );
118 if ( !$this->mNewid
&& $wgUser->isAllowed('rollback') ) {
119 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
120 'action=rollback&from=' . urlencode($this->mNewUser
) .
121 '&token=' . urlencode( $wgUser->editToken( array( $wgTitle->getPrefixedText(), $this->mNewUser
) ) ) ) .
126 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isLoggedIn() &&
127 ( $wgUser->isAllowed('rollback') ||
!$wgOnlySysopsCanPatrol ) )
129 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
130 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
135 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
136 if ( $this->mNewid
== 0 ) {
139 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
142 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
143 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
144 '<br />' . $prevlink;
145 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
146 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
147 '<br />' . $nextlink . $patrol;
149 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
150 $oldHeader, $newHeader );
151 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
152 $wgOut->addWikiText( $this->mNewtext
);
154 wfProfileOut( $fname );
157 # Show the first revision of an article. Uses normal diff headers in contrast to normal
158 # "old revision" display style.
160 function showFirstRevision()
162 global $wgOut, $wgTitle, $wgUser, $wgLang;
164 $fname = 'DifferenceEngine::showFirstRevision';
165 wfProfileIn( $fname );
168 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
170 # Get article text from the DB
172 if ( ! $this->loadText() ) {
173 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
175 $mtext = wfMsg( 'missingarticle', $t );
176 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
177 $wgOut->addHTML( $mtext );
178 wfProfileOut( $fname );
182 # Check if user is allowed to look at this page. If not, bail out.
184 if ( !( $this->mOldPage
->userCanRead() ) ) {
185 $wgOut->loginToUse();
187 wfProfileOut( $fname );
191 # Prepare the header box
193 $sk = $wgUser->getSkin();
195 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
196 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
197 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
198 'target=' . urlencode($this->mOldUser
) );
199 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
200 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
201 "($uTLink | $contribs)<br />" . $this->mOldComment
.
202 '<br />' . $nextlink. "</div>\n";
204 $wgOut->addHTML( $header );
206 $wgOut->setSubtitle( wfMsg( 'difference' ) );
207 $wgOut->setRobotpolicy( 'noindex,follow' );
210 # Show current revision
212 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
213 $wgOut->addWikiText( $this->mNewtext
);
215 wfProfileOut( $fname );
218 function showDiff( $otext, $ntext, $otitle, $ntitle )
221 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
224 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
225 global $wgUseExternalDiffEngine, $wgContLang;
227 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
229 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
230 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
233 $otext = $wgContLang->segmentForDiff($otext);
234 $ntext = $wgContLang->segmentForDiff($ntext);
236 if ( $wgUseExternalDiffEngine ) {
237 # For historical reasons, external diff engine expects
238 # input text to be HTML-escaped already
239 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
240 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
241 if( !function_exists( 'wikidiff_do_diff' ) ) {
242 dl('php_wikidiff.so');
244 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
246 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
247 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
248 $diffs =& new Diff( $ota, $nta );
249 $formatter =& new TableDiffFormatter();
250 $difftext = $formatter->format( $diffs );
252 $difftext = $wgContLang->unsegmentForDiff($difftext);
253 $out .= $difftext."</table>\n";
257 # Load the text of the articles to compare. If newid is 0, then compare
258 # the old article in oldid to the current article; if oldid is 0, then
259 # compare the current article to the immediately previous one (ignoring
260 # the value of newid).
264 global $wgTitle, $wgOut, $wgLang;
265 $fname = 'DifferenceEngine::loadText';
267 $dbr =& wfGetDB( DB_SLAVE
);
268 if( $this->mNewid
) {
269 $this->newRev
=& Revision
::newFromId( $this->mNewid
);
271 $this->newRev
=& Revision
::newFromTitle( $wgTitle );
274 if( $this->newRev
->isCurrent() ) {
275 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
276 $this->mNewPage
= $wgTitle;
277 $newLink = $this->mNewPage
->escapeLocalUrl();
278 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
280 $this->mNewPage
= $this->newRev
->getTitle();
281 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
282 $t = $wgLang->timeanddate( $this->newRev
->getTimestamp(), true );
283 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
284 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
287 if( $this->mOldid
) {
288 $this->oldRev
=& Revision
::newFromId( $this->mOldid
);
290 $this->oldRev
=& $this->newRev
->getPrevious();
291 $this->mOldid
= $this->oldRev
->getId();
294 $this->mOldPage
= $this->oldRev
->getTitle();
296 $t = $wgLang->timeanddate( $this->oldRev
->getTimestamp(), true );
297 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
298 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
300 $this->mNewUser
= $this->newRev
->getUserText();
301 $this->mNewComment
= $this->newRev
->getComment();
302 $this->mNewtext
= $this->newRev
->getText();
304 $this->mOldUser
= $this->oldRev
->getUserText();
305 $this->mOldComment
= $this->oldRev
->getComment();
306 $this->mOldtext
= $this->oldRev
->getText();
312 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
314 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
315 // You may copy this code freely under the conditions of the GPL.
318 define('USE_ASSERTS', function_exists('assert'));
324 * @subpackage DifferenceEngine
332 trigger_error('pure virtual', E_USER_ERROR
);
336 return $this->orig ?
sizeof($this->orig
) : 0;
339 function nclosing() {
340 return $this->closing ?
sizeof($this->closing
) : 0;
348 * @subpackage DifferenceEngine
350 class _DiffOp_Copy
extends _DiffOp
{
353 function _DiffOp_Copy ($orig, $closing = false) {
354 if (!is_array($closing))
357 $this->closing
= $closing;
361 return new _DiffOp_Copy($this->closing
, $this->orig
);
369 * @subpackage DifferenceEngine
371 class _DiffOp_Delete
extends _DiffOp
{
372 var $type = 'delete';
374 function _DiffOp_Delete ($lines) {
375 $this->orig
= $lines;
376 $this->closing
= false;
380 return new _DiffOp_Add($this->orig
);
388 * @subpackage DifferenceEngine
390 class _DiffOp_Add
extends _DiffOp
{
393 function _DiffOp_Add ($lines) {
394 $this->closing
= $lines;
399 return new _DiffOp_Delete($this->closing
);
407 * @subpackage DifferenceEngine
409 class _DiffOp_Change
extends _DiffOp
{
410 var $type = 'change';
412 function _DiffOp_Change ($orig, $closing) {
414 $this->closing
= $closing;
418 return new _DiffOp_Change($this->closing
, $this->orig
);
424 * Class used internally by Diff to actually compute the diffs.
426 * The algorithm used here is mostly lifted from the perl module
427 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
428 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
430 * More ideas are taken from:
431 * http://www.ics.uci.edu/~eppstein/161/960229.html
433 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
434 * diffutils-2.7, which can be found at:
435 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
437 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
440 * @author Geoffrey T. Dairiki
443 * @subpackage DifferenceEngine
447 function diff ($from_lines, $to_lines) {
448 $fname = '_DiffEngine::diff';
449 wfProfileIn( $fname );
451 $n_from = sizeof($from_lines);
452 $n_to = sizeof($to_lines);
454 $this->xchanged
= $this->ychanged
= array();
455 $this->xv
= $this->yv
= array();
456 $this->xind
= $this->yind
= array();
458 unset($this->in_seq
);
461 // Skip leading common lines.
462 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
463 if ($from_lines[$skip] != $to_lines[$skip])
465 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
467 // Skip trailing common lines.
468 $xi = $n_from; $yi = $n_to;
469 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
470 if ($from_lines[$xi] != $to_lines[$yi])
472 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
475 // Ignore lines which do not exist in both files.
476 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
477 $xhash[$from_lines[$xi]] = 1;
478 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
479 $line = $to_lines[$yi];
480 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
486 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
487 $line = $from_lines[$xi];
488 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
495 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
497 // Merge edits when possible
498 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
499 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
501 // Compute the edit operations.
504 while ($xi < $n_from ||
$yi < $n_to) {
505 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
506 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
508 // Skip matching "snake".
510 while ( $xi < $n_from && $yi < $n_to
511 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
512 $copy[] = $from_lines[$xi++
];
516 $edits[] = new _DiffOp_Copy($copy);
518 // Find deletes & adds.
520 while ($xi < $n_from && $this->xchanged
[$xi])
521 $delete[] = $from_lines[$xi++
];
524 while ($yi < $n_to && $this->ychanged
[$yi])
525 $add[] = $to_lines[$yi++
];
528 $edits[] = new _DiffOp_Change($delete, $add);
530 $edits[] = new _DiffOp_Delete($delete);
532 $edits[] = new _DiffOp_Add($add);
534 wfProfileOut( $fname );
539 /* Divide the Largest Common Subsequence (LCS) of the sequences
540 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
543 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
544 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
545 * sub sequences. The first sub-sequence is contained in [X0, X1),
546 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
547 * that (X0, Y0) == (XOFF, YOFF) and
548 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
550 * This function assumes that the first lines of the specified portions
551 * of the two files do not match, and likewise that the last lines do not
552 * match. The caller must trim matching lines from the beginning and end
553 * of the portions it is going to specify.
555 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
556 $fname = '_DiffEngine::_diag';
557 wfProfileIn( $fname );
560 if ($xlim - $xoff > $ylim - $yoff) {
561 // Things seems faster (I'm not sure I understand why)
562 // when the shortest sequence in X.
564 list ($xoff, $xlim, $yoff, $ylim)
565 = array( $yoff, $ylim, $xoff, $xlim);
569 for ($i = $ylim - 1; $i >= $yoff; $i--)
570 $ymatches[$this->xv
[$i]][] = $i;
572 for ($i = $ylim - 1; $i >= $yoff; $i--)
573 $ymatches[$this->yv
[$i]][] = $i;
576 $this->seq
[0]= $yoff - 1;
577 $this->in_seq
= array();
580 $numer = $xlim - $xoff +
$nchunks - 1;
582 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
583 wfProfileIn( "$fname-chunk" );
585 for ($i = 0; $i <= $this->lcs
; $i++
)
586 $ymids[$i][$chunk-1] = $this->seq
[$i];
588 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
589 for ( ; $x < $x1; $x++
) {
590 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
591 if (empty($ymatches[$line]))
593 $matches = $ymatches[$line];
595 while (list ($junk, $y) = each($matches))
596 if (empty($this->in_seq
[$y])) {
597 $k = $this->_lcs_pos($y);
598 USE_ASSERTS
&& assert($k > 0);
599 $ymids[$k] = $ymids[$k-1];
602 while (list ($junk, $y) = each($matches)) {
603 if ($y > $this->seq
[$k-1]) {
604 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
605 // Optimization: this is a common case:
606 // next match is just replacing previous match.
607 $this->in_seq
[$this->seq
[$k]] = false;
609 $this->in_seq
[$y] = 1;
610 } else if (empty($this->in_seq
[$y])) {
611 $k = $this->_lcs_pos($y);
612 USE_ASSERTS
&& assert($k > 0);
613 $ymids[$k] = $ymids[$k-1];
617 wfProfileOut( "$fname-chunk" );
620 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
621 $ymid = $ymids[$this->lcs
];
622 for ($n = 0; $n < $nchunks - 1; $n++
) {
623 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
625 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
627 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
629 wfProfileOut( $fname );
630 return array($this->lcs
, $seps);
633 function _lcs_pos ($ypos) {
634 $fname = '_DiffEngine::_lcs_pos';
635 wfProfileIn( $fname );
638 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
639 $this->seq
[++
$this->lcs
] = $ypos;
640 $this->in_seq
[$ypos] = 1;
641 wfProfileOut( $fname );
646 while ($beg < $end) {
647 $mid = (int)(($beg +
$end) / 2);
648 if ( $ypos > $this->seq
[$mid] )
654 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
656 $this->in_seq
[$this->seq
[$end]] = false;
657 $this->seq
[$end] = $ypos;
658 $this->in_seq
[$ypos] = 1;
659 wfProfileOut( $fname );
663 /* Find LCS of two sequences.
665 * The results are recorded in the vectors $this->{x,y}changed[], by
666 * storing a 1 in the element for each line that is an insertion
667 * or deletion (ie. is not in the LCS).
669 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
671 * Note that XLIM, YLIM are exclusive bounds.
672 * All line numbers are origin-0 and discarded lines are not counted.
674 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
675 $fname = '_DiffEngine::_compareseq';
676 wfProfileIn( $fname );
678 // Slide down the bottom initial diagonal.
679 while ($xoff < $xlim && $yoff < $ylim
680 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
685 // Slide up the top initial diagonal.
686 while ($xlim > $xoff && $ylim > $yoff
687 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
692 if ($xoff == $xlim ||
$yoff == $ylim)
695 // This is ad hoc but seems to work well.
696 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
697 //$nchunks = max(2,min(8,(int)$nchunks));
698 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
700 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
704 // X and Y sequences have no common subsequence:
706 while ($yoff < $ylim)
707 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
708 while ($xoff < $xlim)
709 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
711 // Use the partitions to split this problem into subproblems.
714 while ($pt2 = next($seps)) {
715 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
719 wfProfileOut( $fname );
722 /* Adjust inserts/deletes of identical lines to join changes
723 * as much as possible.
725 * We do something when a run of changed lines include a
726 * line at one end and has an excluded, identical line at the other.
727 * We are free to choose which identical line is included.
728 * `compareseq' usually chooses the one at the beginning,
729 * but usually it is cleaner to consider the following identical line
730 * to be the "change".
732 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
734 function _shift_boundaries ($lines, &$changed, $other_changed) {
735 $fname = '_DiffEngine::_shift_boundaries';
736 wfProfileIn( $fname );
740 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
741 $len = sizeof($lines);
742 $other_len = sizeof($other_changed);
746 * Scan forwards to find beginning of another run of changes.
747 * Also keep track of the corresponding point in the other file.
749 * Throughout this code, $i and $j are adjusted together so that
750 * the first $i elements of $changed and the first $j elements
751 * of $other_changed both contain the same number of zeros
753 * Furthermore, $j is always kept so that $j == $other_len or
754 * $other_changed[$j] == false.
756 while ($j < $other_len && $other_changed[$j])
759 while ($i < $len && ! $changed[$i]) {
760 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
762 while ($j < $other_len && $other_changed[$j])
771 // Find the end of this run of changes.
772 while (++
$i < $len && $changed[$i])
777 * Record the length of this run of changes, so that
778 * we can later determine whether the run has grown.
780 $runlength = $i - $start;
783 * Move the changed region back, so long as the
784 * previous unchanged line matches the last changed one.
785 * This merges with previous changed regions.
787 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
788 $changed[--$start] = 1;
789 $changed[--$i] = false;
790 while ($start > 0 && $changed[$start - 1])
792 USE_ASSERTS
&& assert('$j > 0');
793 while ($other_changed[--$j])
795 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
799 * Set CORRESPONDING to the end of the changed run, at the last
800 * point where it corresponds to a changed run in the other file.
801 * CORRESPONDING == LEN means no such point has been found.
803 $corresponding = $j < $other_len ?
$i : $len;
806 * Move the changed region forward, so long as the
807 * first changed line matches the following unchanged one.
808 * This merges with following changed regions.
809 * Do this second, so that if there are no merges,
810 * the changed region is moved forward as far as possible.
812 while ($i < $len && $lines[$start] == $lines[$i]) {
813 $changed[$start++
] = false;
815 while ($i < $len && $changed[$i])
818 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
820 if ($j < $other_len && $other_changed[$j]) {
822 while ($j < $other_len && $other_changed[$j])
826 } while ($runlength != $i - $start);
829 * If possible, move the fully-merged run of changes
830 * back to a corresponding run in the other file.
832 while ($corresponding < $i) {
833 $changed[--$start] = 1;
835 USE_ASSERTS
&& assert('$j > 0');
836 while ($other_changed[--$j])
838 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
841 wfProfileOut( $fname );
846 * Class representing a 'diff' between two sequences of strings.
850 * @subpackage DifferenceEngine
858 * Computes diff between sequences of strings.
860 * @param $from_lines array An array of strings.
861 * (Typically these are lines from a file.)
862 * @param $to_lines array An array of strings.
864 function Diff($from_lines, $to_lines) {
865 $eng = new _DiffEngine
;
866 $this->edits
= $eng->diff($from_lines, $to_lines);
867 //$this->_check($from_lines, $to_lines);
871 * Compute reversed Diff.
875 * $diff = new Diff($lines1, $lines2);
876 * $rev = $diff->reverse();
877 * @return object A Diff object representing the inverse of the
880 function reverse () {
882 $rev->edits
= array();
883 foreach ($this->edits
as $edit) {
884 $rev->edits
[] = $edit->reverse();
890 * Check for empty diff.
892 * @return bool True iff two sequences were identical.
894 function isEmpty () {
895 foreach ($this->edits
as $edit) {
896 if ($edit->type
!= 'copy')
903 * Compute the length of the Longest Common Subsequence (LCS).
905 * This is mostly for diagnostic purposed.
907 * @return int The length of the LCS.
911 foreach ($this->edits
as $edit) {
912 if ($edit->type
== 'copy')
913 $lcs +
= sizeof($edit->orig
);
919 * Get the original set of lines.
921 * This reconstructs the $from_lines parameter passed to the
924 * @return array The original sequence of strings.
929 foreach ($this->edits
as $edit) {
931 array_splice($lines, sizeof($lines), 0, $edit->orig
);
937 * Get the closing set of lines.
939 * This reconstructs the $to_lines parameter passed to the
942 * @return array The sequence of strings.
947 foreach ($this->edits
as $edit) {
949 array_splice($lines, sizeof($lines), 0, $edit->closing
);
955 * Check a Diff for validity.
957 * This is here only for debugging purposes.
959 function _check ($from_lines, $to_lines) {
960 $fname = 'Diff::_check';
961 wfProfileIn( $fname );
962 if (serialize($from_lines) != serialize($this->orig()))
963 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
964 if (serialize($to_lines) != serialize($this->closing()))
965 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
967 $rev = $this->reverse();
968 if (serialize($to_lines) != serialize($rev->orig()))
969 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
970 if (serialize($from_lines) != serialize($rev->closing()))
971 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
975 foreach ($this->edits
as $edit) {
976 if ( $prevtype == $edit->type
)
977 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
978 $prevtype = $edit->type
;
982 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
983 wfProfileOut( $fname );
992 * @subpackage DifferenceEngine
994 class MappedDiff
extends Diff
999 * Computes diff between sequences of strings.
1001 * This can be used to compute things like
1002 * case-insensitve diffs, or diffs which ignore
1003 * changes in white-space.
1005 * @param $from_lines array An array of strings.
1006 * (Typically these are lines from a file.)
1008 * @param $to_lines array An array of strings.
1010 * @param $mapped_from_lines array This array should
1011 * have the same size number of elements as $from_lines.
1012 * The elements in $mapped_from_lines and
1013 * $mapped_to_lines are what is actually compared
1014 * when computing the diff.
1016 * @param $mapped_to_lines array This array should
1017 * have the same number of elements as $to_lines.
1019 function MappedDiff($from_lines, $to_lines,
1020 $mapped_from_lines, $mapped_to_lines) {
1021 $fname = 'MappedDiff::MappedDiff';
1022 wfProfileIn( $fname );
1024 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1025 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1027 $this->Diff($mapped_from_lines, $mapped_to_lines);
1030 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1031 $orig = &$this->edits
[$i]->orig
;
1032 if (is_array($orig)) {
1033 $orig = array_slice($from_lines, $xi, sizeof($orig));
1034 $xi +
= sizeof($orig);
1037 $closing = &$this->edits
[$i]->closing
;
1038 if (is_array($closing)) {
1039 $closing = array_slice($to_lines, $yi, sizeof($closing));
1040 $yi +
= sizeof($closing);
1043 wfProfileOut( $fname );
1048 * A class to format Diffs
1050 * This class formats the diff in classic diff format.
1051 * It is intended that this class be customized via inheritance,
1052 * to obtain fancier outputs.
1055 * @package MediaWiki
1056 * @subpackage DifferenceEngine
1061 * Number of leading context "lines" to preserve.
1063 * This should be left at zero for this class, but subclasses
1064 * may want to set this to other values.
1066 var $leading_context_lines = 0;
1069 * Number of trailing context "lines" to preserve.
1071 * This should be left at zero for this class, but subclasses
1072 * may want to set this to other values.
1074 var $trailing_context_lines = 0;
1079 * @param $diff object A Diff object.
1080 * @return string The formatted output.
1082 function format($diff) {
1083 $fname = 'DiffFormatter::format';
1084 wfProfileIn( $fname );
1090 $nlead = $this->leading_context_lines
;
1091 $ntrail = $this->trailing_context_lines
;
1093 $this->_start_diff();
1095 foreach ($diff->edits
as $edit) {
1096 if ($edit->type
== 'copy') {
1097 if (is_array($block)) {
1098 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1103 $context = array_slice($edit->orig
, 0, $ntrail);
1104 $block[] = new _DiffOp_Copy($context);
1106 $this->_block($x0, $ntrail +
$xi - $x0,
1107 $y0, $ntrail +
$yi - $y0,
1112 $context = $edit->orig
;
1115 if (! is_array($block)) {
1116 $context = array_slice($context, sizeof($context) - $nlead);
1117 $x0 = $xi - sizeof($context);
1118 $y0 = $yi - sizeof($context);
1121 $block[] = new _DiffOp_Copy($context);
1127 $xi +
= sizeof($edit->orig
);
1129 $yi +
= sizeof($edit->closing
);
1132 if (is_array($block))
1133 $this->_block($x0, $xi - $x0,
1137 $end = $this->_end_diff();
1138 wfProfileOut( $fname );
1142 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1143 $fname = 'DiffFormatter::_block';
1144 wfProfileIn( $fname );
1145 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1146 foreach ($edits as $edit) {
1147 if ($edit->type
== 'copy')
1148 $this->_context($edit->orig
);
1149 elseif ($edit->type
== 'add')
1150 $this->_added($edit->closing
);
1151 elseif ($edit->type
== 'delete')
1152 $this->_deleted($edit->orig
);
1153 elseif ($edit->type
== 'change')
1154 $this->_changed($edit->orig
, $edit->closing
);
1156 trigger_error('Unknown edit type', E_USER_ERROR
);
1158 $this->_end_block();
1159 wfProfileOut( $fname );
1162 function _start_diff() {
1166 function _end_diff() {
1167 $val = ob_get_contents();
1172 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1174 $xbeg .= "," . ($xbeg +
$xlen - 1);
1176 $ybeg .= "," . ($ybeg +
$ylen - 1);
1178 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1181 function _start_block($header) {
1185 function _end_block() {
1188 function _lines($lines, $prefix = ' ') {
1189 foreach ($lines as $line)
1190 echo "$prefix $line\n";
1193 function _context($lines) {
1194 $this->_lines($lines);
1197 function _added($lines) {
1198 $this->_lines($lines, '>');
1200 function _deleted($lines) {
1201 $this->_lines($lines, '<');
1204 function _changed($orig, $closing) {
1205 $this->_deleted($orig);
1207 $this->_added($closing);
1213 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1217 define('NBSP', ' '); // iso-8859-x non-breaking space.
1222 * @package MediaWiki
1223 * @subpackage DifferenceEngine
1225 class _HWLDF_WordAccumulator
{
1226 function _HWLDF_WordAccumulator () {
1227 $this->_lines
= array();
1233 function _flushGroup ($new_tag) {
1234 if ($this->_group
!== '') {
1235 if ($this->_tag
== 'mark')
1236 $this->_line
.= '<span class="diffchange">' .
1237 htmlspecialchars ( $this->_group
) . '</span>';
1239 $this->_line
.= htmlspecialchars ( $this->_group
);
1242 $this->_tag
= $new_tag;
1245 function _flushLine ($new_tag) {
1246 $this->_flushGroup($new_tag);
1247 if ($this->_line
!= '')
1248 array_push ( $this->_lines
, $this->_line
);
1250 # make empty lines visible by inserting an NBSP
1251 array_push ( $this->_lines
, NBSP
);
1255 function addWords ($words, $tag = '') {
1256 if ($tag != $this->_tag
)
1257 $this->_flushGroup($tag);
1259 foreach ($words as $word) {
1260 // new-line should only come as first char of word.
1263 if ($word[0] == "\n") {
1264 $this->_flushLine($tag);
1265 $word = substr($word, 1);
1267 assert(!strstr($word, "\n"));
1268 $this->_group
.= $word;
1272 function getLines() {
1273 $this->_flushLine('~done');
1274 return $this->_lines
;
1281 * @package MediaWiki
1282 * @subpackage DifferenceEngine
1284 class WordLevelDiff
extends MappedDiff
1286 function WordLevelDiff ($orig_lines, $closing_lines) {
1287 $fname = 'WordLevelDiff::WordLevelDiff';
1288 wfProfileIn( $fname );
1290 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1291 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1294 $this->MappedDiff($orig_words, $closing_words,
1295 $orig_stripped, $closing_stripped);
1296 wfProfileOut( $fname );
1299 function _split($lines) {
1300 $fname = 'WordLevelDiff::_split';
1301 wfProfileIn( $fname );
1302 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1303 implode("\n", $lines),
1305 wfProfileOut( $fname );
1306 return array(array(''), array(''));
1308 wfProfileOut( $fname );
1309 return array($m[0], $m[1]);
1313 $fname = 'WordLevelDiff::orig';
1314 wfProfileIn( $fname );
1315 $orig = new _HWLDF_WordAccumulator
;
1317 foreach ($this->edits
as $edit) {
1318 if ($edit->type
== 'copy')
1319 $orig->addWords($edit->orig
);
1320 elseif ($edit->orig
)
1321 $orig->addWords($edit->orig
, 'mark');
1323 $lines = $orig->getLines();
1324 wfProfileOut( $fname );
1328 function closing () {
1329 $fname = 'WordLevelDiff::closing';
1330 wfProfileIn( $fname );
1331 $closing = new _HWLDF_WordAccumulator
;
1333 foreach ($this->edits
as $edit) {
1334 if ($edit->type
== 'copy')
1335 $closing->addWords($edit->closing
);
1336 elseif ($edit->closing
)
1337 $closing->addWords($edit->closing
, 'mark');
1339 $lines = $closing->getLines();
1340 wfProfileOut( $fname );
1346 * Wikipedia Table style diff formatter.
1349 * @package MediaWiki
1350 * @subpackage DifferenceEngine
1352 class TableDiffFormatter
extends DiffFormatter
1354 function TableDiffFormatter() {
1355 $this->leading_context_lines
= 2;
1356 $this->trailing_context_lines
= 2;
1359 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1360 $l1 = wfMsg( 'lineno', $xbeg );
1361 $l2 = wfMsg( 'lineno', $ybeg );
1363 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1364 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1368 function _start_block( $header ) {
1373 function _end_block() {
1376 function _lines( $lines, $prefix=' ', $color='white' ) {
1379 # HTML-escape parameter before calling this
1380 function addedLine( $line ) {
1381 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1384 # HTML-escape parameter before calling this
1385 function deletedLine( $line ) {
1386 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1389 # HTML-escape parameter before calling this
1390 function contextLine( $line ) {
1391 return "<td> </td><td class='diff-context'>{$line}</td>";
1394 function emptyLine() {
1395 return '<td colspan="2"> </td>';
1398 function _added( $lines ) {
1399 foreach ($lines as $line) {
1400 echo '<tr>' . $this->emptyLine() .
1401 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1405 function _deleted($lines) {
1406 foreach ($lines as $line) {
1407 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1408 $this->emptyLine() . "</tr>\n";
1412 function _context( $lines ) {
1413 foreach ($lines as $line) {
1415 $this->contextLine( htmlspecialchars ( $line ) ) .
1416 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1420 function _changed( $orig, $closing ) {
1421 $fname = 'TableDiffFormatter::_changed';
1422 wfProfileIn( $fname );
1424 $diff = new WordLevelDiff( $orig, $closing );
1425 $del = $diff->orig();
1426 $add = $diff->closing();
1428 # Notice that WordLevelDiff returns HTML-escaped output.
1429 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1431 while ( $line = array_shift( $del ) ) {
1432 $aline = array_shift( $add );
1433 echo '<tr>' . $this->deletedLine( $line ) .
1434 $this->addedLine( $aline ) . "</tr>\n";
1436 foreach ($add as $line) { # If any leftovers
1437 echo '<tr>' . $this->emptyLine() .
1438 $this->addedLine( $line ) . "</tr>\n";
1440 wfProfileOut( $fname );