5 * @subpackage DifferenceEngine
9 require_once( 'Revision.php' );
11 define( 'MAX_DIFF_LINE', 10000 );
12 define( 'MAX_DIFF_XREF_LENGTH', 10000 );
18 * @subpackage DifferenceEngine
20 class DifferenceEngine
{
25 var $mOldtitle, $mNewtitle, $mPagetitle;
26 var $mOldtext, $mNewtext;
27 var $mOldUser, $mNewUser;
28 var $mOldComment, $mNewComment;
29 var $mOldPage, $mNewPage;
30 var $mRcidMarkPatrolled;
35 * @param integer $old Old ID we want to show and diff with.
36 * @param string $new Either 'prev' or 'next'.
37 * @param integer $rcid ??? (default 0)
39 function DifferenceEngine( $old, $new, $rcid = 0 ) {
42 if ( 'prev' == $new ) {
43 # Show diff between revision $old and the previous one.
44 # Get previous one from DB.
46 $this->mNewid
= intval($old);
48 $this->mOldid
= $wgTitle->getPreviousRevisionID( $this->mNewid
);
50 } elseif ( 'next' == $new ) {
51 # Show diff between revision $old and the previous one.
52 # Get previous one from DB.
54 $this->mOldid
= intval($old);
55 $this->mNewid
= $wgTitle->getNextRevisionID( $this->mOldid
);
56 if ( false === $this->mNewid
) {
57 # if no result, NewId points to the newest old revision. The only newer
58 # revision is cur, which is "0".
63 $this->mOldid
= intval($old);
64 $this->mNewid
= intval($new);
66 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
69 function showDiffPage() {
70 global $wgUser, $wgTitle, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol,
71 $wgUseExternalEditor, $wgUseRCPatrol;
72 $fname = 'DifferenceEngine::showDiffPage';
73 wfProfileIn( $fname );
75 # If external diffs are enabled both globally and for the user,
76 # we'll use the application/x-external-editor interface to call
77 # an external diff tool like kompare, kdiff3, etc.
78 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
79 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
81 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
82 $url1=$wgTitle->getFullURL("action=raw&oldid=".$this->mOldid
);
83 $url2=$wgTitle->getFullURL("action=raw&oldid=".$this->mNewid
);
84 $special=$wgLang->getNsText(NS_SPECIAL
);
89 Script={$wgServer}{$wgScript}
90 Special namespace={$special}
104 # mOldid is false if the difference engine is called with a "vague" query for
105 # a diff between a version V and its previous version V' AND the version V
106 # is the first version of that article. In that case, V' does not exist.
107 if ( $this->mOldid
=== false ) {
108 $this->showFirstRevision();
109 wfProfileOut( $fname );
113 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
115 $mtext = wfMsg( 'missingarticle', $t );
117 $wgOut->setArticleFlag( false );
118 if ( ! $this->loadText() ) {
119 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
120 $wgOut->addHTML( $mtext );
121 wfProfileOut( $fname );
124 $wgOut->suppressQuickbar();
126 $oldTitle = $this->mOldPage
->getPrefixedText();
127 $newTitle = $this->mNewPage
->getPrefixedText();
128 if( $oldTitle == $newTitle ) {
129 $wgOut->setPageTitle( $newTitle );
131 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
133 $wgOut->setSubtitle( wfMsg( 'difference' ) );
134 $wgOut->setRobotpolicy( 'noindex,follow' );
136 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
137 $wgOut->loginToUse();
139 wfProfileOut( $fname );
143 $sk = $wgUser->getSkin();
144 $talk = $wgContLang->getNsText( NS_TALK
);
145 $contribs = wfMsg( 'contribslink' );
147 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
148 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
150 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
151 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
152 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
153 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
154 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
155 'target=' . urlencode($this->mOldUser
) );
156 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
157 'target=' . urlencode($this->mNewUser
) );
158 if ( $this->newRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
159 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
160 'action=rollback&from=' . urlencode($this->mNewUser
) .
161 '&token=' . urlencode( $wgUser->editToken( array( $wgTitle->getPrefixedText(), $this->mNewUser
) ) ) ) .
166 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isLoggedIn() &&
167 ( $wgUser->isAllowed('rollback') ||
!$wgOnlySysopsCanPatrol ) )
169 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
170 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
175 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsgHtml( 'previousdiff' ),
176 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
177 if ( $this->newRev
->isCurrent() ) {
180 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsgHtml( 'nextdiff' ),
181 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
184 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
185 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
186 '<br />' . $prevlink;
187 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
188 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
189 '<br />' . $nextlink . $patrol;
191 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
192 $oldHeader, $newHeader );
193 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
195 if( !$this->newRev
->isCurrent() ) {
196 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
198 $wgOut->addWikiText( $this->mNewtext
);
199 if( !$this->newRev
->isCurrent() ) {
200 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
203 wfProfileOut( $fname );
207 * Show the first revision of an article. Uses normal diff headers in
208 * contrast to normal "old revision" display style.
210 function showFirstRevision() {
211 global $wgOut, $wgTitle, $wgUser, $wgLang;
213 $fname = 'DifferenceEngine::showFirstRevision';
214 wfProfileIn( $fname );
217 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
219 # Get article text from the DB
221 if ( ! $this->loadText() ) {
222 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
224 $mtext = wfMsg( 'missingarticle', $t );
225 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
226 $wgOut->addHTML( $mtext );
227 wfProfileOut( $fname );
231 # Check if user is allowed to look at this page. If not, bail out.
233 if ( !( $this->mOldPage
->userCanRead() ) ) {
234 $wgOut->loginToUse();
236 wfProfileOut( $fname );
240 # Prepare the header box
242 $sk = $wgUser->getSkin();
244 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
245 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
246 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
247 'target=' . urlencode($this->mOldUser
) );
248 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
249 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
250 "($uTLink | $contribs)<br />" . $this->mOldComment
.
251 '<br />' . $nextlink. "</div>\n";
253 $wgOut->addHTML( $header );
255 $wgOut->setSubtitle( wfMsg( 'difference' ) );
256 $wgOut->setRobotpolicy( 'noindex,follow' );
259 # Show current revision
261 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
262 $wgOut->addWikiText( $this->mNewtext
);
264 wfProfileOut( $fname );
267 function showDiff( $otext, $ntext, $otitle, $ntitle ) {
269 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
272 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
273 global $wgUseExternalDiffEngine, $wgContLang;
275 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
277 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
278 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
281 $otext = $wgContLang->segmentForDiff($otext);
282 $ntext = $wgContLang->segmentForDiff($ntext);
284 if ( $wgUseExternalDiffEngine ) {
285 # For historical reasons, external diff engine expects
286 # input text to be HTML-escaped already
287 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
288 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
289 if( !function_exists( 'wikidiff_do_diff' ) ) {
290 dl('php_wikidiff.so');
292 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
294 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
295 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
296 $diffs =& new Diff( $ota, $nta );
297 $formatter =& new TableDiffFormatter();
298 $difftext = $formatter->format( $diffs );
300 $difftext = $wgContLang->unsegmentForDiff($difftext);
301 $out .= $difftext."</table>\n";
306 * Load the text of the articles to compare. If newid is 0, then compare
307 * the old article in oldid to the current article; if oldid is 0, then
308 * compare the current article to the immediately previous one (ignoring the
311 function loadText() {
312 global $wgTitle, $wgOut, $wgLang;
313 $fname = 'DifferenceEngine::loadText';
315 $dbr =& wfGetDB( DB_SLAVE
);
316 if( $this->mNewid
) {
317 $this->newRev
= Revision
::newFromId( $this->mNewid
);
319 $this->newRev
= Revision
::newFromTitle( $wgTitle );
321 if( is_null( $this->newRev
) ) {
325 if( $this->newRev
->isCurrent() ) {
326 $wgOut->setArticleFlag( true );
327 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
328 $this->mNewPage
= $wgTitle;
329 $newLink = $this->mNewPage
->escapeLocalUrl();
330 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
332 $this->mNewPage
= $this->newRev
->getTitle();
333 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
334 $t = $wgLang->timeanddate( $this->newRev
->getTimestamp(), true );
335 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
336 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
339 if( $this->mOldid
) {
340 $this->oldRev
= Revision
::newFromId( $this->mOldid
);
342 $this->oldRev
= $this->newRev
->getPrevious();
343 $this->mOldid
= $this->oldRev
->getId();
345 if( is_null( $this->oldRev
) ) {
349 $this->mOldPage
= $this->oldRev
->getTitle();
351 $t = $wgLang->timeanddate( $this->oldRev
->getTimestamp(), true );
352 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
353 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
355 $this->mNewUser
= $this->newRev
->getUserText();
356 $this->mNewComment
= $this->newRev
->getComment();
357 $this->mNewtext
= $this->newRev
->getText();
359 $this->mOldUser
= $this->oldRev
->getUserText();
360 $this->mOldComment
= $this->oldRev
->getComment();
361 $this->mOldtext
= $this->oldRev
->getText();
367 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
369 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
370 // You may copy this code freely under the conditions of the GPL.
373 define('USE_ASSERTS', function_exists('assert'));
379 * @subpackage DifferenceEngine
387 trigger_error('pure virtual', E_USER_ERROR
);
391 return $this->orig ?
sizeof($this->orig
) : 0;
394 function nclosing() {
395 return $this->closing ?
sizeof($this->closing
) : 0;
403 * @subpackage DifferenceEngine
405 class _DiffOp_Copy
extends _DiffOp
{
408 function _DiffOp_Copy ($orig, $closing = false) {
409 if (!is_array($closing))
412 $this->closing
= $closing;
416 return new _DiffOp_Copy($this->closing
, $this->orig
);
424 * @subpackage DifferenceEngine
426 class _DiffOp_Delete
extends _DiffOp
{
427 var $type = 'delete';
429 function _DiffOp_Delete ($lines) {
430 $this->orig
= $lines;
431 $this->closing
= false;
435 return new _DiffOp_Add($this->orig
);
443 * @subpackage DifferenceEngine
445 class _DiffOp_Add
extends _DiffOp
{
448 function _DiffOp_Add ($lines) {
449 $this->closing
= $lines;
454 return new _DiffOp_Delete($this->closing
);
462 * @subpackage DifferenceEngine
464 class _DiffOp_Change
extends _DiffOp
{
465 var $type = 'change';
467 function _DiffOp_Change ($orig, $closing) {
469 $this->closing
= $closing;
473 return new _DiffOp_Change($this->closing
, $this->orig
);
479 * Class used internally by Diff to actually compute the diffs.
481 * The algorithm used here is mostly lifted from the perl module
482 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
483 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
485 * More ideas are taken from:
486 * http://www.ics.uci.edu/~eppstein/161/960229.html
488 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
489 * diffutils-2.7, which can be found at:
490 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
492 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
495 * Line length limits for robustness added by Tim Starling, 2005-08-31
497 * @author Geoffrey T. Dairiki, Tim Starling
500 * @subpackage DifferenceEngine
504 function diff ($from_lines, $to_lines) {
505 $fname = '_DiffEngine::diff';
506 wfProfileIn( $fname );
508 $n_from = sizeof($from_lines);
509 $n_to = sizeof($to_lines);
511 $this->xchanged
= $this->ychanged
= array();
512 $this->xv
= $this->yv
= array();
513 $this->xind
= $this->yind
= array();
515 unset($this->in_seq
);
518 // Skip leading common lines.
519 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
520 if ($from_lines[$skip] != $to_lines[$skip])
522 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
524 // Skip trailing common lines.
525 $xi = $n_from; $yi = $n_to;
526 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
527 if ($from_lines[$xi] != $to_lines[$yi])
529 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
532 // Ignore lines which do not exist in both files.
533 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
534 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
537 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
538 $line = $to_lines[$yi];
539 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
541 $yhash[$this->_line_hash($line)] = 1;
545 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
546 $line = $from_lines[$xi];
547 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
554 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
556 // Merge edits when possible
557 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
558 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
560 // Compute the edit operations.
563 while ($xi < $n_from ||
$yi < $n_to) {
564 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
565 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
567 // Skip matching "snake".
569 while ( $xi < $n_from && $yi < $n_to
570 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
571 $copy[] = $from_lines[$xi++
];
575 $edits[] = new _DiffOp_Copy($copy);
577 // Find deletes & adds.
579 while ($xi < $n_from && $this->xchanged
[$xi])
580 $delete[] = $from_lines[$xi++
];
583 while ($yi < $n_to && $this->ychanged
[$yi])
584 $add[] = $to_lines[$yi++
];
587 $edits[] = new _DiffOp_Change($delete, $add);
589 $edits[] = new _DiffOp_Delete($delete);
591 $edits[] = new _DiffOp_Add($add);
593 wfProfileOut( $fname );
598 * Returns the whole line if it's small enough, or the MD5 hash otherwise
600 function _line_hash( $line ) {
601 if ( strlen( $line ) > MAX_DIFF_XREF_LENGTH
) {
609 /* Divide the Largest Common Subsequence (LCS) of the sequences
610 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
613 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
614 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
615 * sub sequences. The first sub-sequence is contained in [X0, X1),
616 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
617 * that (X0, Y0) == (XOFF, YOFF) and
618 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
620 * This function assumes that the first lines of the specified portions
621 * of the two files do not match, and likewise that the last lines do not
622 * match. The caller must trim matching lines from the beginning and end
623 * of the portions it is going to specify.
625 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
626 $fname = '_DiffEngine::_diag';
627 wfProfileIn( $fname );
630 if ($xlim - $xoff > $ylim - $yoff) {
631 // Things seems faster (I'm not sure I understand why)
632 // when the shortest sequence in X.
634 list ($xoff, $xlim, $yoff, $ylim)
635 = array( $yoff, $ylim, $xoff, $xlim);
639 for ($i = $ylim - 1; $i >= $yoff; $i--)
640 $ymatches[$this->xv
[$i]][] = $i;
642 for ($i = $ylim - 1; $i >= $yoff; $i--)
643 $ymatches[$this->yv
[$i]][] = $i;
646 $this->seq
[0]= $yoff - 1;
647 $this->in_seq
= array();
650 $numer = $xlim - $xoff +
$nchunks - 1;
652 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
653 wfProfileIn( "$fname-chunk" );
655 for ($i = 0; $i <= $this->lcs
; $i++
)
656 $ymids[$i][$chunk-1] = $this->seq
[$i];
658 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
659 for ( ; $x < $x1; $x++
) {
660 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
661 if (empty($ymatches[$line]))
663 $matches = $ymatches[$line];
665 while (list ($junk, $y) = each($matches))
666 if (empty($this->in_seq
[$y])) {
667 $k = $this->_lcs_pos($y);
668 USE_ASSERTS
&& assert($k > 0);
669 $ymids[$k] = $ymids[$k-1];
672 while (list ($junk, $y) = each($matches)) {
673 if ($y > $this->seq
[$k-1]) {
674 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
675 // Optimization: this is a common case:
676 // next match is just replacing previous match.
677 $this->in_seq
[$this->seq
[$k]] = false;
679 $this->in_seq
[$y] = 1;
680 } else if (empty($this->in_seq
[$y])) {
681 $k = $this->_lcs_pos($y);
682 USE_ASSERTS
&& assert($k > 0);
683 $ymids[$k] = $ymids[$k-1];
687 wfProfileOut( "$fname-chunk" );
690 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
691 $ymid = $ymids[$this->lcs
];
692 for ($n = 0; $n < $nchunks - 1; $n++
) {
693 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
695 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
697 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
699 wfProfileOut( $fname );
700 return array($this->lcs
, $seps);
703 function _lcs_pos ($ypos) {
704 $fname = '_DiffEngine::_lcs_pos';
705 wfProfileIn( $fname );
708 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
709 $this->seq
[++
$this->lcs
] = $ypos;
710 $this->in_seq
[$ypos] = 1;
711 wfProfileOut( $fname );
716 while ($beg < $end) {
717 $mid = (int)(($beg +
$end) / 2);
718 if ( $ypos > $this->seq
[$mid] )
724 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
726 $this->in_seq
[$this->seq
[$end]] = false;
727 $this->seq
[$end] = $ypos;
728 $this->in_seq
[$ypos] = 1;
729 wfProfileOut( $fname );
733 /* Find LCS of two sequences.
735 * The results are recorded in the vectors $this->{x,y}changed[], by
736 * storing a 1 in the element for each line that is an insertion
737 * or deletion (ie. is not in the LCS).
739 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
741 * Note that XLIM, YLIM are exclusive bounds.
742 * All line numbers are origin-0 and discarded lines are not counted.
744 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
745 $fname = '_DiffEngine::_compareseq';
746 wfProfileIn( $fname );
748 // Slide down the bottom initial diagonal.
749 while ($xoff < $xlim && $yoff < $ylim
750 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
755 // Slide up the top initial diagonal.
756 while ($xlim > $xoff && $ylim > $yoff
757 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
762 if ($xoff == $xlim ||
$yoff == $ylim)
765 // This is ad hoc but seems to work well.
766 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
767 //$nchunks = max(2,min(8,(int)$nchunks));
768 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
770 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
774 // X and Y sequences have no common subsequence:
776 while ($yoff < $ylim)
777 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
778 while ($xoff < $xlim)
779 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
781 // Use the partitions to split this problem into subproblems.
784 while ($pt2 = next($seps)) {
785 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
789 wfProfileOut( $fname );
792 /* Adjust inserts/deletes of identical lines to join changes
793 * as much as possible.
795 * We do something when a run of changed lines include a
796 * line at one end and has an excluded, identical line at the other.
797 * We are free to choose which identical line is included.
798 * `compareseq' usually chooses the one at the beginning,
799 * but usually it is cleaner to consider the following identical line
800 * to be the "change".
802 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
804 function _shift_boundaries ($lines, &$changed, $other_changed) {
805 $fname = '_DiffEngine::_shift_boundaries';
806 wfProfileIn( $fname );
810 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
811 $len = sizeof($lines);
812 $other_len = sizeof($other_changed);
816 * Scan forwards to find beginning of another run of changes.
817 * Also keep track of the corresponding point in the other file.
819 * Throughout this code, $i and $j are adjusted together so that
820 * the first $i elements of $changed and the first $j elements
821 * of $other_changed both contain the same number of zeros
823 * Furthermore, $j is always kept so that $j == $other_len or
824 * $other_changed[$j] == false.
826 while ($j < $other_len && $other_changed[$j])
829 while ($i < $len && ! $changed[$i]) {
830 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
832 while ($j < $other_len && $other_changed[$j])
841 // Find the end of this run of changes.
842 while (++
$i < $len && $changed[$i])
847 * Record the length of this run of changes, so that
848 * we can later determine whether the run has grown.
850 $runlength = $i - $start;
853 * Move the changed region back, so long as the
854 * previous unchanged line matches the last changed one.
855 * This merges with previous changed regions.
857 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
858 $changed[--$start] = 1;
859 $changed[--$i] = false;
860 while ($start > 0 && $changed[$start - 1])
862 USE_ASSERTS
&& assert('$j > 0');
863 while ($other_changed[--$j])
865 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
869 * Set CORRESPONDING to the end of the changed run, at the last
870 * point where it corresponds to a changed run in the other file.
871 * CORRESPONDING == LEN means no such point has been found.
873 $corresponding = $j < $other_len ?
$i : $len;
876 * Move the changed region forward, so long as the
877 * first changed line matches the following unchanged one.
878 * This merges with following changed regions.
879 * Do this second, so that if there are no merges,
880 * the changed region is moved forward as far as possible.
882 while ($i < $len && $lines[$start] == $lines[$i]) {
883 $changed[$start++
] = false;
885 while ($i < $len && $changed[$i])
888 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
890 if ($j < $other_len && $other_changed[$j]) {
892 while ($j < $other_len && $other_changed[$j])
896 } while ($runlength != $i - $start);
899 * If possible, move the fully-merged run of changes
900 * back to a corresponding run in the other file.
902 while ($corresponding < $i) {
903 $changed[--$start] = 1;
905 USE_ASSERTS
&& assert('$j > 0');
906 while ($other_changed[--$j])
908 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
911 wfProfileOut( $fname );
916 * Class representing a 'diff' between two sequences of strings.
920 * @subpackage DifferenceEngine
928 * Computes diff between sequences of strings.
930 * @param $from_lines array An array of strings.
931 * (Typically these are lines from a file.)
932 * @param $to_lines array An array of strings.
934 function Diff($from_lines, $to_lines) {
935 $eng = new _DiffEngine
;
936 $this->edits
= $eng->diff($from_lines, $to_lines);
937 //$this->_check($from_lines, $to_lines);
941 * Compute reversed Diff.
945 * $diff = new Diff($lines1, $lines2);
946 * $rev = $diff->reverse();
947 * @return object A Diff object representing the inverse of the
950 function reverse () {
952 $rev->edits
= array();
953 foreach ($this->edits
as $edit) {
954 $rev->edits
[] = $edit->reverse();
960 * Check for empty diff.
962 * @return bool True iff two sequences were identical.
964 function isEmpty () {
965 foreach ($this->edits
as $edit) {
966 if ($edit->type
!= 'copy')
973 * Compute the length of the Longest Common Subsequence (LCS).
975 * This is mostly for diagnostic purposed.
977 * @return int The length of the LCS.
981 foreach ($this->edits
as $edit) {
982 if ($edit->type
== 'copy')
983 $lcs +
= sizeof($edit->orig
);
989 * Get the original set of lines.
991 * This reconstructs the $from_lines parameter passed to the
994 * @return array The original sequence of strings.
999 foreach ($this->edits
as $edit) {
1001 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1007 * Get the closing set of lines.
1009 * This reconstructs the $to_lines parameter passed to the
1012 * @return array The sequence of strings.
1014 function closing() {
1017 foreach ($this->edits
as $edit) {
1019 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1025 * Check a Diff for validity.
1027 * This is here only for debugging purposes.
1029 function _check ($from_lines, $to_lines) {
1030 $fname = 'Diff::_check';
1031 wfProfileIn( $fname );
1032 if (serialize($from_lines) != serialize($this->orig()))
1033 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1034 if (serialize($to_lines) != serialize($this->closing()))
1035 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1037 $rev = $this->reverse();
1038 if (serialize($to_lines) != serialize($rev->orig()))
1039 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1040 if (serialize($from_lines) != serialize($rev->closing()))
1041 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1045 foreach ($this->edits
as $edit) {
1046 if ( $prevtype == $edit->type
)
1047 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1048 $prevtype = $edit->type
;
1051 $lcs = $this->lcs();
1052 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1053 wfProfileOut( $fname );
1061 * @package MediaWiki
1062 * @subpackage DifferenceEngine
1064 class MappedDiff
extends Diff
1069 * Computes diff between sequences of strings.
1071 * This can be used to compute things like
1072 * case-insensitve diffs, or diffs which ignore
1073 * changes in white-space.
1075 * @param $from_lines array An array of strings.
1076 * (Typically these are lines from a file.)
1078 * @param $to_lines array An array of strings.
1080 * @param $mapped_from_lines array This array should
1081 * have the same size number of elements as $from_lines.
1082 * The elements in $mapped_from_lines and
1083 * $mapped_to_lines are what is actually compared
1084 * when computing the diff.
1086 * @param $mapped_to_lines array This array should
1087 * have the same number of elements as $to_lines.
1089 function MappedDiff($from_lines, $to_lines,
1090 $mapped_from_lines, $mapped_to_lines) {
1091 $fname = 'MappedDiff::MappedDiff';
1092 wfProfileIn( $fname );
1094 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1095 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1097 $this->Diff($mapped_from_lines, $mapped_to_lines);
1100 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1101 $orig = &$this->edits
[$i]->orig
;
1102 if (is_array($orig)) {
1103 $orig = array_slice($from_lines, $xi, sizeof($orig));
1104 $xi +
= sizeof($orig);
1107 $closing = &$this->edits
[$i]->closing
;
1108 if (is_array($closing)) {
1109 $closing = array_slice($to_lines, $yi, sizeof($closing));
1110 $yi +
= sizeof($closing);
1113 wfProfileOut( $fname );
1118 * A class to format Diffs
1120 * This class formats the diff in classic diff format.
1121 * It is intended that this class be customized via inheritance,
1122 * to obtain fancier outputs.
1125 * @package MediaWiki
1126 * @subpackage DifferenceEngine
1131 * Number of leading context "lines" to preserve.
1133 * This should be left at zero for this class, but subclasses
1134 * may want to set this to other values.
1136 var $leading_context_lines = 0;
1139 * Number of trailing context "lines" to preserve.
1141 * This should be left at zero for this class, but subclasses
1142 * may want to set this to other values.
1144 var $trailing_context_lines = 0;
1149 * @param $diff object A Diff object.
1150 * @return string The formatted output.
1152 function format($diff) {
1153 $fname = 'DiffFormatter::format';
1154 wfProfileIn( $fname );
1160 $nlead = $this->leading_context_lines
;
1161 $ntrail = $this->trailing_context_lines
;
1163 $this->_start_diff();
1165 foreach ($diff->edits
as $edit) {
1166 if ($edit->type
== 'copy') {
1167 if (is_array($block)) {
1168 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1173 $context = array_slice($edit->orig
, 0, $ntrail);
1174 $block[] = new _DiffOp_Copy($context);
1176 $this->_block($x0, $ntrail +
$xi - $x0,
1177 $y0, $ntrail +
$yi - $y0,
1182 $context = $edit->orig
;
1185 if (! is_array($block)) {
1186 $context = array_slice($context, sizeof($context) - $nlead);
1187 $x0 = $xi - sizeof($context);
1188 $y0 = $yi - sizeof($context);
1191 $block[] = new _DiffOp_Copy($context);
1197 $xi +
= sizeof($edit->orig
);
1199 $yi +
= sizeof($edit->closing
);
1202 if (is_array($block))
1203 $this->_block($x0, $xi - $x0,
1207 $end = $this->_end_diff();
1208 wfProfileOut( $fname );
1212 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1213 $fname = 'DiffFormatter::_block';
1214 wfProfileIn( $fname );
1215 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1216 foreach ($edits as $edit) {
1217 if ($edit->type
== 'copy')
1218 $this->_context($edit->orig
);
1219 elseif ($edit->type
== 'add')
1220 $this->_added($edit->closing
);
1221 elseif ($edit->type
== 'delete')
1222 $this->_deleted($edit->orig
);
1223 elseif ($edit->type
== 'change')
1224 $this->_changed($edit->orig
, $edit->closing
);
1226 trigger_error('Unknown edit type', E_USER_ERROR
);
1228 $this->_end_block();
1229 wfProfileOut( $fname );
1232 function _start_diff() {
1236 function _end_diff() {
1237 $val = ob_get_contents();
1242 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1244 $xbeg .= "," . ($xbeg +
$xlen - 1);
1246 $ybeg .= "," . ($ybeg +
$ylen - 1);
1248 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1251 function _start_block($header) {
1255 function _end_block() {
1258 function _lines($lines, $prefix = ' ') {
1259 foreach ($lines as $line)
1260 echo "$prefix $line\n";
1263 function _context($lines) {
1264 $this->_lines($lines);
1267 function _added($lines) {
1268 $this->_lines($lines, '>');
1270 function _deleted($lines) {
1271 $this->_lines($lines, '<');
1274 function _changed($orig, $closing) {
1275 $this->_deleted($orig);
1277 $this->_added($closing);
1283 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1287 define('NBSP', ' '); // iso-8859-x non-breaking space.
1292 * @package MediaWiki
1293 * @subpackage DifferenceEngine
1295 class _HWLDF_WordAccumulator
{
1296 function _HWLDF_WordAccumulator () {
1297 $this->_lines
= array();
1303 function _flushGroup ($new_tag) {
1304 if ($this->_group
!== '') {
1305 if ($this->_tag
== 'mark')
1306 $this->_line
.= '<span class="diffchange">' .
1307 htmlspecialchars ( $this->_group
) . '</span>';
1309 $this->_line
.= htmlspecialchars ( $this->_group
);
1312 $this->_tag
= $new_tag;
1315 function _flushLine ($new_tag) {
1316 $this->_flushGroup($new_tag);
1317 if ($this->_line
!= '')
1318 array_push ( $this->_lines
, $this->_line
);
1320 # make empty lines visible by inserting an NBSP
1321 array_push ( $this->_lines
, NBSP
);
1325 function addWords ($words, $tag = '') {
1326 if ($tag != $this->_tag
)
1327 $this->_flushGroup($tag);
1329 foreach ($words as $word) {
1330 // new-line should only come as first char of word.
1333 if ($word[0] == "\n") {
1334 $this->_flushLine($tag);
1335 $word = substr($word, 1);
1337 assert(!strstr($word, "\n"));
1338 $this->_group
.= $word;
1342 function getLines() {
1343 $this->_flushLine('~done');
1344 return $this->_lines
;
1351 * @package MediaWiki
1352 * @subpackage DifferenceEngine
1354 class WordLevelDiff
extends MappedDiff
1356 function WordLevelDiff ($orig_lines, $closing_lines) {
1357 $fname = 'WordLevelDiff::WordLevelDiff';
1358 wfProfileIn( $fname );
1360 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1361 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1363 $this->MappedDiff($orig_words, $closing_words,
1364 $orig_stripped, $closing_stripped);
1365 wfProfileOut( $fname );
1368 function _split($lines) {
1369 $fname = 'WordLevelDiff::_split';
1370 wfProfileIn( $fname );
1373 $stripped = array();
1375 foreach ( $lines as $line ) {
1376 # If the line is too long, just pretend the entire line is one big word
1377 # This prevents resource exhaustion problems
1384 if ( strlen( $line ) > MAX_DIFF_LINE
) {
1386 $stripped[] = $line;
1388 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1391 $words = array_merge( $words, $m[0] );
1392 $stripped = array_merge( $stripped, $m[1] );
1396 wfProfileOut( $fname );
1397 return array($words, $stripped);
1401 $fname = 'WordLevelDiff::orig';
1402 wfProfileIn( $fname );
1403 $orig = new _HWLDF_WordAccumulator
;
1405 foreach ($this->edits
as $edit) {
1406 if ($edit->type
== 'copy')
1407 $orig->addWords($edit->orig
);
1408 elseif ($edit->orig
)
1409 $orig->addWords($edit->orig
, 'mark');
1411 $lines = $orig->getLines();
1412 wfProfileOut( $fname );
1416 function closing () {
1417 $fname = 'WordLevelDiff::closing';
1418 wfProfileIn( $fname );
1419 $closing = new _HWLDF_WordAccumulator
;
1421 foreach ($this->edits
as $edit) {
1422 if ($edit->type
== 'copy')
1423 $closing->addWords($edit->closing
);
1424 elseif ($edit->closing
)
1425 $closing->addWords($edit->closing
, 'mark');
1427 $lines = $closing->getLines();
1428 wfProfileOut( $fname );
1434 * Wikipedia Table style diff formatter.
1437 * @package MediaWiki
1438 * @subpackage DifferenceEngine
1440 class TableDiffFormatter
extends DiffFormatter
1442 function TableDiffFormatter() {
1443 $this->leading_context_lines
= 2;
1444 $this->trailing_context_lines
= 2;
1447 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1448 $l1 = wfMsg( 'lineno', $xbeg );
1449 $l2 = wfMsg( 'lineno', $ybeg );
1451 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1452 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1456 function _start_block( $header ) {
1461 function _end_block() {
1464 function _lines( $lines, $prefix=' ', $color='white' ) {
1467 # HTML-escape parameter before calling this
1468 function addedLine( $line ) {
1469 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1472 # HTML-escape parameter before calling this
1473 function deletedLine( $line ) {
1474 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1477 # HTML-escape parameter before calling this
1478 function contextLine( $line ) {
1479 return "<td> </td><td class='diff-context'>{$line}</td>";
1482 function emptyLine() {
1483 return '<td colspan="2"> </td>';
1486 function _added( $lines ) {
1487 foreach ($lines as $line) {
1488 echo '<tr>' . $this->emptyLine() .
1489 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1493 function _deleted($lines) {
1494 foreach ($lines as $line) {
1495 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1496 $this->emptyLine() . "</tr>\n";
1500 function _context( $lines ) {
1501 foreach ($lines as $line) {
1503 $this->contextLine( htmlspecialchars ( $line ) ) .
1504 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1508 function _changed( $orig, $closing ) {
1509 $fname = 'TableDiffFormatter::_changed';
1510 wfProfileIn( $fname );
1512 $diff = new WordLevelDiff( $orig, $closing );
1513 $del = $diff->orig();
1514 $add = $diff->closing();
1516 # Notice that WordLevelDiff returns HTML-escaped output.
1517 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1519 while ( $line = array_shift( $del ) ) {
1520 $aline = array_shift( $add );
1521 echo '<tr>' . $this->deletedLine( $line ) .
1522 $this->addedLine( $aline ) . "</tr>\n";
1524 foreach ($add as $line) { # If any leftovers
1525 echo '<tr>' . $this->emptyLine() .
1526 $this->addedLine( $line ) . "</tr>\n";
1528 wfProfileOut( $fname );