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);
28 $dbr =& wfGetDB( DB_SLAVE
);
29 $this->mOldid
= $dbr->selectField( 'old', 'old_id',
30 "old_title='" . $wgTitle->getDBkey() . "'" .
31 ' AND old_namespace=' . $wgTitle->getNamespace() .
32 " AND old_id<{$this->mNewid} ORDER BY old_id DESC" );
34 } elseif ( 'next' == $new ) {
36 # Show diff between revision $old and the previous one.
37 # Get previous one from DB.
39 $this->mOldid
= intval($old);
40 $dbr =& wfGetDB( DB_SLAVE
);
41 $this->mNewid
= $dbr->selectField( 'old', 'old_id',
42 "old_title='" . $wgTitle->getDBkey() . "'" .
43 ' AND old_namespace=' . $wgTitle->getNamespace() .
44 " AND old_id>{$this->mOldid} ORDER BY old_id " );
45 if ( false === $this->mNewid
) {
46 # if no result, NewId points to the newest old revision. The only newer
47 # revision is cur, which is "0".
53 $this->mOldid
= intval($old);
54 $this->mNewid
= intval($new);
56 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
59 function showDiffPage()
61 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
62 $fname = 'DifferenceEngine::showDiffPage';
63 wfProfileIn( $fname );
65 # mOldid is false if the difference engine is called with a "vague" query for
66 # a diff between a version V and its previous version V' AND the version V
67 # is the first version of that article. In that case, V' does not exist.
68 if ( $this->mOldid
=== false ) {
69 $this->showFirstRevision();
70 wfProfileOut( $fname );
74 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
76 $mtext = wfMsg( 'missingarticle', $t );
78 $wgOut->setArticleFlag( false );
79 if ( ! $this->loadText() ) {
80 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
81 $wgOut->addHTML( $mtext );
82 wfProfileOut( $fname );
85 $wgOut->suppressQuickbar();
87 $oldTitle = $this->mOldPage
->getPrefixedText();
88 $newTitle = $this->mNewPage
->getPrefixedText();
89 if( $oldTitle == $newTitle ) {
90 $wgOut->setPageTitle( $newTitle );
92 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
94 $wgOut->setSubtitle( wfMsg( 'difference' ) );
95 $wgOut->setRobotpolicy( 'noindex,follow' );
97 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
100 wfProfileOut( $fname );
104 $sk = $wgUser->getSkin();
105 $talk = $wgLang->getNsText( NS_TALK
);
106 $contribs = wfMsg( 'contribslink' );
108 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
109 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
111 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
112 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
113 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
114 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
115 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
116 'target=' . urlencode($this->mOldUser
) );
117 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
118 'target=' . urlencode($this->mNewUser
) );
119 if ( !$this->mNewid
&& $wgUser->isSysop() ) {
120 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
121 'action=rollback&from=' . urlencode($this->mNewUser
) ) . ']</strong>';
125 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
126 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
128 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
129 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
134 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
135 if ( $this->mNewid
== 0 ) {
138 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
141 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
142 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
143 '<br />' . $prevlink;
144 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
145 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
146 '<br />' . $nextlink . $patrol;
148 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
149 $oldHeader, $newHeader );
150 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
151 $wgOut->addWikiText( $this->mNewtext
);
153 wfProfileOut( $fname );
156 # Show the first revision of an article. Uses normal diff headers in contrast to normal
157 # "old revision" display style.
159 function showFirstRevision()
161 global $wgOut, $wgTitle, $wgUser, $wgLang;
163 $fname = 'DifferenceEngine::showFirstRevision';
164 wfProfileIn( $fname );
167 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
169 # Get article text from the DB
171 if ( ! $this->loadText() ) {
172 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
174 $mtext = wfMsg( 'missingarticle', $t );
175 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
176 $wgOut->addHTML( $mtext );
177 wfProfileOut( $fname );
181 # Check if user is allowed to look at this page. If not, bail out.
183 if ( !( $this->mOldPage
->userCanRead() ) ) {
184 $wgOut->loginToUse();
186 wfProfileOut( $fname );
190 # Prepare the header box
192 $sk = $wgUser->getSkin();
194 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
195 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
196 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
197 'target=' . urlencode($this->mOldUser
) );
198 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
199 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
200 "($uTLink | $contribs)<br />" . $this->mOldComment
.
201 '<br />' . $nextlink. "</div>\n";
203 $wgOut->addHTML( $header );
205 $wgOut->setSubtitle( wfMsg( 'difference' ) );
206 $wgOut->setRobotpolicy( 'noindex,follow' );
209 # Show current revision
211 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
212 $wgOut->addWikiText( $this->mNewtext
);
214 wfProfileOut( $fname );
217 function showDiff( $otext, $ntext, $otitle, $ntitle )
219 global $wgOut, $wgUseExternalDiffEngine;
222 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
224 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
225 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
229 if ( $wgUseExternalDiffEngine ) {
230 # For historical reasons, external diff engine expects
231 # input text to be HTML-escaped already
232 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
233 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
234 dl('php_wikidiff.so');
235 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
237 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
238 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
239 $diffs = new Diff( $ota, $nta );
240 $formatter = new TableDiffFormatter();
241 $formatter->format( $diffs );
243 $wgOut->addHTML( "</table>\n" );
246 # Load the text of the articles to compare. If newid is 0, then compare
247 # the old article in oldid to the current article; if oldid is 0, then
248 # compare the current article to the immediately previous one (ignoring
249 # the value of newid).
253 global $wgTitle, $wgOut, $wgLang;
254 $fname = 'DifferenceEngine::loadText';
256 $dbr =& wfGetDB( DB_SLAVE
);
257 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
258 $wgOut->setArticleFlag( true );
259 $newLink = $wgTitle->getLocalUrl();
260 $this->mPagetitle
= wfMsg( 'currentrev' );
261 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
262 $id = $wgTitle->getArticleID();
264 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
265 array( 'cur_id' => $id ), $fname );
266 if ( $s === false ) {
267 wfDebug( "Unable to load cur_id $id\n" );
271 $this->mNewPage
= &$wgTitle;
272 $this->mNewtext
= $s->cur_text
;
273 $this->mNewUser
= $s->cur_user_text
;
274 $this->mNewComment
= $s->cur_comment
;
276 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
277 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
279 if ( $s === false ) {
280 wfDebug( "Unable to load old_id {$this->mNewid}\n" );
284 $this->mNewtext
= Article
::getRevisionText( $s );
286 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
287 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
288 $newLink = $wgTitle->getLocalUrl ('oldid=' . $this->mNewid
);
289 $this->mPagetitle
= wfMsg( 'revisionasof', $t );
290 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
291 $this->mNewUser
= $s->old_user_text
;
292 $this->mNewComment
= $s->old_comment
;
294 if ( 0 == $this->mOldid
) {
295 $s = $dbr->getArray( 'old',
296 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
298 'old_namespace' => $this->mNewPage
->getNamespace(),
299 'old_title' => $this->mNewPage
->getDBkey()
300 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
302 if ( $s === false ) {
303 wfDebug( 'Unable to load ' . $this->mNewPage
->getPrefixedDBkey
. " from old\n" );
307 $s = $dbr->getArray( 'old',
308 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
309 array( 'old_id' => $this->mOldid
),
312 if ( $s === false ) {
313 wfDebug( "Unable to load old_id {$this->mOldid}\n" );
317 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
318 $this->mOldtext
= Article
::getRevisionText( $s );
320 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
321 $oldLink = $this->mOldPage
->getLocalUrl ('oldid=' . $this->mOldid
);
322 $this->mOldtitle
= "<a href='$oldLink'>" . wfMsg( 'revisionasof', $t ) . '</a>';
323 $this->mOldUser
= $s->old_user_text
;
324 $this->mOldComment
= $s->old_comment
;
330 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
332 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
333 // You may copy this code freely under the conditions of the GPL.
336 define('USE_ASSERTS', function_exists('assert'));
348 trigger_error('pure virtual', E_USER_ERROR
);
352 return $this->orig ?
sizeof($this->orig
) : 0;
355 function nclosing() {
356 return $this->closing ?
sizeof($this->closing
) : 0;
364 class _DiffOp_Copy
extends _DiffOp
{
367 function _DiffOp_Copy ($orig, $closing = false) {
368 if (!is_array($closing))
371 $this->closing
= $closing;
375 return new _DiffOp_Copy($this->closing
, $this->orig
);
383 class _DiffOp_Delete
extends _DiffOp
{
384 var $type = 'delete';
386 function _DiffOp_Delete ($lines) {
387 $this->orig
= $lines;
388 $this->closing
= false;
392 return new _DiffOp_Add($this->orig
);
400 class _DiffOp_Add
extends _DiffOp
{
403 function _DiffOp_Add ($lines) {
404 $this->closing
= $lines;
409 return new _DiffOp_Delete($this->closing
);
417 class _DiffOp_Change
extends _DiffOp
{
418 var $type = 'change';
420 function _DiffOp_Change ($orig, $closing) {
422 $this->closing
= $closing;
426 return new _DiffOp_Change($this->closing
, $this->orig
);
432 * Class used internally by Diff to actually compute the diffs.
434 * The algorithm used here is mostly lifted from the perl module
435 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
436 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
438 * More ideas are taken from:
439 * http://www.ics.uci.edu/~eppstein/161/960229.html
441 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
442 * diffutils-2.7, which can be found at:
443 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
445 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
448 * @author Geoffrey T. Dairiki
454 function diff ($from_lines, $to_lines) {
455 $n_from = sizeof($from_lines);
456 $n_to = sizeof($to_lines);
458 $this->xchanged
= $this->ychanged
= array();
459 $this->xv
= $this->yv
= array();
460 $this->xind
= $this->yind
= array();
462 unset($this->in_seq
);
465 // Skip leading common lines.
466 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
467 if ($from_lines[$skip] != $to_lines[$skip])
469 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
471 // Skip trailing common lines.
472 $xi = $n_from; $yi = $n_to;
473 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
474 if ($from_lines[$xi] != $to_lines[$yi])
476 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
479 // Ignore lines which do not exist in both files.
480 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
481 $xhash[$from_lines[$xi]] = 1;
482 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
483 $line = $to_lines[$yi];
484 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
490 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
491 $line = $from_lines[$xi];
492 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
499 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
501 // Merge edits when possible
502 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
503 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
505 // Compute the edit operations.
508 while ($xi < $n_from ||
$yi < $n_to) {
509 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
510 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
512 // Skip matching "snake".
514 while ( $xi < $n_from && $yi < $n_to
515 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
516 $copy[] = $from_lines[$xi++
];
520 $edits[] = new _DiffOp_Copy($copy);
522 // Find deletes & adds.
524 while ($xi < $n_from && $this->xchanged
[$xi])
525 $delete[] = $from_lines[$xi++
];
528 while ($yi < $n_to && $this->ychanged
[$yi])
529 $add[] = $to_lines[$yi++
];
532 $edits[] = new _DiffOp_Change($delete, $add);
534 $edits[] = new _DiffOp_Delete($delete);
536 $edits[] = new _DiffOp_Add($add);
542 /* Divide the Largest Common Subsequence (LCS) of the sequences
543 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
546 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
547 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
548 * sub sequences. The first sub-sequence is contained in [X0, X1),
549 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
550 * that (X0, Y0) == (XOFF, YOFF) and
551 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
553 * This function assumes that the first lines of the specified portions
554 * of the two files do not match, and likewise that the last lines do not
555 * match. The caller must trim matching lines from the beginning and end
556 * of the portions it is going to specify.
558 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
561 if ($xlim - $xoff > $ylim - $yoff) {
562 // Things seems faster (I'm not sure I understand why)
563 // when the shortest sequence in X.
565 list ($xoff, $xlim, $yoff, $ylim)
566 = array( $yoff, $ylim, $xoff, $xlim);
570 for ($i = $ylim - 1; $i >= $yoff; $i--)
571 $ymatches[$this->xv
[$i]][] = $i;
573 for ($i = $ylim - 1; $i >= $yoff; $i--)
574 $ymatches[$this->yv
[$i]][] = $i;
577 $this->seq
[0]= $yoff - 1;
578 $this->in_seq
= array();
581 $numer = $xlim - $xoff +
$nchunks - 1;
583 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
585 for ($i = 0; $i <= $this->lcs
; $i++
)
586 $ymids[$i][$chunk-1] = $this->seq
[$i];
588 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
589 for ( ; $x < $x1; $x++
) {
590 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
591 if (empty($ymatches[$line]))
593 $matches = $ymatches[$line];
595 while (list ($junk, $y) = each($matches))
596 if (empty($this->in_seq
[$y])) {
597 $k = $this->_lcs_pos($y);
598 USE_ASSERTS
&& assert($k > 0);
599 $ymids[$k] = $ymids[$k-1];
602 while (list ($junk, $y) = each($matches)) {
603 if ($y > $this->seq
[$k-1]) {
604 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
605 // Optimization: this is a common case:
606 // next match is just replacing previous match.
607 $this->in_seq
[$this->seq
[$k]] = false;
609 $this->in_seq
[$y] = 1;
611 else if (empty($this->in_seq
[$y])) {
612 $k = $this->_lcs_pos($y);
613 USE_ASSERTS
&& assert($k > 0);
614 $ymids[$k] = $ymids[$k-1];
620 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
621 $ymid = $ymids[$this->lcs
];
622 for ($n = 0; $n < $nchunks - 1; $n++
) {
623 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
625 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
627 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
629 return array($this->lcs
, $seps);
632 function _lcs_pos ($ypos) {
634 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
635 $this->seq
[++
$this->lcs
] = $ypos;
636 $this->in_seq
[$ypos] = 1;
641 while ($beg < $end) {
642 $mid = (int)(($beg +
$end) / 2);
643 if ( $ypos > $this->seq
[$mid] )
649 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
651 $this->in_seq
[$this->seq
[$end]] = false;
652 $this->seq
[$end] = $ypos;
653 $this->in_seq
[$ypos] = 1;
657 /* Find LCS of two sequences.
659 * The results are recorded in the vectors $this->{x,y}changed[], by
660 * storing a 1 in the element for each line that is an insertion
661 * or deletion (ie. is not in the LCS).
663 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
665 * Note that XLIM, YLIM are exclusive bounds.
666 * All line numbers are origin-0 and discarded lines are not counted.
668 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
669 // Slide down the bottom initial diagonal.
670 while ($xoff < $xlim && $yoff < $ylim
671 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
676 // Slide up the top initial diagonal.
677 while ($xlim > $xoff && $ylim > $yoff
678 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
683 if ($xoff == $xlim ||
$yoff == $ylim)
686 // This is ad hoc but seems to work well.
687 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
688 //$nchunks = max(2,min(8,(int)$nchunks));
689 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
691 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
695 // X and Y sequences have no common subsequence:
697 while ($yoff < $ylim)
698 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
699 while ($xoff < $xlim)
700 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
703 // Use the partitions to split this problem into subproblems.
706 while ($pt2 = next($seps)) {
707 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
713 /* Adjust inserts/deletes of identical lines to join changes
714 * as much as possible.
716 * We do something when a run of changed lines include a
717 * line at one end and has an excluded, identical line at the other.
718 * We are free to choose which identical line is included.
719 * `compareseq' usually chooses the one at the beginning,
720 * but usually it is cleaner to consider the following identical line
721 * to be the "change".
723 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
725 function _shift_boundaries ($lines, &$changed, $other_changed) {
729 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
730 $len = sizeof($lines);
731 $other_len = sizeof($other_changed);
735 * Scan forwards to find beginning of another run of changes.
736 * Also keep track of the corresponding point in the other file.
738 * Throughout this code, $i and $j are adjusted together so that
739 * the first $i elements of $changed and the first $j elements
740 * of $other_changed both contain the same number of zeros
742 * Furthermore, $j is always kept so that $j == $other_len or
743 * $other_changed[$j] == false.
745 while ($j < $other_len && $other_changed[$j])
748 while ($i < $len && ! $changed[$i]) {
749 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
751 while ($j < $other_len && $other_changed[$j])
760 // Find the end of this run of changes.
761 while (++
$i < $len && $changed[$i])
766 * Record the length of this run of changes, so that
767 * we can later determine whether the run has grown.
769 $runlength = $i - $start;
772 * Move the changed region back, so long as the
773 * previous unchanged line matches the last changed one.
774 * This merges with previous changed regions.
776 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
777 $changed[--$start] = 1;
778 $changed[--$i] = false;
779 while ($start > 0 && $changed[$start - 1])
781 USE_ASSERTS
&& assert('$j > 0');
782 while ($other_changed[--$j])
784 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
788 * Set CORRESPONDING to the end of the changed run, at the last
789 * point where it corresponds to a changed run in the other file.
790 * CORRESPONDING == LEN means no such point has been found.
792 $corresponding = $j < $other_len ?
$i : $len;
795 * Move the changed region forward, so long as the
796 * first changed line matches the following unchanged one.
797 * This merges with following changed regions.
798 * Do this second, so that if there are no merges,
799 * the changed region is moved forward as far as possible.
801 while ($i < $len && $lines[$start] == $lines[$i]) {
802 $changed[$start++
] = false;
804 while ($i < $len && $changed[$i])
807 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
809 if ($j < $other_len && $other_changed[$j]) {
811 while ($j < $other_len && $other_changed[$j])
815 } while ($runlength != $i - $start);
818 * If possible, move the fully-merged run of changes
819 * back to a corresponding run in the other file.
821 while ($corresponding < $i) {
822 $changed[--$start] = 1;
824 USE_ASSERTS
&& assert('$j > 0');
825 while ($other_changed[--$j])
827 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
834 * Class representing a 'diff' between two sequences of strings.
844 * Computes diff between sequences of strings.
846 * @param $from_lines array An array of strings.
847 * (Typically these are lines from a file.)
848 * @param $to_lines array An array of strings.
850 function Diff($from_lines, $to_lines) {
851 $eng = new _DiffEngine
;
852 $this->edits
= $eng->diff($from_lines, $to_lines);
853 //$this->_check($from_lines, $to_lines);
857 * Compute reversed Diff.
861 * $diff = new Diff($lines1, $lines2);
862 * $rev = $diff->reverse();
863 * @return object A Diff object representing the inverse of the
866 function reverse () {
868 $rev->edits
= array();
869 foreach ($this->edits
as $edit) {
870 $rev->edits
[] = $edit->reverse();
876 * Check for empty diff.
878 * @return bool True iff two sequences were identical.
880 function isEmpty () {
881 foreach ($this->edits
as $edit) {
882 if ($edit->type
!= 'copy')
889 * Compute the length of the Longest Common Subsequence (LCS).
891 * This is mostly for diagnostic purposed.
893 * @return int The length of the LCS.
897 foreach ($this->edits
as $edit) {
898 if ($edit->type
== 'copy')
899 $lcs +
= sizeof($edit->orig
);
905 * Get the original set of lines.
907 * This reconstructs the $from_lines parameter passed to the
910 * @return array The original sequence of strings.
915 foreach ($this->edits
as $edit) {
917 array_splice($lines, sizeof($lines), 0, $edit->orig
);
923 * Get the closing set of lines.
925 * This reconstructs the $to_lines parameter passed to the
928 * @return array The sequence of strings.
933 foreach ($this->edits
as $edit) {
935 array_splice($lines, sizeof($lines), 0, $edit->closing
);
941 * Check a Diff for validity.
943 * This is here only for debugging purposes.
945 function _check ($from_lines, $to_lines) {
946 if (serialize($from_lines) != serialize($this->orig()))
947 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
948 if (serialize($to_lines) != serialize($this->closing()))
949 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
951 $rev = $this->reverse();
952 if (serialize($to_lines) != serialize($rev->orig()))
953 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
954 if (serialize($from_lines) != serialize($rev->closing()))
955 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
959 foreach ($this->edits
as $edit) {
960 if ( $prevtype == $edit->type
)
961 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
962 $prevtype = $edit->type
;
966 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
975 class MappedDiff
extends Diff
980 * Computes diff between sequences of strings.
982 * This can be used to compute things like
983 * case-insensitve diffs, or diffs which ignore
984 * changes in white-space.
986 * @param $from_lines array An array of strings.
987 * (Typically these are lines from a file.)
989 * @param $to_lines array An array of strings.
991 * @param $mapped_from_lines array This array should
992 * have the same size number of elements as $from_lines.
993 * The elements in $mapped_from_lines and
994 * $mapped_to_lines are what is actually compared
995 * when computing the diff.
997 * @param $mapped_to_lines array This array should
998 * have the same number of elements as $to_lines.
1000 function MappedDiff($from_lines, $to_lines,
1001 $mapped_from_lines, $mapped_to_lines) {
1003 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1004 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1006 $this->Diff($mapped_from_lines, $mapped_to_lines);
1009 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1010 $orig = &$this->edits
[$i]->orig
;
1011 if (is_array($orig)) {
1012 $orig = array_slice($from_lines, $xi, sizeof($orig));
1013 $xi +
= sizeof($orig);
1016 $closing = &$this->edits
[$i]->closing
;
1017 if (is_array($closing)) {
1018 $closing = array_slice($to_lines, $yi, sizeof($closing));
1019 $yi +
= sizeof($closing);
1026 * A class to format Diffs
1028 * This class formats the diff in classic diff format.
1029 * It is intended that this class be customized via inheritance,
1030 * to obtain fancier outputs.
1032 * @package MediaWiki
1037 * Number of leading context "lines" to preserve.
1039 * This should be left at zero for this class, but subclasses
1040 * may want to set this to other values.
1042 var $leading_context_lines = 0;
1045 * Number of trailing context "lines" to preserve.
1047 * This should be left at zero for this class, but subclasses
1048 * may want to set this to other values.
1050 var $trailing_context_lines = 0;
1055 * @param $diff object A Diff object.
1056 * @return string The formatted output.
1058 function format($diff) {
1064 $nlead = $this->leading_context_lines
;
1065 $ntrail = $this->trailing_context_lines
;
1067 $this->_start_diff();
1069 foreach ($diff->edits
as $edit) {
1070 if ($edit->type
== 'copy') {
1071 if (is_array($block)) {
1072 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1077 $context = array_slice($edit->orig
, 0, $ntrail);
1078 $block[] = new _DiffOp_Copy($context);
1080 $this->_block($x0, $ntrail +
$xi - $x0,
1081 $y0, $ntrail +
$yi - $y0,
1086 $context = $edit->orig
;
1089 if (! is_array($block)) {
1090 $context = array_slice($context, sizeof($context) - $nlead);
1091 $x0 = $xi - sizeof($context);
1092 $y0 = $yi - sizeof($context);
1095 $block[] = new _DiffOp_Copy($context);
1101 $xi +
= sizeof($edit->orig
);
1103 $yi +
= sizeof($edit->closing
);
1106 if (is_array($block))
1107 $this->_block($x0, $xi - $x0,
1111 return $this->_end_diff();
1114 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1115 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1116 foreach ($edits as $edit) {
1117 if ($edit->type
== 'copy')
1118 $this->_context($edit->orig
);
1119 elseif ($edit->type
== 'add')
1120 $this->_added($edit->closing
);
1121 elseif ($edit->type
== 'delete')
1122 $this->_deleted($edit->orig
);
1123 elseif ($edit->type
== 'change')
1124 $this->_changed($edit->orig
, $edit->closing
);
1126 trigger_error('Unknown edit type', E_USER_ERROR
);
1128 $this->_end_block();
1131 function _start_diff() {
1135 function _end_diff() {
1136 $val = ob_get_contents();
1141 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1143 $xbeg .= "," . ($xbeg +
$xlen - 1);
1145 $ybeg .= "," . ($ybeg +
$ylen - 1);
1147 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1150 function _start_block($header) {
1154 function _end_block() {
1157 function _lines($lines, $prefix = ' ') {
1158 foreach ($lines as $line)
1159 echo "$prefix $line\n";
1162 function _context($lines) {
1163 $this->_lines($lines);
1166 function _added($lines) {
1167 $this->_lines($lines, '>');
1169 function _deleted($lines) {
1170 $this->_lines($lines, '<');
1173 function _changed($orig, $closing) {
1174 $this->_deleted($orig);
1176 $this->_added($closing);
1182 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1186 define('NBSP', ' '); // iso-8859-x non-breaking space.
1190 * @package MediaWiki
1192 class _HWLDF_WordAccumulator
{
1193 function _HWLDF_WordAccumulator () {
1194 $this->_lines
= array();
1200 function _flushGroup ($new_tag) {
1201 if ($this->_group
!== '') {
1202 if ($this->_tag
== 'mark')
1203 $this->_line
.= '<span class="diffchange">' .
1204 htmlspecialchars ( $this->_group
) . '</span>';
1206 $this->_line
.= htmlspecialchars ( $this->_group
);
1209 $this->_tag
= $new_tag;
1212 function _flushLine ($new_tag) {
1213 $this->_flushGroup($new_tag);
1214 if ($this->_line
!= '')
1215 array_push ( $this->_lines
, $this->_line
);
1217 # make empty lines visible by inserting an NBSP
1218 array_push ( $this->_lines
, NBSP
);
1222 function addWords ($words, $tag = '') {
1223 if ($tag != $this->_tag
)
1224 $this->_flushGroup($tag);
1226 foreach ($words as $word) {
1227 // new-line should only come as first char of word.
1230 if ($word[0] == "\n") {
1231 $this->_flushLine($tag);
1232 $word = substr($word, 1);
1234 assert(!strstr($word, "\n"));
1235 $this->_group
.= $word;
1239 function getLines() {
1240 $this->_flushLine('~done');
1241 return $this->_lines
;
1247 * @package MediaWiki
1249 class WordLevelDiff
extends MappedDiff
1251 function WordLevelDiff ($orig_lines, $closing_lines) {
1252 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1253 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1256 $this->MappedDiff($orig_words, $closing_words,
1257 $orig_stripped, $closing_stripped);
1260 function _split($lines) {
1261 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1262 implode("\n", $lines),
1264 return array(array(''), array(''));
1266 return array($m[0], $m[1]);
1270 $orig = new _HWLDF_WordAccumulator
;
1272 foreach ($this->edits
as $edit) {
1273 if ($edit->type
== 'copy')
1274 $orig->addWords($edit->orig
);
1275 elseif ($edit->orig
)
1276 $orig->addWords($edit->orig
, 'mark');
1278 return $orig->getLines();
1281 function closing () {
1282 $closing = new _HWLDF_WordAccumulator
;
1284 foreach ($this->edits
as $edit) {
1285 if ($edit->type
== 'copy')
1286 $closing->addWords($edit->closing
);
1287 elseif ($edit->closing
)
1288 $closing->addWords($edit->closing
, 'mark');
1290 return $closing->getLines();
1295 * Wikipedia Table style diff formatter.
1297 * @package MediaWiki
1299 class TableDiffFormatter
extends DiffFormatter
1301 function TableDiffFormatter() {
1302 $this->leading_context_lines
= 2;
1303 $this->trailing_context_lines
= 2;
1306 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1307 $l1 = wfMsg( 'lineno', $xbeg );
1308 $l2 = wfMsg( 'lineno', $ybeg );
1310 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1311 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1315 function _start_block( $header ) {
1317 $wgOut->addHTML( $header );
1320 function _end_block() {
1323 function _lines( $lines, $prefix=' ', $color='white' ) {
1326 # HTML-escape parameter before calling this
1327 function addedLine( $line ) {
1328 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1331 # HTML-escape parameter before calling this
1332 function deletedLine( $line ) {
1333 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1336 # HTML-escape parameter before calling this
1337 function contextLine( $line ) {
1338 return "<td> </td><td class='diff-context'>{$line}</td>";
1341 function emptyLine() {
1342 return '<td colspan="2"> </td>';
1345 function _added( $lines ) {
1347 foreach ($lines as $line) {
1348 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1349 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1353 function _deleted($lines) {
1355 foreach ($lines as $line) {
1356 $wgOut->addHTML( '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1357 $this->emptyLine() . "</tr>\n" );
1361 function _context( $lines ) {
1363 foreach ($lines as $line) {
1364 $wgOut->addHTML( '<tr>' .
1365 $this->contextLine( htmlspecialchars ( $line ) ) .
1366 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1370 function _changed( $orig, $closing ) {
1372 $diff = new WordLevelDiff( $orig, $closing );
1373 $del = $diff->orig();
1374 $add = $diff->closing();
1376 # Notice that WordLevelDiff returns HTML-escaped output.
1377 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1379 while ( $line = array_shift( $del ) ) {
1380 $aline = array_shift( $add );
1381 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1382 $this->addedLine( $aline ) . "</tr>\n" );
1384 foreach ($add as $line) { # If any leftovers
1385 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1386 $this->addedLine( $line ) . "</tr>\n" );