11 class DifferenceEngine
{
12 /* private */ var $mOldid, $mNewid;
13 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
14 /* private */ var $mOldtext, $mNewtext;
15 /* private */ var $mOldUser, $mNewUser;
16 /* private */ var $mOldComment, $mNewComment;
17 /* private */ var $mOldPage, $mNewPage;
18 /* private */ var $mRcidMarkPatrolled;
20 function DifferenceEngine( $old, $new, $rcid = 0 )
23 if ( 'prev' == $new ) {
24 # Show diff between revision $old and the previous one.
25 # Get previous one from DB.
27 $this->mNewid
= intval($old);
29 $this->mOldid
= $wgTitle->getPreviousRevisionID( $this->mNewid
);
31 } elseif ( 'next' == $new ) {
33 # Show diff between revision $old and the previous one.
34 # Get previous one from DB.
36 $this->mOldid
= intval($old);
37 $this->mNewid
= $wgTitle->getNextRevisionID( $this->mOldid
);
38 if ( false === $this->mNewid
) {
39 # if no result, NewId points to the newest old revision. The only newer
40 # revision is cur, which is "0".
46 $this->mOldid
= intval($old);
47 $this->mNewid
= intval($new);
49 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
52 function showDiffPage()
54 global $wgUser, $wgTitle, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
55 $fname = 'DifferenceEngine::showDiffPage';
56 wfProfileIn( $fname );
58 # mOldid is false if the difference engine is called with a "vague" query for
59 # a diff between a version V and its previous version V' AND the version V
60 # is the first version of that article. In that case, V' does not exist.
61 if ( $this->mOldid
=== false ) {
62 $this->showFirstRevision();
63 wfProfileOut( $fname );
67 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
69 $mtext = wfMsg( 'missingarticle', $t );
71 $wgOut->setArticleFlag( false );
72 if ( ! $this->loadText() ) {
73 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
74 $wgOut->addHTML( $mtext );
75 wfProfileOut( $fname );
78 $wgOut->suppressQuickbar();
80 $oldTitle = $this->mOldPage
->getPrefixedText();
81 $newTitle = $this->mNewPage
->getPrefixedText();
82 if( $oldTitle == $newTitle ) {
83 $wgOut->setPageTitle( $newTitle );
85 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
87 $wgOut->setSubtitle( wfMsg( 'difference' ) );
88 $wgOut->setRobotpolicy( 'noindex,follow' );
90 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
93 wfProfileOut( $fname );
97 $sk = $wgUser->getSkin();
98 $talk = $wgContLang->getNsText( NS_TALK
);
99 $contribs = wfMsg( 'contribslink' );
101 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
102 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
104 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
105 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
106 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
107 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
108 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
109 'target=' . urlencode($this->mOldUser
) );
110 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
111 'target=' . urlencode($this->mNewUser
) );
112 if ( !$this->mNewid
&& $wgUser->isSysop() ) {
113 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
114 'action=rollback&from=' . urlencode($this->mNewUser
) ) . ']</strong>';
118 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
119 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
121 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
122 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
127 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
128 if ( $this->mNewid
== 0 ) {
131 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
134 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
135 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
136 '<br />' . $prevlink;
137 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
138 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
139 '<br />' . $nextlink . $patrol;
141 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
142 $oldHeader, $newHeader );
143 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
144 $wgOut->addWikiText( $this->mNewtext
);
146 wfProfileOut( $fname );
149 # Show the first revision of an article. Uses normal diff headers in contrast to normal
150 # "old revision" display style.
152 function showFirstRevision()
154 global $wgOut, $wgTitle, $wgUser, $wgLang;
156 $fname = 'DifferenceEngine::showFirstRevision';
157 wfProfileIn( $fname );
160 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
162 # Get article text from the DB
164 if ( ! $this->loadText() ) {
165 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
167 $mtext = wfMsg( 'missingarticle', $t );
168 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
169 $wgOut->addHTML( $mtext );
170 wfProfileOut( $fname );
174 # Check if user is allowed to look at this page. If not, bail out.
176 if ( !( $this->mOldPage
->userCanRead() ) ) {
177 $wgOut->loginToUse();
179 wfProfileOut( $fname );
183 # Prepare the header box
185 $sk = $wgUser->getSkin();
187 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
188 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
189 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
190 'target=' . urlencode($this->mOldUser
) );
191 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
192 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
193 "($uTLink | $contribs)<br />" . $this->mOldComment
.
194 '<br />' . $nextlink. "</div>\n";
196 $wgOut->addHTML( $header );
198 $wgOut->setSubtitle( wfMsg( 'difference' ) );
199 $wgOut->setRobotpolicy( 'noindex,follow' );
202 # Show current revision
204 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
205 $wgOut->addWikiText( $this->mNewtext
);
207 wfProfileOut( $fname );
210 function showDiff( $otext, $ntext, $otitle, $ntitle )
212 global $wgOut, $wgUseExternalDiffEngine;
215 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
217 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
218 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
222 if ( $wgUseExternalDiffEngine ) {
223 # For historical reasons, external diff engine expects
224 # input text to be HTML-escaped already
225 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
226 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
227 dl('php_wikidiff.so');
228 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
230 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
231 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
232 $diffs = new Diff( $ota, $nta );
233 $formatter = new TableDiffFormatter();
234 $formatter->format( $diffs );
236 $wgOut->addHTML( "</table>\n" );
239 # Load the text of the articles to compare. If newid is 0, then compare
240 # the old article in oldid to the current article; if oldid is 0, then
241 # compare the current article to the immediately previous one (ignoring
242 # the value of newid).
246 global $wgTitle, $wgOut, $wgLang;
247 $fname = 'DifferenceEngine::loadText';
249 $dbr =& wfGetDB( DB_SLAVE
);
250 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
251 $wgOut->setArticleFlag( true );
252 $newLink = $wgTitle->escapeLocalUrl();
253 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
254 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
255 $id = $wgTitle->getArticleID();
257 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
258 array( 'cur_id' => $id ), $fname );
259 if ( $s === false ) {
260 wfDebug( "Unable to load cur_id $id\n" );
264 $this->mNewPage
= &$wgTitle;
265 $this->mNewtext
= $s->cur_text
;
266 $this->mNewUser
= $s->cur_user_text
;
267 $this->mNewComment
= $s->cur_comment
;
269 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
270 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
272 if ( $s === false ) {
273 wfDebug( "Unable to load old_id {$this->mNewid}\n" );
277 $this->mNewtext
= Article
::getRevisionText( $s );
279 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
280 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
281 $newLink = $wgTitle->escapeLocalUrl ('oldid=' . $this->mNewid
);
282 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
283 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
284 $this->mNewUser
= $s->old_user_text
;
285 $this->mNewComment
= $s->old_comment
;
287 if ( 0 == $this->mOldid
) {
288 $s = $dbr->getArray( 'old',
289 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
291 'old_namespace' => $this->mNewPage
->getNamespace(),
292 'old_title' => $this->mNewPage
->getDBkey()
293 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
295 if ( $s === false ) {
296 wfDebug( 'Unable to load ' . $this->mNewPage
->getPrefixedDBkey
. " from old\n" );
300 $s = $dbr->getArray( 'old',
301 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
302 array( 'old_id' => $this->mOldid
),
305 if ( $s === false ) {
306 wfDebug( "Unable to load old_id {$this->mOldid}\n" );
310 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
311 $this->mOldtext
= Article
::getRevisionText( $s );
313 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
314 $oldLink = $this->mOldPage
->escapeLocalUrl ('oldid=' . $this->mOldid
);
315 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
316 $this->mOldUser
= $s->old_user_text
;
317 $this->mOldComment
= $s->old_comment
;
323 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
325 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
326 // You may copy this code freely under the conditions of the GPL.
329 define('USE_ASSERTS', function_exists('assert'));
341 trigger_error('pure virtual', E_USER_ERROR
);
345 return $this->orig ?
sizeof($this->orig
) : 0;
348 function nclosing() {
349 return $this->closing ?
sizeof($this->closing
) : 0;
357 class _DiffOp_Copy
extends _DiffOp
{
360 function _DiffOp_Copy ($orig, $closing = false) {
361 if (!is_array($closing))
364 $this->closing
= $closing;
368 return new _DiffOp_Copy($this->closing
, $this->orig
);
376 class _DiffOp_Delete
extends _DiffOp
{
377 var $type = 'delete';
379 function _DiffOp_Delete ($lines) {
380 $this->orig
= $lines;
381 $this->closing
= false;
385 return new _DiffOp_Add($this->orig
);
393 class _DiffOp_Add
extends _DiffOp
{
396 function _DiffOp_Add ($lines) {
397 $this->closing
= $lines;
402 return new _DiffOp_Delete($this->closing
);
410 class _DiffOp_Change
extends _DiffOp
{
411 var $type = 'change';
413 function _DiffOp_Change ($orig, $closing) {
415 $this->closing
= $closing;
419 return new _DiffOp_Change($this->closing
, $this->orig
);
425 * Class used internally by Diff to actually compute the diffs.
427 * The algorithm used here is mostly lifted from the perl module
428 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
429 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
431 * More ideas are taken from:
432 * http://www.ics.uci.edu/~eppstein/161/960229.html
434 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
435 * diffutils-2.7, which can be found at:
436 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
438 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
441 * @author Geoffrey T. Dairiki
447 function diff ($from_lines, $to_lines) {
448 $n_from = sizeof($from_lines);
449 $n_to = sizeof($to_lines);
451 $this->xchanged
= $this->ychanged
= array();
452 $this->xv
= $this->yv
= array();
453 $this->xind
= $this->yind
= array();
455 unset($this->in_seq
);
458 // Skip leading common lines.
459 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
460 if ($from_lines[$skip] != $to_lines[$skip])
462 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
464 // Skip trailing common lines.
465 $xi = $n_from; $yi = $n_to;
466 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
467 if ($from_lines[$xi] != $to_lines[$yi])
469 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
472 // Ignore lines which do not exist in both files.
473 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
474 $xhash[$from_lines[$xi]] = 1;
475 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
476 $line = $to_lines[$yi];
477 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
483 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
484 $line = $from_lines[$xi];
485 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
492 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
494 // Merge edits when possible
495 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
496 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
498 // Compute the edit operations.
501 while ($xi < $n_from ||
$yi < $n_to) {
502 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
503 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
505 // Skip matching "snake".
507 while ( $xi < $n_from && $yi < $n_to
508 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
509 $copy[] = $from_lines[$xi++
];
513 $edits[] = new _DiffOp_Copy($copy);
515 // Find deletes & adds.
517 while ($xi < $n_from && $this->xchanged
[$xi])
518 $delete[] = $from_lines[$xi++
];
521 while ($yi < $n_to && $this->ychanged
[$yi])
522 $add[] = $to_lines[$yi++
];
525 $edits[] = new _DiffOp_Change($delete, $add);
527 $edits[] = new _DiffOp_Delete($delete);
529 $edits[] = new _DiffOp_Add($add);
535 /* Divide the Largest Common Subsequence (LCS) of the sequences
536 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
539 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
540 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
541 * sub sequences. The first sub-sequence is contained in [X0, X1),
542 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
543 * that (X0, Y0) == (XOFF, YOFF) and
544 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
546 * This function assumes that the first lines of the specified portions
547 * of the two files do not match, and likewise that the last lines do not
548 * match. The caller must trim matching lines from the beginning and end
549 * of the portions it is going to specify.
551 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
554 if ($xlim - $xoff > $ylim - $yoff) {
555 // Things seems faster (I'm not sure I understand why)
556 // when the shortest sequence in X.
558 list ($xoff, $xlim, $yoff, $ylim)
559 = array( $yoff, $ylim, $xoff, $xlim);
563 for ($i = $ylim - 1; $i >= $yoff; $i--)
564 $ymatches[$this->xv
[$i]][] = $i;
566 for ($i = $ylim - 1; $i >= $yoff; $i--)
567 $ymatches[$this->yv
[$i]][] = $i;
570 $this->seq
[0]= $yoff - 1;
571 $this->in_seq
= array();
574 $numer = $xlim - $xoff +
$nchunks - 1;
576 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
578 for ($i = 0; $i <= $this->lcs
; $i++
)
579 $ymids[$i][$chunk-1] = $this->seq
[$i];
581 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
582 for ( ; $x < $x1; $x++
) {
583 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
584 if (empty($ymatches[$line]))
586 $matches = $ymatches[$line];
588 while (list ($junk, $y) = each($matches))
589 if (empty($this->in_seq
[$y])) {
590 $k = $this->_lcs_pos($y);
591 USE_ASSERTS
&& assert($k > 0);
592 $ymids[$k] = $ymids[$k-1];
595 while (list ($junk, $y) = each($matches)) {
596 if ($y > $this->seq
[$k-1]) {
597 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
598 // Optimization: this is a common case:
599 // next match is just replacing previous match.
600 $this->in_seq
[$this->seq
[$k]] = false;
602 $this->in_seq
[$y] = 1;
604 else if (empty($this->in_seq
[$y])) {
605 $k = $this->_lcs_pos($y);
606 USE_ASSERTS
&& assert($k > 0);
607 $ymids[$k] = $ymids[$k-1];
613 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
614 $ymid = $ymids[$this->lcs
];
615 for ($n = 0; $n < $nchunks - 1; $n++
) {
616 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
618 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
620 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
622 return array($this->lcs
, $seps);
625 function _lcs_pos ($ypos) {
627 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
628 $this->seq
[++
$this->lcs
] = $ypos;
629 $this->in_seq
[$ypos] = 1;
634 while ($beg < $end) {
635 $mid = (int)(($beg +
$end) / 2);
636 if ( $ypos > $this->seq
[$mid] )
642 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
644 $this->in_seq
[$this->seq
[$end]] = false;
645 $this->seq
[$end] = $ypos;
646 $this->in_seq
[$ypos] = 1;
650 /* Find LCS of two sequences.
652 * The results are recorded in the vectors $this->{x,y}changed[], by
653 * storing a 1 in the element for each line that is an insertion
654 * or deletion (ie. is not in the LCS).
656 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
658 * Note that XLIM, YLIM are exclusive bounds.
659 * All line numbers are origin-0 and discarded lines are not counted.
661 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
662 // Slide down the bottom initial diagonal.
663 while ($xoff < $xlim && $yoff < $ylim
664 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
669 // Slide up the top initial diagonal.
670 while ($xlim > $xoff && $ylim > $yoff
671 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
676 if ($xoff == $xlim ||
$yoff == $ylim)
679 // This is ad hoc but seems to work well.
680 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
681 //$nchunks = max(2,min(8,(int)$nchunks));
682 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
684 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
688 // X and Y sequences have no common subsequence:
690 while ($yoff < $ylim)
691 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
692 while ($xoff < $xlim)
693 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
696 // Use the partitions to split this problem into subproblems.
699 while ($pt2 = next($seps)) {
700 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
706 /* Adjust inserts/deletes of identical lines to join changes
707 * as much as possible.
709 * We do something when a run of changed lines include a
710 * line at one end and has an excluded, identical line at the other.
711 * We are free to choose which identical line is included.
712 * `compareseq' usually chooses the one at the beginning,
713 * but usually it is cleaner to consider the following identical line
714 * to be the "change".
716 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
718 function _shift_boundaries ($lines, &$changed, $other_changed) {
722 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
723 $len = sizeof($lines);
724 $other_len = sizeof($other_changed);
728 * Scan forwards to find beginning of another run of changes.
729 * Also keep track of the corresponding point in the other file.
731 * Throughout this code, $i and $j are adjusted together so that
732 * the first $i elements of $changed and the first $j elements
733 * of $other_changed both contain the same number of zeros
735 * Furthermore, $j is always kept so that $j == $other_len or
736 * $other_changed[$j] == false.
738 while ($j < $other_len && $other_changed[$j])
741 while ($i < $len && ! $changed[$i]) {
742 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
744 while ($j < $other_len && $other_changed[$j])
753 // Find the end of this run of changes.
754 while (++
$i < $len && $changed[$i])
759 * Record the length of this run of changes, so that
760 * we can later determine whether the run has grown.
762 $runlength = $i - $start;
765 * Move the changed region back, so long as the
766 * previous unchanged line matches the last changed one.
767 * This merges with previous changed regions.
769 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
770 $changed[--$start] = 1;
771 $changed[--$i] = false;
772 while ($start > 0 && $changed[$start - 1])
774 USE_ASSERTS
&& assert('$j > 0');
775 while ($other_changed[--$j])
777 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
781 * Set CORRESPONDING to the end of the changed run, at the last
782 * point where it corresponds to a changed run in the other file.
783 * CORRESPONDING == LEN means no such point has been found.
785 $corresponding = $j < $other_len ?
$i : $len;
788 * Move the changed region forward, so long as the
789 * first changed line matches the following unchanged one.
790 * This merges with following changed regions.
791 * Do this second, so that if there are no merges,
792 * the changed region is moved forward as far as possible.
794 while ($i < $len && $lines[$start] == $lines[$i]) {
795 $changed[$start++
] = false;
797 while ($i < $len && $changed[$i])
800 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
802 if ($j < $other_len && $other_changed[$j]) {
804 while ($j < $other_len && $other_changed[$j])
808 } while ($runlength != $i - $start);
811 * If possible, move the fully-merged run of changes
812 * back to a corresponding run in the other file.
814 while ($corresponding < $i) {
815 $changed[--$start] = 1;
817 USE_ASSERTS
&& assert('$j > 0');
818 while ($other_changed[--$j])
820 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
827 * Class representing a 'diff' between two sequences of strings.
837 * Computes diff between sequences of strings.
839 * @param $from_lines array An array of strings.
840 * (Typically these are lines from a file.)
841 * @param $to_lines array An array of strings.
843 function Diff($from_lines, $to_lines) {
844 $eng = new _DiffEngine
;
845 $this->edits
= $eng->diff($from_lines, $to_lines);
846 //$this->_check($from_lines, $to_lines);
850 * Compute reversed Diff.
854 * $diff = new Diff($lines1, $lines2);
855 * $rev = $diff->reverse();
856 * @return object A Diff object representing the inverse of the
859 function reverse () {
861 $rev->edits
= array();
862 foreach ($this->edits
as $edit) {
863 $rev->edits
[] = $edit->reverse();
869 * Check for empty diff.
871 * @return bool True iff two sequences were identical.
873 function isEmpty () {
874 foreach ($this->edits
as $edit) {
875 if ($edit->type
!= 'copy')
882 * Compute the length of the Longest Common Subsequence (LCS).
884 * This is mostly for diagnostic purposed.
886 * @return int The length of the LCS.
890 foreach ($this->edits
as $edit) {
891 if ($edit->type
== 'copy')
892 $lcs +
= sizeof($edit->orig
);
898 * Get the original set of lines.
900 * This reconstructs the $from_lines parameter passed to the
903 * @return array The original sequence of strings.
908 foreach ($this->edits
as $edit) {
910 array_splice($lines, sizeof($lines), 0, $edit->orig
);
916 * Get the closing set of lines.
918 * This reconstructs the $to_lines parameter passed to the
921 * @return array The sequence of strings.
926 foreach ($this->edits
as $edit) {
928 array_splice($lines, sizeof($lines), 0, $edit->closing
);
934 * Check a Diff for validity.
936 * This is here only for debugging purposes.
938 function _check ($from_lines, $to_lines) {
939 if (serialize($from_lines) != serialize($this->orig()))
940 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
941 if (serialize($to_lines) != serialize($this->closing()))
942 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
944 $rev = $this->reverse();
945 if (serialize($to_lines) != serialize($rev->orig()))
946 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
947 if (serialize($from_lines) != serialize($rev->closing()))
948 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
952 foreach ($this->edits
as $edit) {
953 if ( $prevtype == $edit->type
)
954 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
955 $prevtype = $edit->type
;
959 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
968 class MappedDiff
extends Diff
973 * Computes diff between sequences of strings.
975 * This can be used to compute things like
976 * case-insensitve diffs, or diffs which ignore
977 * changes in white-space.
979 * @param $from_lines array An array of strings.
980 * (Typically these are lines from a file.)
982 * @param $to_lines array An array of strings.
984 * @param $mapped_from_lines array This array should
985 * have the same size number of elements as $from_lines.
986 * The elements in $mapped_from_lines and
987 * $mapped_to_lines are what is actually compared
988 * when computing the diff.
990 * @param $mapped_to_lines array This array should
991 * have the same number of elements as $to_lines.
993 function MappedDiff($from_lines, $to_lines,
994 $mapped_from_lines, $mapped_to_lines) {
996 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
997 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
999 $this->Diff($mapped_from_lines, $mapped_to_lines);
1002 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1003 $orig = &$this->edits
[$i]->orig
;
1004 if (is_array($orig)) {
1005 $orig = array_slice($from_lines, $xi, sizeof($orig));
1006 $xi +
= sizeof($orig);
1009 $closing = &$this->edits
[$i]->closing
;
1010 if (is_array($closing)) {
1011 $closing = array_slice($to_lines, $yi, sizeof($closing));
1012 $yi +
= sizeof($closing);
1019 * A class to format Diffs
1021 * This class formats the diff in classic diff format.
1022 * It is intended that this class be customized via inheritance,
1023 * to obtain fancier outputs.
1025 * @package MediaWiki
1030 * Number of leading context "lines" to preserve.
1032 * This should be left at zero for this class, but subclasses
1033 * may want to set this to other values.
1035 var $leading_context_lines = 0;
1038 * Number of trailing context "lines" to preserve.
1040 * This should be left at zero for this class, but subclasses
1041 * may want to set this to other values.
1043 var $trailing_context_lines = 0;
1048 * @param $diff object A Diff object.
1049 * @return string The formatted output.
1051 function format($diff) {
1057 $nlead = $this->leading_context_lines
;
1058 $ntrail = $this->trailing_context_lines
;
1060 $this->_start_diff();
1062 foreach ($diff->edits
as $edit) {
1063 if ($edit->type
== 'copy') {
1064 if (is_array($block)) {
1065 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1070 $context = array_slice($edit->orig
, 0, $ntrail);
1071 $block[] = new _DiffOp_Copy($context);
1073 $this->_block($x0, $ntrail +
$xi - $x0,
1074 $y0, $ntrail +
$yi - $y0,
1079 $context = $edit->orig
;
1082 if (! is_array($block)) {
1083 $context = array_slice($context, sizeof($context) - $nlead);
1084 $x0 = $xi - sizeof($context);
1085 $y0 = $yi - sizeof($context);
1088 $block[] = new _DiffOp_Copy($context);
1094 $xi +
= sizeof($edit->orig
);
1096 $yi +
= sizeof($edit->closing
);
1099 if (is_array($block))
1100 $this->_block($x0, $xi - $x0,
1104 return $this->_end_diff();
1107 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1108 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1109 foreach ($edits as $edit) {
1110 if ($edit->type
== 'copy')
1111 $this->_context($edit->orig
);
1112 elseif ($edit->type
== 'add')
1113 $this->_added($edit->closing
);
1114 elseif ($edit->type
== 'delete')
1115 $this->_deleted($edit->orig
);
1116 elseif ($edit->type
== 'change')
1117 $this->_changed($edit->orig
, $edit->closing
);
1119 trigger_error('Unknown edit type', E_USER_ERROR
);
1121 $this->_end_block();
1124 function _start_diff() {
1128 function _end_diff() {
1129 $val = ob_get_contents();
1134 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1136 $xbeg .= "," . ($xbeg +
$xlen - 1);
1138 $ybeg .= "," . ($ybeg +
$ylen - 1);
1140 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1143 function _start_block($header) {
1147 function _end_block() {
1150 function _lines($lines, $prefix = ' ') {
1151 foreach ($lines as $line)
1152 echo "$prefix $line\n";
1155 function _context($lines) {
1156 $this->_lines($lines);
1159 function _added($lines) {
1160 $this->_lines($lines, '>');
1162 function _deleted($lines) {
1163 $this->_lines($lines, '<');
1166 function _changed($orig, $closing) {
1167 $this->_deleted($orig);
1169 $this->_added($closing);
1175 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1179 define('NBSP', ' '); // iso-8859-x non-breaking space.
1183 * @package MediaWiki
1185 class _HWLDF_WordAccumulator
{
1186 function _HWLDF_WordAccumulator () {
1187 $this->_lines
= array();
1193 function _flushGroup ($new_tag) {
1194 if ($this->_group
!== '') {
1195 if ($this->_tag
== 'mark')
1196 $this->_line
.= '<span class="diffchange">' .
1197 htmlspecialchars ( $this->_group
) . '</span>';
1199 $this->_line
.= htmlspecialchars ( $this->_group
);
1202 $this->_tag
= $new_tag;
1205 function _flushLine ($new_tag) {
1206 $this->_flushGroup($new_tag);
1207 if ($this->_line
!= '')
1208 array_push ( $this->_lines
, $this->_line
);
1210 # make empty lines visible by inserting an NBSP
1211 array_push ( $this->_lines
, NBSP
);
1215 function addWords ($words, $tag = '') {
1216 if ($tag != $this->_tag
)
1217 $this->_flushGroup($tag);
1219 foreach ($words as $word) {
1220 // new-line should only come as first char of word.
1223 if ($word[0] == "\n") {
1224 $this->_flushLine($tag);
1225 $word = substr($word, 1);
1227 assert(!strstr($word, "\n"));
1228 $this->_group
.= $word;
1232 function getLines() {
1233 $this->_flushLine('~done');
1234 return $this->_lines
;
1240 * @package MediaWiki
1242 class WordLevelDiff
extends MappedDiff
1244 function WordLevelDiff ($orig_lines, $closing_lines) {
1245 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1246 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1249 $this->MappedDiff($orig_words, $closing_words,
1250 $orig_stripped, $closing_stripped);
1253 function _split($lines) {
1254 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1255 implode("\n", $lines),
1257 return array(array(''), array(''));
1259 return array($m[0], $m[1]);
1263 $orig = new _HWLDF_WordAccumulator
;
1265 foreach ($this->edits
as $edit) {
1266 if ($edit->type
== 'copy')
1267 $orig->addWords($edit->orig
);
1268 elseif ($edit->orig
)
1269 $orig->addWords($edit->orig
, 'mark');
1271 return $orig->getLines();
1274 function closing () {
1275 $closing = new _HWLDF_WordAccumulator
;
1277 foreach ($this->edits
as $edit) {
1278 if ($edit->type
== 'copy')
1279 $closing->addWords($edit->closing
);
1280 elseif ($edit->closing
)
1281 $closing->addWords($edit->closing
, 'mark');
1283 return $closing->getLines();
1288 * Wikipedia Table style diff formatter.
1290 * @package MediaWiki
1292 class TableDiffFormatter
extends DiffFormatter
1294 function TableDiffFormatter() {
1295 $this->leading_context_lines
= 2;
1296 $this->trailing_context_lines
= 2;
1299 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1300 $l1 = wfMsg( 'lineno', $xbeg );
1301 $l2 = wfMsg( 'lineno', $ybeg );
1303 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1304 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1308 function _start_block( $header ) {
1310 $wgOut->addHTML( $header );
1313 function _end_block() {
1316 function _lines( $lines, $prefix=' ', $color='white' ) {
1319 # HTML-escape parameter before calling this
1320 function addedLine( $line ) {
1321 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1324 # HTML-escape parameter before calling this
1325 function deletedLine( $line ) {
1326 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1329 # HTML-escape parameter before calling this
1330 function contextLine( $line ) {
1331 return "<td> </td><td class='diff-context'>{$line}</td>";
1334 function emptyLine() {
1335 return '<td colspan="2"> </td>';
1338 function _added( $lines ) {
1340 foreach ($lines as $line) {
1341 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1342 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1346 function _deleted($lines) {
1348 foreach ($lines as $line) {
1349 $wgOut->addHTML( '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1350 $this->emptyLine() . "</tr>\n" );
1354 function _context( $lines ) {
1356 foreach ($lines as $line) {
1357 $wgOut->addHTML( '<tr>' .
1358 $this->contextLine( htmlspecialchars ( $line ) ) .
1359 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1363 function _changed( $orig, $closing ) {
1365 $diff = new WordLevelDiff( $orig, $closing );
1366 $del = $diff->orig();
1367 $add = $diff->closing();
1369 # Notice that WordLevelDiff returns HTML-escaped output.
1370 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1372 while ( $line = array_shift( $del ) ) {
1373 $aline = array_shift( $add );
1374 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1375 $this->addedLine( $aline ) . "</tr>\n" );
1377 foreach ($add as $line) { # If any leftovers
1378 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1379 $this->addedLine( $line ) . "</tr>\n" );