f4a3a9f8ca785a46eeafe1722dfc736f71c93545
4 class DifferenceEngine
{
5 /* private */ var $mOldid, $mNewid;
6 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
7 /* private */ var $mOldtext, $mNewtext;
8 /* private */ var $mOldUser, $mNewUser;
9 /* private */ var $mOldComment, $mNewComment;
10 /* private */ var $mOldPage, $mNewPage;
11 /* private */ var $mRcidMarkPatrolled;
13 function DifferenceEngine( $old, $new, $rcid = 0 )
16 if ( 'prev' == $new ) {
17 # Show diff between revision $old and the previous one.
18 # Get previous one from DB.
20 $this->mNewid
= intval($old);
21 $dbr =& wfGetDB( DB_SLAVE
);
22 $this->mOldid
= $dbr->selectField( 'old', 'old_id',
23 "old_title='" . $wgTitle->getDBkey() . "'" .
24 ' AND old_namespace=' . $wgTitle->getNamespace() .
25 " AND old_id<{$this->mNewid} ORDER BY old_id DESC" );
27 } elseif ( 'next' == $new ) {
29 # Show diff between revision $old and the previous one.
30 # Get previous one from DB.
32 $this->mOldid
= intval($old);
33 $dbr =& wfGetDB( DB_SLAVE
);
34 $this->mNewid
= $dbr->selectField( 'old', 'old_id',
35 "old_title='" . $wgTitle->getDBkey() . "'" .
36 ' AND old_namespace=' . $wgTitle->getNamespace() .
37 " AND old_id>{$this->mOldid} ORDER BY old_id " );
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, $wgLang, $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 = $wgLang->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;
214 $otext = str_replace( "\r\n", "\n", htmlspecialchars( $otext ) );
215 $ntext = str_replace( "\r\n", "\n", htmlspecialchars( $ntext ) );
218 $wgOut->addHTML( "<table border='0' width='98%'
219 cellpadding='0' cellspacing='4px' class='diff'><tr>
220 <td colspan='2' width='50%' align='center' class='diff-otitle'>
222 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
225 if ( $wgUseExternalDiffEngine ) {
226 dl('php_wikidiff.so');
227 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
229 $ota = explode( "\n", $otext);
230 $nta = explode( "\n", $ntext);
231 $diffs = new Diff( $ota, $nta );
232 $formatter = new TableDiffFormatter();
233 $formatter->format( $diffs );
235 $wgOut->addHTML( "</table>\n" );
238 # Load the text of the articles to compare. If newid is 0, then compare
239 # the old article in oldid to the current article; if oldid is 0, then
240 # compare the current article to the immediately previous one (ignoring
241 # the value of newid).
245 global $wgTitle, $wgOut, $wgLang;
246 $fname = 'DifferenceEngine::loadText';
248 $dbr =& wfGetDB( DB_SLAVE
);
249 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
250 $wgOut->setArticleFlag( true );
251 $newLink = $wgTitle->getLocalUrl();
252 $this->mPagetitle
= wfMsg( 'currentrev' );
253 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
254 $id = $wgTitle->getArticleID();
256 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
257 array( 'cur_id' => $id ), $fname );
258 if ( $s === false ) {
262 $this->mNewPage
= &$wgTitle;
263 $this->mNewtext
= $s->cur_text
;
264 $this->mNewUser
= $s->cur_user_text
;
265 $this->mNewComment
= $s->cur_comment
;
267 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
268 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
270 if ( $s === false ) {
274 $this->mNewtext
= Article
::getRevisionText( $s );
276 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
277 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
278 $newLink = $wgTitle->getLocalUrl ('oldid=' . $this->mNewid
);
279 $this->mPagetitle
= wfMsg( 'revisionasof', $t );
280 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
281 $this->mNewUser
= $s->old_user_text
;
282 $this->mNewComment
= $s->old_comment
;
284 if ( 0 == $this->mOldid
) {
285 $s = $dbr->getArray( 'old',
286 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
288 'old_namespace' => $this->mNewPage
->getNamespace(),
289 'old_title' => $this->mNewPage
->getDBkey()
290 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
293 $s = $dbr->getArray( 'old',
294 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
295 array( 'old_id' => $this->mOldid
),
299 if ( $s === false ) {
302 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
303 $this->mOldtext
= Article
::getRevisionText( $s );
305 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
306 $oldLink = $this->mOldPage
->getLocalUrl ('oldid=' . $this->mOldid
);
307 $this->mOldtitle
= "<a href='$oldLink'>" . wfMsg( 'revisionasof', $t ) . '</a>';
308 $this->mOldUser
= $s->old_user_text
;
309 $this->mOldComment
= $s->old_comment
;
315 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
317 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
318 // You may copy this code freely under the conditions of the GPL.
321 define('USE_ASSERTS', function_exists('assert'));
329 trigger_error('pure virtual', E_USER_ERROR
);
333 return $this->orig ?
sizeof($this->orig
) : 0;
336 function nclosing() {
337 return $this->closing ?
sizeof($this->closing
) : 0;
341 class _DiffOp_Copy
extends _DiffOp
{
344 function _DiffOp_Copy ($orig, $closing = false) {
345 if (!is_array($closing))
348 $this->closing
= $closing;
352 return new _DiffOp_Copy($this->closing
, $this->orig
);
356 class _DiffOp_Delete
extends _DiffOp
{
357 var $type = 'delete';
359 function _DiffOp_Delete ($lines) {
360 $this->orig
= $lines;
361 $this->closing
= false;
365 return new _DiffOp_Add($this->orig
);
369 class _DiffOp_Add
extends _DiffOp
{
372 function _DiffOp_Add ($lines) {
373 $this->closing
= $lines;
378 return new _DiffOp_Delete($this->closing
);
382 class _DiffOp_Change
extends _DiffOp
{
383 var $type = 'change';
385 function _DiffOp_Change ($orig, $closing) {
387 $this->closing
= $closing;
391 return new _DiffOp_Change($this->closing
, $this->orig
);
397 * Class used internally by Diff to actually compute the diffs.
399 * The algorithm used here is mostly lifted from the perl module
400 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
401 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
403 * More ideas are taken from:
404 * http://www.ics.uci.edu/~eppstein/161/960229.html
406 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
407 * diffutils-2.7, which can be found at:
408 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
410 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
413 * @author Geoffrey T. Dairiki
418 function diff ($from_lines, $to_lines) {
419 $n_from = sizeof($from_lines);
420 $n_to = sizeof($to_lines);
422 $this->xchanged
= $this->ychanged
= array();
423 $this->xv
= $this->yv
= array();
424 $this->xind
= $this->yind
= array();
426 unset($this->in_seq
);
429 // Skip leading common lines.
430 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
431 if ($from_lines[$skip] != $to_lines[$skip])
433 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
435 // Skip trailing common lines.
436 $xi = $n_from; $yi = $n_to;
437 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
438 if ($from_lines[$xi] != $to_lines[$yi])
440 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
443 // Ignore lines which do not exist in both files.
444 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
445 $xhash[$from_lines[$xi]] = 1;
446 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
447 $line = $to_lines[$yi];
448 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
454 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
455 $line = $from_lines[$xi];
456 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
463 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
465 // Merge edits when possible
466 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
467 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
469 // Compute the edit operations.
472 while ($xi < $n_from ||
$yi < $n_to) {
473 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
474 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
476 // Skip matching "snake".
478 while ( $xi < $n_from && $yi < $n_to
479 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
480 $copy[] = $from_lines[$xi++
];
484 $edits[] = new _DiffOp_Copy($copy);
486 // Find deletes & adds.
488 while ($xi < $n_from && $this->xchanged
[$xi])
489 $delete[] = $from_lines[$xi++
];
492 while ($yi < $n_to && $this->ychanged
[$yi])
493 $add[] = $to_lines[$yi++
];
496 $edits[] = new _DiffOp_Change($delete, $add);
498 $edits[] = new _DiffOp_Delete($delete);
500 $edits[] = new _DiffOp_Add($add);
506 /* Divide the Largest Common Subsequence (LCS) of the sequences
507 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
510 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
511 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
512 * sub sequences. The first sub-sequence is contained in [X0, X1),
513 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
514 * that (X0, Y0) == (XOFF, YOFF) and
515 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
517 * This function assumes that the first lines of the specified portions
518 * of the two files do not match, and likewise that the last lines do not
519 * match. The caller must trim matching lines from the beginning and end
520 * of the portions it is going to specify.
522 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
525 if ($xlim - $xoff > $ylim - $yoff) {
526 // Things seems faster (I'm not sure I understand why)
527 // when the shortest sequence in X.
529 list ($xoff, $xlim, $yoff, $ylim)
530 = array( $yoff, $ylim, $xoff, $xlim);
534 for ($i = $ylim - 1; $i >= $yoff; $i--)
535 $ymatches[$this->xv
[$i]][] = $i;
537 for ($i = $ylim - 1; $i >= $yoff; $i--)
538 $ymatches[$this->yv
[$i]][] = $i;
541 $this->seq
[0]= $yoff - 1;
542 $this->in_seq
= array();
545 $numer = $xlim - $xoff +
$nchunks - 1;
547 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
549 for ($i = 0; $i <= $this->lcs
; $i++
)
550 $ymids[$i][$chunk-1] = $this->seq
[$i];
552 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
553 for ( ; $x < $x1; $x++
) {
554 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
555 if (empty($ymatches[$line]))
557 $matches = $ymatches[$line];
559 while (list ($junk, $y) = each($matches))
560 if (empty($this->in_seq
[$y])) {
561 $k = $this->_lcs_pos($y);
562 USE_ASSERTS
&& assert($k > 0);
563 $ymids[$k] = $ymids[$k-1];
566 while (list ($junk, $y) = each($matches)) {
567 if ($y > $this->seq
[$k-1]) {
568 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
569 // Optimization: this is a common case:
570 // next match is just replacing previous match.
571 $this->in_seq
[$this->seq
[$k]] = false;
573 $this->in_seq
[$y] = 1;
575 else if (empty($this->in_seq
[$y])) {
576 $k = $this->_lcs_pos($y);
577 USE_ASSERTS
&& assert($k > 0);
578 $ymids[$k] = $ymids[$k-1];
584 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
585 $ymid = $ymids[$this->lcs
];
586 for ($n = 0; $n < $nchunks - 1; $n++
) {
587 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
589 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
591 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
593 return array($this->lcs
, $seps);
596 function _lcs_pos ($ypos) {
598 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
599 $this->seq
[++
$this->lcs
] = $ypos;
600 $this->in_seq
[$ypos] = 1;
605 while ($beg < $end) {
606 $mid = (int)(($beg +
$end) / 2);
607 if ( $ypos > $this->seq
[$mid] )
613 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
615 $this->in_seq
[$this->seq
[$end]] = false;
616 $this->seq
[$end] = $ypos;
617 $this->in_seq
[$ypos] = 1;
621 /* Find LCS of two sequences.
623 * The results are recorded in the vectors $this->{x,y}changed[], by
624 * storing a 1 in the element for each line that is an insertion
625 * or deletion (ie. is not in the LCS).
627 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
629 * Note that XLIM, YLIM are exclusive bounds.
630 * All line numbers are origin-0 and discarded lines are not counted.
632 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
633 // Slide down the bottom initial diagonal.
634 while ($xoff < $xlim && $yoff < $ylim
635 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
640 // Slide up the top initial diagonal.
641 while ($xlim > $xoff && $ylim > $yoff
642 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
647 if ($xoff == $xlim ||
$yoff == $ylim)
650 // This is ad hoc but seems to work well.
651 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
652 //$nchunks = max(2,min(8,(int)$nchunks));
653 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
655 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
659 // X and Y sequences have no common subsequence:
661 while ($yoff < $ylim)
662 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
663 while ($xoff < $xlim)
664 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
667 // Use the partitions to split this problem into subproblems.
670 while ($pt2 = next($seps)) {
671 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
677 /* Adjust inserts/deletes of identical lines to join changes
678 * as much as possible.
680 * We do something when a run of changed lines include a
681 * line at one end and has an excluded, identical line at the other.
682 * We are free to choose which identical line is included.
683 * `compareseq' usually chooses the one at the beginning,
684 * but usually it is cleaner to consider the following identical line
685 * to be the "change".
687 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
689 function _shift_boundaries ($lines, &$changed, $other_changed) {
693 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
694 $len = sizeof($lines);
695 $other_len = sizeof($other_changed);
699 * Scan forwards to find beginning of another run of changes.
700 * Also keep track of the corresponding point in the other file.
702 * Throughout this code, $i and $j are adjusted together so that
703 * the first $i elements of $changed and the first $j elements
704 * of $other_changed both contain the same number of zeros
706 * Furthermore, $j is always kept so that $j == $other_len or
707 * $other_changed[$j] == false.
709 while ($j < $other_len && $other_changed[$j])
712 while ($i < $len && ! $changed[$i]) {
713 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
715 while ($j < $other_len && $other_changed[$j])
724 // Find the end of this run of changes.
725 while (++
$i < $len && $changed[$i])
730 * Record the length of this run of changes, so that
731 * we can later determine whether the run has grown.
733 $runlength = $i - $start;
736 * Move the changed region back, so long as the
737 * previous unchanged line matches the last changed one.
738 * This merges with previous changed regions.
740 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
741 $changed[--$start] = 1;
742 $changed[--$i] = false;
743 while ($start > 0 && $changed[$start - 1])
745 USE_ASSERTS
&& assert('$j > 0');
746 while ($other_changed[--$j])
748 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
752 * Set CORRESPONDING to the end of the changed run, at the last
753 * point where it corresponds to a changed run in the other file.
754 * CORRESPONDING == LEN means no such point has been found.
756 $corresponding = $j < $other_len ?
$i : $len;
759 * Move the changed region forward, so long as the
760 * first changed line matches the following unchanged one.
761 * This merges with following changed regions.
762 * Do this second, so that if there are no merges,
763 * the changed region is moved forward as far as possible.
765 while ($i < $len && $lines[$start] == $lines[$i]) {
766 $changed[$start++
] = false;
768 while ($i < $len && $changed[$i])
771 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
773 if ($j < $other_len && $other_changed[$j]) {
775 while ($j < $other_len && $other_changed[$j])
779 } while ($runlength != $i - $start);
782 * If possible, move the fully-merged run of changes
783 * back to a corresponding run in the other file.
785 while ($corresponding < $i) {
786 $changed[--$start] = 1;
788 USE_ASSERTS
&& assert('$j > 0');
789 while ($other_changed[--$j])
791 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
798 * Class representing a 'diff' between two sequences of strings.
806 * Computes diff between sequences of strings.
808 * @param $from_lines array An array of strings.
809 * (Typically these are lines from a file.)
810 * @param $to_lines array An array of strings.
812 function Diff($from_lines, $to_lines) {
813 $eng = new _DiffEngine
;
814 $this->edits
= $eng->diff($from_lines, $to_lines);
815 //$this->_check($from_lines, $to_lines);
819 * Compute reversed Diff.
823 * $diff = new Diff($lines1, $lines2);
824 * $rev = $diff->reverse();
825 * @return object A Diff object representing the inverse of the
828 function reverse () {
830 $rev->edits
= array();
831 foreach ($this->edits
as $edit) {
832 $rev->edits
[] = $edit->reverse();
838 * Check for empty diff.
840 * @return bool True iff two sequences were identical.
842 function isEmpty () {
843 foreach ($this->edits
as $edit) {
844 if ($edit->type
!= 'copy')
851 * Compute the length of the Longest Common Subsequence (LCS).
853 * This is mostly for diagnostic purposed.
855 * @return int The length of the LCS.
859 foreach ($this->edits
as $edit) {
860 if ($edit->type
== 'copy')
861 $lcs +
= sizeof($edit->orig
);
867 * Get the original set of lines.
869 * This reconstructs the $from_lines parameter passed to the
872 * @return array The original sequence of strings.
877 foreach ($this->edits
as $edit) {
879 array_splice($lines, sizeof($lines), 0, $edit->orig
);
885 * Get the closing set of lines.
887 * This reconstructs the $to_lines parameter passed to the
890 * @return array The sequence of strings.
895 foreach ($this->edits
as $edit) {
897 array_splice($lines, sizeof($lines), 0, $edit->closing
);
903 * Check a Diff for validity.
905 * This is here only for debugging purposes.
907 function _check ($from_lines, $to_lines) {
908 if (serialize($from_lines) != serialize($this->orig()))
909 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
910 if (serialize($to_lines) != serialize($this->closing()))
911 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
913 $rev = $this->reverse();
914 if (serialize($to_lines) != serialize($rev->orig()))
915 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
916 if (serialize($from_lines) != serialize($rev->closing()))
917 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
921 foreach ($this->edits
as $edit) {
922 if ( $prevtype == $edit->type
)
923 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
924 $prevtype = $edit->type
;
928 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
941 * Computes diff between sequences of strings.
943 * This can be used to compute things like
944 * case-insensitve diffs, or diffs which ignore
945 * changes in white-space.
947 * @param $from_lines array An array of strings.
948 * (Typically these are lines from a file.)
950 * @param $to_lines array An array of strings.
952 * @param $mapped_from_lines array This array should
953 * have the same size number of elements as $from_lines.
954 * The elements in $mapped_from_lines and
955 * $mapped_to_lines are what is actually compared
956 * when computing the diff.
958 * @param $mapped_to_lines array This array should
959 * have the same number of elements as $to_lines.
961 function MappedDiff($from_lines, $to_lines,
962 $mapped_from_lines, $mapped_to_lines) {
964 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
965 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
967 $this->Diff($mapped_from_lines, $mapped_to_lines);
970 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
971 $orig = &$this->edits
[$i]->orig
;
972 if (is_array($orig)) {
973 $orig = array_slice($from_lines, $xi, sizeof($orig));
974 $xi +
= sizeof($orig);
977 $closing = &$this->edits
[$i]->closing
;
978 if (is_array($closing)) {
979 $closing = array_slice($to_lines, $yi, sizeof($closing));
980 $yi +
= sizeof($closing);
987 * A class to format Diffs
989 * This class formats the diff in classic diff format.
990 * It is intended that this class be customized via inheritance,
991 * to obtain fancier outputs.
996 * Number of leading context "lines" to preserve.
998 * This should be left at zero for this class, but subclasses
999 * may want to set this to other values.
1001 var $leading_context_lines = 0;
1004 * Number of trailing context "lines" to preserve.
1006 * This should be left at zero for this class, but subclasses
1007 * may want to set this to other values.
1009 var $trailing_context_lines = 0;
1014 * @param $diff object A Diff object.
1015 * @return string The formatted output.
1017 function format($diff) {
1023 $nlead = $this->leading_context_lines
;
1024 $ntrail = $this->trailing_context_lines
;
1026 $this->_start_diff();
1028 foreach ($diff->edits
as $edit) {
1029 if ($edit->type
== 'copy') {
1030 if (is_array($block)) {
1031 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1036 $context = array_slice($edit->orig
, 0, $ntrail);
1037 $block[] = new _DiffOp_Copy($context);
1039 $this->_block($x0, $ntrail +
$xi - $x0,
1040 $y0, $ntrail +
$yi - $y0,
1045 $context = $edit->orig
;
1048 if (! is_array($block)) {
1049 $context = array_slice($context, sizeof($context) - $nlead);
1050 $x0 = $xi - sizeof($context);
1051 $y0 = $yi - sizeof($context);
1054 $block[] = new _DiffOp_Copy($context);
1060 $xi +
= sizeof($edit->orig
);
1062 $yi +
= sizeof($edit->closing
);
1065 if (is_array($block))
1066 $this->_block($x0, $xi - $x0,
1070 return $this->_end_diff();
1073 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1074 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1075 foreach ($edits as $edit) {
1076 if ($edit->type
== 'copy')
1077 $this->_context($edit->orig
);
1078 elseif ($edit->type
== 'add')
1079 $this->_added($edit->closing
);
1080 elseif ($edit->type
== 'delete')
1081 $this->_deleted($edit->orig
);
1082 elseif ($edit->type
== 'change')
1083 $this->_changed($edit->orig
, $edit->closing
);
1085 trigger_error('Unknown edit type', E_USER_ERROR
);
1087 $this->_end_block();
1090 function _start_diff() {
1094 function _end_diff() {
1095 $val = ob_get_contents();
1100 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1102 $xbeg .= "," . ($xbeg +
$xlen - 1);
1104 $ybeg .= "," . ($ybeg +
$ylen - 1);
1106 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1109 function _start_block($header) {
1113 function _end_block() {
1116 function _lines($lines, $prefix = ' ') {
1117 foreach ($lines as $line)
1118 echo "$prefix $line\n";
1121 function _context($lines) {
1122 $this->_lines($lines);
1125 function _added($lines) {
1126 $this->_lines($lines, '>');
1128 function _deleted($lines) {
1129 $this->_lines($lines, '<');
1132 function _changed($orig, $closing) {
1133 $this->_deleted($orig);
1135 $this->_added($closing);
1141 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1145 define('NBSP', ' '); // iso-8859-x non-breaking space.
1147 class _HWLDF_WordAccumulator
{
1148 function _HWLDF_WordAccumulator () {
1149 $this->_lines
= array();
1155 function _flushGroup ($new_tag) {
1156 if ($this->_group
!== '') {
1157 if ($this->_tag
== 'mark')
1158 $this->_line
.= '<span class="diffchange">'.$this->_group
.'</span>';
1160 $this->_line
.= $this->_group
;
1163 $this->_tag
= $new_tag;
1166 function _flushLine ($new_tag) {
1167 $this->_flushGroup($new_tag);
1168 if ($this->_line
!= '')
1169 $this->_lines
[] = $this->_line
;
1173 function addWords ($words, $tag = '') {
1174 if ($tag != $this->_tag
)
1175 $this->_flushGroup($tag);
1177 foreach ($words as $word) {
1178 // new-line should only come as first char of word.
1181 if ($word[0] == "\n") {
1182 $this->_group
.= NBSP
;
1183 $this->_flushLine($tag);
1184 $word = substr($word, 1);
1186 assert(!strstr($word, "\n"));
1187 $this->_group
.= $word;
1191 function getLines() {
1192 $this->_flushLine('~done');
1193 return $this->_lines
;
1197 class WordLevelDiff
extends MappedDiff
1199 function WordLevelDiff ($orig_lines, $closing_lines) {
1200 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1201 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1204 $this->MappedDiff($orig_words, $closing_words,
1205 $orig_stripped, $closing_stripped);
1208 function _split($lines) {
1209 // FIXME: fix POSIX char class.
1210 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1211 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1212 implode("\n", $lines),
1214 return array(array(''), array(''));
1216 return array($m[0], $m[1]);
1220 $orig = new _HWLDF_WordAccumulator
;
1222 foreach ($this->edits
as $edit) {
1223 if ($edit->type
== 'copy')
1224 $orig->addWords($edit->orig
);
1225 elseif ($edit->orig
)
1226 $orig->addWords($edit->orig
, 'mark');
1228 return $orig->getLines();
1231 function closing () {
1232 $closing = new _HWLDF_WordAccumulator
;
1234 foreach ($this->edits
as $edit) {
1235 if ($edit->type
== 'copy')
1236 $closing->addWords($edit->closing
);
1237 elseif ($edit->closing
)
1238 $closing->addWords($edit->closing
, 'mark');
1240 return $closing->getLines();
1245 * Wikipedia Table style diff formatter.
1248 class TableDiffFormatter
extends DiffFormatter
1250 function TableDiffFormatter() {
1251 $this->leading_context_lines
= 2;
1252 $this->trailing_context_lines
= 2;
1255 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1256 $l1 = wfMsg( 'lineno', $xbeg );
1257 $l2 = wfMsg( 'lineno', $ybeg );
1259 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1260 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1264 function _start_block( $header ) {
1266 $wgOut->addHTML( $header );
1269 function _end_block() {
1272 function _lines( $lines, $prefix=' ', $color='white' ) {
1275 function addedLine( $line ) {
1276 return '<td>+</td><td class="diff-addedline">' .
1280 function deletedLine( $line ) {
1281 return '<td>-</td><td class="diff-deletedline">' .
1285 function emptyLine() {
1286 return '<td colspan="2"> </td>';
1289 function contextLine( $line ) {
1290 return '<td> </td><td class="diff-context">'.$line.'</td>';
1293 function _added($lines) {
1295 foreach ($lines as $line) {
1296 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1297 $this->addedLine( $line ) . "</tr>\n" );
1301 function _deleted($lines) {
1303 foreach ($lines as $line) {
1304 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1305 $this->emptyLine() . "</tr>\n" );
1309 function _context( $lines ) {
1311 foreach ($lines as $line) {
1312 $wgOut->addHTML( '<tr>' . $this->contextLine( $line ) .
1313 $this->contextLine( $line ) . "</tr>\n" );
1317 function _changed( $orig, $closing ) {
1319 $diff = new WordLevelDiff( $orig, $closing );
1320 $del = $diff->orig();
1321 $add = $diff->closing();
1323 while ( $line = array_shift( $del ) ) {
1324 $aline = array_shift( $add );
1325 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1326 $this->addedLine( $aline ) . "</tr>\n" );
1328 $this->_added( $add ); # If any leftovers