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->isAllowed('rollback') ) {
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->isAllowed('rollback') ||
!$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 )
213 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
216 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
217 global $wgUseExternalDiffEngine;
219 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
221 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
222 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
226 if ( $wgUseExternalDiffEngine ) {
227 # For historical reasons, external diff engine expects
228 # input text to be HTML-escaped already
229 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
230 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
231 dl('php_wikidiff.so');
232 $out .= wikidiff_do_diff( $otext, $ntext, 2 );
234 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
235 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
236 $diffs =& new Diff( $ota, $nta );
237 $formatter =& new TableDiffFormatter();
238 $out .= $formatter->format( $diffs );
240 $out .= "</table>\n";
244 # Load the text of the articles to compare. If newid is 0, then compare
245 # the old article in oldid to the current article; if oldid is 0, then
246 # compare the current article to the immediately previous one (ignoring
247 # the value of newid).
251 global $wgTitle, $wgOut, $wgLang;
252 $fname = 'DifferenceEngine::loadText';
254 $dbr =& wfGetDB( DB_SLAVE
);
255 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
256 $wgOut->setArticleFlag( true );
257 $newLink = $wgTitle->escapeLocalUrl();
258 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
259 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
260 $id = $wgTitle->getArticleID();
262 $s = $dbr->selectRow( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
263 array( 'cur_id' => $id ), $fname );
264 if ( $s === false ) {
265 wfDebug( "Unable to load cur_id $id\n" );
269 $this->mNewPage
= &$wgTitle;
270 $this->mNewtext
= $s->cur_text
;
271 $this->mNewUser
= $s->cur_user_text
;
272 $this->mNewComment
= $s->cur_comment
;
274 $s = $dbr->selectRow( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
275 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
277 if ( $s === false ) {
278 wfDebug( "Unable to load old_id {$this->mNewid}\n" );
282 $this->mNewtext
= Article
::getRevisionText( $s );
284 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
285 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
286 $newLink = $wgTitle->escapeLocalUrl ('oldid=' . $this->mNewid
);
287 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
288 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
289 $this->mNewUser
= $s->old_user_text
;
290 $this->mNewComment
= $s->old_comment
;
292 if ( 0 == $this->mOldid
) {
293 $s = $dbr->selectRow( 'old',
294 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
296 'old_namespace' => $this->mNewPage
->getNamespace(),
297 'old_title' => $this->mNewPage
->getDBkey()
298 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
300 if ( $s === false ) {
301 wfDebug( 'Unable to load ' . $this->mNewPage
->getPrefixedDBkey() . " from old\n" );
305 $s = $dbr->selectRow( 'old',
306 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
307 array( 'old_id' => $this->mOldid
),
310 if ( $s === false ) {
311 wfDebug( "Unable to load old_id {$this->mOldid}\n" );
315 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
316 $this->mOldtext
= Article
::getRevisionText( $s );
318 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
319 $oldLink = $this->mOldPage
->escapeLocalUrl ('oldid=' . $this->mOldid
);
320 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
321 $this->mOldUser
= $s->old_user_text
;
322 $this->mOldComment
= $s->old_comment
;
328 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
330 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
331 // You may copy this code freely under the conditions of the GPL.
334 define('USE_ASSERTS', function_exists('assert'));
346 trigger_error('pure virtual', E_USER_ERROR
);
350 return $this->orig ?
sizeof($this->orig
) : 0;
353 function nclosing() {
354 return $this->closing ?
sizeof($this->closing
) : 0;
362 class _DiffOp_Copy
extends _DiffOp
{
365 function _DiffOp_Copy ($orig, $closing = false) {
366 if (!is_array($closing))
369 $this->closing
= $closing;
373 return new _DiffOp_Copy($this->closing
, $this->orig
);
381 class _DiffOp_Delete
extends _DiffOp
{
382 var $type = 'delete';
384 function _DiffOp_Delete ($lines) {
385 $this->orig
= $lines;
386 $this->closing
= false;
390 return new _DiffOp_Add($this->orig
);
398 class _DiffOp_Add
extends _DiffOp
{
401 function _DiffOp_Add ($lines) {
402 $this->closing
= $lines;
407 return new _DiffOp_Delete($this->closing
);
415 class _DiffOp_Change
extends _DiffOp
{
416 var $type = 'change';
418 function _DiffOp_Change ($orig, $closing) {
420 $this->closing
= $closing;
424 return new _DiffOp_Change($this->closing
, $this->orig
);
430 * Class used internally by Diff to actually compute the diffs.
432 * The algorithm used here is mostly lifted from the perl module
433 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
434 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
436 * More ideas are taken from:
437 * http://www.ics.uci.edu/~eppstein/161/960229.html
439 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
440 * diffutils-2.7, which can be found at:
441 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
443 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
446 * @author Geoffrey T. Dairiki
452 function diff ($from_lines, $to_lines) {
453 $n_from = sizeof($from_lines);
454 $n_to = sizeof($to_lines);
456 $this->xchanged
= $this->ychanged
= array();
457 $this->xv
= $this->yv
= array();
458 $this->xind
= $this->yind
= array();
460 unset($this->in_seq
);
463 // Skip leading common lines.
464 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
465 if ($from_lines[$skip] != $to_lines[$skip])
467 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
469 // Skip trailing common lines.
470 $xi = $n_from; $yi = $n_to;
471 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
472 if ($from_lines[$xi] != $to_lines[$yi])
474 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
477 // Ignore lines which do not exist in both files.
478 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
479 $xhash[$from_lines[$xi]] = 1;
480 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
481 $line = $to_lines[$yi];
482 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
488 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
489 $line = $from_lines[$xi];
490 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
497 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
499 // Merge edits when possible
500 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
501 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
503 // Compute the edit operations.
506 while ($xi < $n_from ||
$yi < $n_to) {
507 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
508 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
510 // Skip matching "snake".
512 while ( $xi < $n_from && $yi < $n_to
513 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
514 $copy[] = $from_lines[$xi++
];
518 $edits[] = new _DiffOp_Copy($copy);
520 // Find deletes & adds.
522 while ($xi < $n_from && $this->xchanged
[$xi])
523 $delete[] = $from_lines[$xi++
];
526 while ($yi < $n_to && $this->ychanged
[$yi])
527 $add[] = $to_lines[$yi++
];
530 $edits[] = new _DiffOp_Change($delete, $add);
532 $edits[] = new _DiffOp_Delete($delete);
534 $edits[] = new _DiffOp_Add($add);
540 /* Divide the Largest Common Subsequence (LCS) of the sequences
541 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
544 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
545 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
546 * sub sequences. The first sub-sequence is contained in [X0, X1),
547 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
548 * that (X0, Y0) == (XOFF, YOFF) and
549 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
551 * This function assumes that the first lines of the specified portions
552 * of the two files do not match, and likewise that the last lines do not
553 * match. The caller must trim matching lines from the beginning and end
554 * of the portions it is going to specify.
556 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
559 if ($xlim - $xoff > $ylim - $yoff) {
560 // Things seems faster (I'm not sure I understand why)
561 // when the shortest sequence in X.
563 list ($xoff, $xlim, $yoff, $ylim)
564 = array( $yoff, $ylim, $xoff, $xlim);
568 for ($i = $ylim - 1; $i >= $yoff; $i--)
569 $ymatches[$this->xv
[$i]][] = $i;
571 for ($i = $ylim - 1; $i >= $yoff; $i--)
572 $ymatches[$this->yv
[$i]][] = $i;
575 $this->seq
[0]= $yoff - 1;
576 $this->in_seq
= array();
579 $numer = $xlim - $xoff +
$nchunks - 1;
581 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
583 for ($i = 0; $i <= $this->lcs
; $i++
)
584 $ymids[$i][$chunk-1] = $this->seq
[$i];
586 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
587 for ( ; $x < $x1; $x++
) {
588 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
589 if (empty($ymatches[$line]))
591 $matches = $ymatches[$line];
593 while (list ($junk, $y) = each($matches))
594 if (empty($this->in_seq
[$y])) {
595 $k = $this->_lcs_pos($y);
596 USE_ASSERTS
&& assert($k > 0);
597 $ymids[$k] = $ymids[$k-1];
600 while (list ($junk, $y) = each($matches)) {
601 if ($y > $this->seq
[$k-1]) {
602 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
603 // Optimization: this is a common case:
604 // next match is just replacing previous match.
605 $this->in_seq
[$this->seq
[$k]] = false;
607 $this->in_seq
[$y] = 1;
609 else if (empty($this->in_seq
[$y])) {
610 $k = $this->_lcs_pos($y);
611 USE_ASSERTS
&& assert($k > 0);
612 $ymids[$k] = $ymids[$k-1];
618 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
619 $ymid = $ymids[$this->lcs
];
620 for ($n = 0; $n < $nchunks - 1; $n++
) {
621 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
623 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
625 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
627 return array($this->lcs
, $seps);
630 function _lcs_pos ($ypos) {
632 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
633 $this->seq
[++
$this->lcs
] = $ypos;
634 $this->in_seq
[$ypos] = 1;
639 while ($beg < $end) {
640 $mid = (int)(($beg +
$end) / 2);
641 if ( $ypos > $this->seq
[$mid] )
647 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
649 $this->in_seq
[$this->seq
[$end]] = false;
650 $this->seq
[$end] = $ypos;
651 $this->in_seq
[$ypos] = 1;
655 /* Find LCS of two sequences.
657 * The results are recorded in the vectors $this->{x,y}changed[], by
658 * storing a 1 in the element for each line that is an insertion
659 * or deletion (ie. is not in the LCS).
661 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
663 * Note that XLIM, YLIM are exclusive bounds.
664 * All line numbers are origin-0 and discarded lines are not counted.
666 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
667 // Slide down the bottom initial diagonal.
668 while ($xoff < $xlim && $yoff < $ylim
669 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
674 // Slide up the top initial diagonal.
675 while ($xlim > $xoff && $ylim > $yoff
676 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
681 if ($xoff == $xlim ||
$yoff == $ylim)
684 // This is ad hoc but seems to work well.
685 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
686 //$nchunks = max(2,min(8,(int)$nchunks));
687 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
689 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
693 // X and Y sequences have no common subsequence:
695 while ($yoff < $ylim)
696 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
697 while ($xoff < $xlim)
698 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
701 // Use the partitions to split this problem into subproblems.
704 while ($pt2 = next($seps)) {
705 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
711 /* Adjust inserts/deletes of identical lines to join changes
712 * as much as possible.
714 * We do something when a run of changed lines include a
715 * line at one end and has an excluded, identical line at the other.
716 * We are free to choose which identical line is included.
717 * `compareseq' usually chooses the one at the beginning,
718 * but usually it is cleaner to consider the following identical line
719 * to be the "change".
721 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
723 function _shift_boundaries ($lines, &$changed, $other_changed) {
727 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
728 $len = sizeof($lines);
729 $other_len = sizeof($other_changed);
733 * Scan forwards to find beginning of another run of changes.
734 * Also keep track of the corresponding point in the other file.
736 * Throughout this code, $i and $j are adjusted together so that
737 * the first $i elements of $changed and the first $j elements
738 * of $other_changed both contain the same number of zeros
740 * Furthermore, $j is always kept so that $j == $other_len or
741 * $other_changed[$j] == false.
743 while ($j < $other_len && $other_changed[$j])
746 while ($i < $len && ! $changed[$i]) {
747 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
749 while ($j < $other_len && $other_changed[$j])
758 // Find the end of this run of changes.
759 while (++
$i < $len && $changed[$i])
764 * Record the length of this run of changes, so that
765 * we can later determine whether the run has grown.
767 $runlength = $i - $start;
770 * Move the changed region back, so long as the
771 * previous unchanged line matches the last changed one.
772 * This merges with previous changed regions.
774 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
775 $changed[--$start] = 1;
776 $changed[--$i] = false;
777 while ($start > 0 && $changed[$start - 1])
779 USE_ASSERTS
&& assert('$j > 0');
780 while ($other_changed[--$j])
782 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
786 * Set CORRESPONDING to the end of the changed run, at the last
787 * point where it corresponds to a changed run in the other file.
788 * CORRESPONDING == LEN means no such point has been found.
790 $corresponding = $j < $other_len ?
$i : $len;
793 * Move the changed region forward, so long as the
794 * first changed line matches the following unchanged one.
795 * This merges with following changed regions.
796 * Do this second, so that if there are no merges,
797 * the changed region is moved forward as far as possible.
799 while ($i < $len && $lines[$start] == $lines[$i]) {
800 $changed[$start++
] = false;
802 while ($i < $len && $changed[$i])
805 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
807 if ($j < $other_len && $other_changed[$j]) {
809 while ($j < $other_len && $other_changed[$j])
813 } while ($runlength != $i - $start);
816 * If possible, move the fully-merged run of changes
817 * back to a corresponding run in the other file.
819 while ($corresponding < $i) {
820 $changed[--$start] = 1;
822 USE_ASSERTS
&& assert('$j > 0');
823 while ($other_changed[--$j])
825 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
832 * Class representing a 'diff' between two sequences of strings.
842 * Computes diff between sequences of strings.
844 * @param $from_lines array An array of strings.
845 * (Typically these are lines from a file.)
846 * @param $to_lines array An array of strings.
848 function Diff($from_lines, $to_lines) {
849 $eng = new _DiffEngine
;
850 $this->edits
= $eng->diff($from_lines, $to_lines);
851 //$this->_check($from_lines, $to_lines);
855 * Compute reversed Diff.
859 * $diff = new Diff($lines1, $lines2);
860 * $rev = $diff->reverse();
861 * @return object A Diff object representing the inverse of the
864 function reverse () {
866 $rev->edits
= array();
867 foreach ($this->edits
as $edit) {
868 $rev->edits
[] = $edit->reverse();
874 * Check for empty diff.
876 * @return bool True iff two sequences were identical.
878 function isEmpty () {
879 foreach ($this->edits
as $edit) {
880 if ($edit->type
!= 'copy')
887 * Compute the length of the Longest Common Subsequence (LCS).
889 * This is mostly for diagnostic purposed.
891 * @return int The length of the LCS.
895 foreach ($this->edits
as $edit) {
896 if ($edit->type
== 'copy')
897 $lcs +
= sizeof($edit->orig
);
903 * Get the original set of lines.
905 * This reconstructs the $from_lines parameter passed to the
908 * @return array The original sequence of strings.
913 foreach ($this->edits
as $edit) {
915 array_splice($lines, sizeof($lines), 0, $edit->orig
);
921 * Get the closing set of lines.
923 * This reconstructs the $to_lines parameter passed to the
926 * @return array The sequence of strings.
931 foreach ($this->edits
as $edit) {
933 array_splice($lines, sizeof($lines), 0, $edit->closing
);
939 * Check a Diff for validity.
941 * This is here only for debugging purposes.
943 function _check ($from_lines, $to_lines) {
944 if (serialize($from_lines) != serialize($this->orig()))
945 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
946 if (serialize($to_lines) != serialize($this->closing()))
947 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
949 $rev = $this->reverse();
950 if (serialize($to_lines) != serialize($rev->orig()))
951 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
952 if (serialize($from_lines) != serialize($rev->closing()))
953 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
957 foreach ($this->edits
as $edit) {
958 if ( $prevtype == $edit->type
)
959 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
960 $prevtype = $edit->type
;
964 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
973 class MappedDiff
extends Diff
978 * Computes diff between sequences of strings.
980 * This can be used to compute things like
981 * case-insensitve diffs, or diffs which ignore
982 * changes in white-space.
984 * @param $from_lines array An array of strings.
985 * (Typically these are lines from a file.)
987 * @param $to_lines array An array of strings.
989 * @param $mapped_from_lines array This array should
990 * have the same size number of elements as $from_lines.
991 * The elements in $mapped_from_lines and
992 * $mapped_to_lines are what is actually compared
993 * when computing the diff.
995 * @param $mapped_to_lines array This array should
996 * have the same number of elements as $to_lines.
998 function MappedDiff($from_lines, $to_lines,
999 $mapped_from_lines, $mapped_to_lines) {
1001 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1002 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1004 $this->Diff($mapped_from_lines, $mapped_to_lines);
1007 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1008 $orig = &$this->edits
[$i]->orig
;
1009 if (is_array($orig)) {
1010 $orig = array_slice($from_lines, $xi, sizeof($orig));
1011 $xi +
= sizeof($orig);
1014 $closing = &$this->edits
[$i]->closing
;
1015 if (is_array($closing)) {
1016 $closing = array_slice($to_lines, $yi, sizeof($closing));
1017 $yi +
= sizeof($closing);
1024 * A class to format Diffs
1026 * This class formats the diff in classic diff format.
1027 * It is intended that this class be customized via inheritance,
1028 * to obtain fancier outputs.
1030 * @package MediaWiki
1035 * Number of leading context "lines" to preserve.
1037 * This should be left at zero for this class, but subclasses
1038 * may want to set this to other values.
1040 var $leading_context_lines = 0;
1043 * Number of trailing context "lines" to preserve.
1045 * This should be left at zero for this class, but subclasses
1046 * may want to set this to other values.
1048 var $trailing_context_lines = 0;
1053 * @param $diff object A Diff object.
1054 * @return string The formatted output.
1056 function format($diff) {
1062 $nlead = $this->leading_context_lines
;
1063 $ntrail = $this->trailing_context_lines
;
1065 $this->_start_diff();
1067 foreach ($diff->edits
as $edit) {
1068 if ($edit->type
== 'copy') {
1069 if (is_array($block)) {
1070 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1075 $context = array_slice($edit->orig
, 0, $ntrail);
1076 $block[] = new _DiffOp_Copy($context);
1078 $this->_block($x0, $ntrail +
$xi - $x0,
1079 $y0, $ntrail +
$yi - $y0,
1084 $context = $edit->orig
;
1087 if (! is_array($block)) {
1088 $context = array_slice($context, sizeof($context) - $nlead);
1089 $x0 = $xi - sizeof($context);
1090 $y0 = $yi - sizeof($context);
1093 $block[] = new _DiffOp_Copy($context);
1099 $xi +
= sizeof($edit->orig
);
1101 $yi +
= sizeof($edit->closing
);
1104 if (is_array($block))
1105 $this->_block($x0, $xi - $x0,
1109 return $this->_end_diff();
1112 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1113 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1114 foreach ($edits as $edit) {
1115 if ($edit->type
== 'copy')
1116 $this->_context($edit->orig
);
1117 elseif ($edit->type
== 'add')
1118 $this->_added($edit->closing
);
1119 elseif ($edit->type
== 'delete')
1120 $this->_deleted($edit->orig
);
1121 elseif ($edit->type
== 'change')
1122 $this->_changed($edit->orig
, $edit->closing
);
1124 trigger_error('Unknown edit type', E_USER_ERROR
);
1126 $this->_end_block();
1129 function _start_diff() {
1133 function _end_diff() {
1134 $val = ob_get_contents();
1139 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1141 $xbeg .= "," . ($xbeg +
$xlen - 1);
1143 $ybeg .= "," . ($ybeg +
$ylen - 1);
1145 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1148 function _start_block($header) {
1152 function _end_block() {
1155 function _lines($lines, $prefix = ' ') {
1156 foreach ($lines as $line)
1157 echo "$prefix $line\n";
1160 function _context($lines) {
1161 $this->_lines($lines);
1164 function _added($lines) {
1165 $this->_lines($lines, '>');
1167 function _deleted($lines) {
1168 $this->_lines($lines, '<');
1171 function _changed($orig, $closing) {
1172 $this->_deleted($orig);
1174 $this->_added($closing);
1180 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1184 define('NBSP', ' '); // iso-8859-x non-breaking space.
1188 * @package MediaWiki
1190 class _HWLDF_WordAccumulator
{
1191 function _HWLDF_WordAccumulator () {
1192 $this->_lines
= array();
1198 function _flushGroup ($new_tag) {
1199 if ($this->_group
!== '') {
1200 if ($this->_tag
== 'mark')
1201 $this->_line
.= '<span class="diffchange">' .
1202 htmlspecialchars ( $this->_group
) . '</span>';
1204 $this->_line
.= htmlspecialchars ( $this->_group
);
1207 $this->_tag
= $new_tag;
1210 function _flushLine ($new_tag) {
1211 $this->_flushGroup($new_tag);
1212 if ($this->_line
!= '')
1213 array_push ( $this->_lines
, $this->_line
);
1215 # make empty lines visible by inserting an NBSP
1216 array_push ( $this->_lines
, NBSP
);
1220 function addWords ($words, $tag = '') {
1221 if ($tag != $this->_tag
)
1222 $this->_flushGroup($tag);
1224 foreach ($words as $word) {
1225 // new-line should only come as first char of word.
1228 if ($word[0] == "\n") {
1229 $this->_flushLine($tag);
1230 $word = substr($word, 1);
1232 assert(!strstr($word, "\n"));
1233 $this->_group
.= $word;
1237 function getLines() {
1238 $this->_flushLine('~done');
1239 return $this->_lines
;
1245 * @package MediaWiki
1247 class WordLevelDiff
extends MappedDiff
1249 function WordLevelDiff ($orig_lines, $closing_lines) {
1250 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1251 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1254 $this->MappedDiff($orig_words, $closing_words,
1255 $orig_stripped, $closing_stripped);
1258 function _split($lines) {
1259 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1260 implode("\n", $lines),
1262 return array(array(''), array(''));
1264 return array($m[0], $m[1]);
1268 $orig = new _HWLDF_WordAccumulator
;
1270 foreach ($this->edits
as $edit) {
1271 if ($edit->type
== 'copy')
1272 $orig->addWords($edit->orig
);
1273 elseif ($edit->orig
)
1274 $orig->addWords($edit->orig
, 'mark');
1276 return $orig->getLines();
1279 function closing () {
1280 $closing = new _HWLDF_WordAccumulator
;
1282 foreach ($this->edits
as $edit) {
1283 if ($edit->type
== 'copy')
1284 $closing->addWords($edit->closing
);
1285 elseif ($edit->closing
)
1286 $closing->addWords($edit->closing
, 'mark');
1288 return $closing->getLines();
1293 * Wikipedia Table style diff formatter.
1295 * @package MediaWiki
1297 class TableDiffFormatter
extends DiffFormatter
1299 function TableDiffFormatter() {
1300 $this->leading_context_lines
= 2;
1301 $this->trailing_context_lines
= 2;
1304 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1305 $l1 = wfMsg( 'lineno', $xbeg );
1306 $l2 = wfMsg( 'lineno', $ybeg );
1308 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1309 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1313 function _start_block( $header ) {
1318 function _end_block() {
1321 function _lines( $lines, $prefix=' ', $color='white' ) {
1324 # HTML-escape parameter before calling this
1325 function addedLine( $line ) {
1326 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1329 # HTML-escape parameter before calling this
1330 function deletedLine( $line ) {
1331 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1334 # HTML-escape parameter before calling this
1335 function contextLine( $line ) {
1336 return "<td> </td><td class='diff-context'>{$line}</td>";
1339 function emptyLine() {
1340 return '<td colspan="2"> </td>';
1343 function _added( $lines ) {
1344 foreach ($lines as $line) {
1345 echo '<tr>' . $this->emptyLine() .
1346 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1350 function _deleted($lines) {
1351 foreach ($lines as $line) {
1352 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1353 $this->emptyLine() . "</tr>\n";
1357 function _context( $lines ) {
1358 foreach ($lines as $line) {
1360 $this->contextLine( htmlspecialchars ( $line ) ) .
1361 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1365 function _changed( $orig, $closing ) {
1366 $diff = new WordLevelDiff( $orig, $closing );
1367 $del = $diff->orig();
1368 $add = $diff->closing();
1370 # Notice that WordLevelDiff returns HTML-escaped output.
1371 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1373 while ( $line = array_shift( $del ) ) {
1374 $aline = array_shift( $add );
1375 echo '<tr>' . $this->deletedLine( $line ) .
1376 $this->addedLine( $aline ) . "</tr>\n";
1378 foreach ($add as $line) { # If any leftovers
1379 echo '<tr>' . $this->emptyLine() .
1380 $this->addedLine( $line ) . "</tr>\n";