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 $this->mNewid
= intval($old);
18 $dbr =& wfGetDB( DB_SLAVE
);
19 $this->mOldid
= $dbr->selectField( 'old', 'old_id',
20 "old_title='" . $wgTitle->getDBkey() . "'" .
21 ' AND old_namespace=' . $wgTitle->getNamespace() .
22 " AND old_id<{$this->mNewid} order by old_id desc" );
25 $this->mOldid
= intval($old);
26 $this->mNewid
= intval($new);
28 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
31 function showDiffPage()
33 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
34 $fname = 'DifferenceEngine::showDiffPage';
35 wfProfileIn( $fname );
37 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
39 $mtext = wfMsg( 'missingarticle', $t );
41 $wgOut->setArticleFlag( false );
42 if ( ! $this->loadText() ) {
43 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
44 $wgOut->addHTML( $mtext );
45 wfProfileOut( $fname );
48 $wgOut->suppressQuickbar();
50 $oldTitle = $this->mOldPage
->getPrefixedText();
51 $newTitle = $this->mNewPage
->getPrefixedText();
52 if( $oldTitle == $newTitle ) {
53 $wgOut->setPageTitle( $newTitle );
55 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
57 $wgOut->setSubtitle( wfMsg( 'difference' ) );
58 $wgOut->setRobotpolicy( 'noindex,follow' );
60 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
63 wfProfileOut( $fname );
67 $sk = $wgUser->getSkin();
68 $talk = $wgLang->getNsText( NS_TALK
);
69 $contribs = wfMsg( 'contribslink' );
71 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
72 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
74 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
75 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
76 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
77 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
78 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
79 'target=' . urlencode($this->mOldUser
) );
80 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
81 'target=' . urlencode($this->mNewUser
) );
82 if ( !$this->mNewid
&& $wgUser->isSysop() ) {
83 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
84 'action=rollback&from=' . urlencode($this->mNewUser
) ) . ']</strong>';
88 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
89 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
91 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
92 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
97 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
98 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
;
99 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
100 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
. $patrol;
102 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
103 $oldHeader, $newHeader );
104 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
105 $wgOut->addWikiText( $this->mNewtext
);
107 wfProfileOut( $fname );
110 function showDiff( $otext, $ntext, $otitle, $ntitle )
112 global $wgOut, $wgUseExternalDiffEngine;
114 $otext = str_replace( "\r\n", "\n", $otext );
115 $ntext = str_replace( "\r\n", "\n", $ntext );
118 $wgOut->addHTML( "<table border='0' width='98%'
119 cellpadding='0' cellspacing='4px' class='diff'><tr>
120 <td colspan='2' width='50%' align='center' class='diff-otitle'>
122 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
125 if ( $wgUseExternalDiffEngine ) {
126 dl('php_wikidiff.so');
127 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
129 $ota = explode( "\n", $otext);
130 $nta = explode( "\n", $ntext);
131 $diffs = new Diff( $ota, $nta );
132 $formatter = new TableDiffFormatter();
133 $formatter->format( $diffs );
135 $wgOut->addHTML( "</table>\n" );
138 # Load the text of the articles to compare. If newid is 0, then compare
139 # the old article in oldid to the current article; if oldid is 0, then
140 # compare the current article to the immediately previous one (ignoring
141 # the value of newid).
145 global $wgTitle, $wgOut, $wgLang;
146 $fname = 'DifferenceEngine::loadText';
148 $dbr =& wfGetDB( DB_SLAVE
);
149 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
150 $wgOut->setArticleFlag( true );
151 $newLink = $wgTitle->getLocalUrl();
152 $this->mPagetitle
= wfMsg( 'currentrev' );
153 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
154 $id = $wgTitle->getArticleID();
156 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
157 array( 'cur_id' => $id ), $fname );
158 if ( $s === false ) {
162 $this->mNewPage
= &$wgTitle;
163 $this->mNewtext
= $s->cur_text
;
164 $this->mNewUser
= $s->cur_user_text
;
165 $this->mNewComment
= $s->cur_comment
;
167 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
168 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
170 if ( $s === false ) {
174 $this->mNewtext
= Article
::getRevisionText( $s );
176 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
177 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
178 $newLink = $wgTitle->getLocalUrl ('oldid=' . $this->mNewid
);
179 $this->mPagetitle
= wfMsg( 'revisionasof', $t );
180 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
181 $this->mNewUser
= $s->old_user_text
;
182 $this->mNewComment
= $s->old_comment
;
184 if ( 0 == $this->mOldid
) {
185 $s = $dbr->getArray( 'old',
186 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
188 'old_namespace' => $this->mNewPage
->getNamespace(),
189 'old_title' => $this->mNewPage
->getDBkey()
190 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
193 $s = $dbr->getArray( 'old',
194 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
195 array( 'old_id' => $this->mOldid
),
199 if ( $s === false ) {
202 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
203 $this->mOldtext
= Article
::getRevisionText( $s );
205 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
206 $oldLink = $this->mOldPage
->getLocalUrl ('oldid=' . $this->mOldid
);
207 $this->mOldtitle
= "<a href='$oldLink'>" . wfMsg( 'revisionasof', $t ) . '</a>';
208 $this->mOldUser
= $s->old_user_text
;
209 $this->mOldComment
= $s->old_comment
;
215 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
217 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
218 // You may copy this code freely under the conditions of the GPL.
221 define('USE_ASSERTS', function_exists('assert'));
229 trigger_error('pure virtual', E_USER_ERROR
);
233 return $this->orig ?
sizeof($this->orig
) : 0;
236 function nclosing() {
237 return $this->closing ?
sizeof($this->closing
) : 0;
241 class _DiffOp_Copy
extends _DiffOp
{
244 function _DiffOp_Copy ($orig, $closing = false) {
245 if (!is_array($closing))
248 $this->closing
= $closing;
252 return new _DiffOp_Copy($this->closing
, $this->orig
);
256 class _DiffOp_Delete
extends _DiffOp
{
257 var $type = 'delete';
259 function _DiffOp_Delete ($lines) {
260 $this->orig
= $lines;
261 $this->closing
= false;
265 return new _DiffOp_Add($this->orig
);
269 class _DiffOp_Add
extends _DiffOp
{
272 function _DiffOp_Add ($lines) {
273 $this->closing
= $lines;
278 return new _DiffOp_Delete($this->closing
);
282 class _DiffOp_Change
extends _DiffOp
{
283 var $type = 'change';
285 function _DiffOp_Change ($orig, $closing) {
287 $this->closing
= $closing;
291 return new _DiffOp_Change($this->closing
, $this->orig
);
297 * Class used internally by Diff to actually compute the diffs.
299 * The algorithm used here is mostly lifted from the perl module
300 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
301 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
303 * More ideas are taken from:
304 * http://www.ics.uci.edu/~eppstein/161/960229.html
306 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
307 * diffutils-2.7, which can be found at:
308 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
310 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
313 * @author Geoffrey T. Dairiki
318 function diff ($from_lines, $to_lines) {
319 $n_from = sizeof($from_lines);
320 $n_to = sizeof($to_lines);
322 $this->xchanged
= $this->ychanged
= array();
323 $this->xv
= $this->yv
= array();
324 $this->xind
= $this->yind
= array();
326 unset($this->in_seq
);
329 // Skip leading common lines.
330 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
331 if ($from_lines[$skip] != $to_lines[$skip])
333 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
335 // Skip trailing common lines.
336 $xi = $n_from; $yi = $n_to;
337 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
338 if ($from_lines[$xi] != $to_lines[$yi])
340 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
343 // Ignore lines which do not exist in both files.
344 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
345 $xhash[$from_lines[$xi]] = 1;
346 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
347 $line = $to_lines[$yi];
348 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
354 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
355 $line = $from_lines[$xi];
356 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
363 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
365 // Merge edits when possible
366 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
367 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
369 // Compute the edit operations.
372 while ($xi < $n_from ||
$yi < $n_to) {
373 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
374 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
376 // Skip matching "snake".
378 while ( $xi < $n_from && $yi < $n_to
379 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
380 $copy[] = $from_lines[$xi++
];
384 $edits[] = new _DiffOp_Copy($copy);
386 // Find deletes & adds.
388 while ($xi < $n_from && $this->xchanged
[$xi])
389 $delete[] = $from_lines[$xi++
];
392 while ($yi < $n_to && $this->ychanged
[$yi])
393 $add[] = $to_lines[$yi++
];
396 $edits[] = new _DiffOp_Change($delete, $add);
398 $edits[] = new _DiffOp_Delete($delete);
400 $edits[] = new _DiffOp_Add($add);
406 /* Divide the Largest Common Subsequence (LCS) of the sequences
407 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
410 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
411 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
412 * sub sequences. The first sub-sequence is contained in [X0, X1),
413 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
414 * that (X0, Y0) == (XOFF, YOFF) and
415 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
417 * This function assumes that the first lines of the specified portions
418 * of the two files do not match, and likewise that the last lines do not
419 * match. The caller must trim matching lines from the beginning and end
420 * of the portions it is going to specify.
422 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
425 if ($xlim - $xoff > $ylim - $yoff) {
426 // Things seems faster (I'm not sure I understand why)
427 // when the shortest sequence in X.
429 list ($xoff, $xlim, $yoff, $ylim)
430 = array( $yoff, $ylim, $xoff, $xlim);
434 for ($i = $ylim - 1; $i >= $yoff; $i--)
435 $ymatches[$this->xv
[$i]][] = $i;
437 for ($i = $ylim - 1; $i >= $yoff; $i--)
438 $ymatches[$this->yv
[$i]][] = $i;
441 $this->seq
[0]= $yoff - 1;
442 $this->in_seq
= array();
445 $numer = $xlim - $xoff +
$nchunks - 1;
447 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
449 for ($i = 0; $i <= $this->lcs
; $i++
)
450 $ymids[$i][$chunk-1] = $this->seq
[$i];
452 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
453 for ( ; $x < $x1; $x++
) {
454 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
455 if (empty($ymatches[$line]))
457 $matches = $ymatches[$line];
459 while (list ($junk, $y) = each($matches))
460 if (empty($this->in_seq
[$y])) {
461 $k = $this->_lcs_pos($y);
462 USE_ASSERTS
&& assert($k > 0);
463 $ymids[$k] = $ymids[$k-1];
466 while (list ($junk, $y) = each($matches)) {
467 if ($y > $this->seq
[$k-1]) {
468 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
469 // Optimization: this is a common case:
470 // next match is just replacing previous match.
471 $this->in_seq
[$this->seq
[$k]] = false;
473 $this->in_seq
[$y] = 1;
475 else if (empty($this->in_seq
[$y])) {
476 $k = $this->_lcs_pos($y);
477 USE_ASSERTS
&& assert($k > 0);
478 $ymids[$k] = $ymids[$k-1];
484 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
485 $ymid = $ymids[$this->lcs
];
486 for ($n = 0; $n < $nchunks - 1; $n++
) {
487 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
489 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
491 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
493 return array($this->lcs
, $seps);
496 function _lcs_pos ($ypos) {
498 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
499 $this->seq
[++
$this->lcs
] = $ypos;
500 $this->in_seq
[$ypos] = 1;
505 while ($beg < $end) {
506 $mid = (int)(($beg +
$end) / 2);
507 if ( $ypos > $this->seq
[$mid] )
513 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
515 $this->in_seq
[$this->seq
[$end]] = false;
516 $this->seq
[$end] = $ypos;
517 $this->in_seq
[$ypos] = 1;
521 /* Find LCS of two sequences.
523 * The results are recorded in the vectors $this->{x,y}changed[], by
524 * storing a 1 in the element for each line that is an insertion
525 * or deletion (ie. is not in the LCS).
527 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
529 * Note that XLIM, YLIM are exclusive bounds.
530 * All line numbers are origin-0 and discarded lines are not counted.
532 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
533 // Slide down the bottom initial diagonal.
534 while ($xoff < $xlim && $yoff < $ylim
535 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
540 // Slide up the top initial diagonal.
541 while ($xlim > $xoff && $ylim > $yoff
542 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
547 if ($xoff == $xlim ||
$yoff == $ylim)
550 // This is ad hoc but seems to work well.
551 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
552 //$nchunks = max(2,min(8,(int)$nchunks));
553 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
555 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
559 // X and Y sequences have no common subsequence:
561 while ($yoff < $ylim)
562 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
563 while ($xoff < $xlim)
564 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
567 // Use the partitions to split this problem into subproblems.
570 while ($pt2 = next($seps)) {
571 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
577 /* Adjust inserts/deletes of identical lines to join changes
578 * as much as possible.
580 * We do something when a run of changed lines include a
581 * line at one end and has an excluded, identical line at the other.
582 * We are free to choose which identical line is included.
583 * `compareseq' usually chooses the one at the beginning,
584 * but usually it is cleaner to consider the following identical line
585 * to be the "change".
587 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
589 function _shift_boundaries ($lines, &$changed, $other_changed) {
593 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
594 $len = sizeof($lines);
595 $other_len = sizeof($other_changed);
599 * Scan forwards to find beginning of another run of changes.
600 * Also keep track of the corresponding point in the other file.
602 * Throughout this code, $i and $j are adjusted together so that
603 * the first $i elements of $changed and the first $j elements
604 * of $other_changed both contain the same number of zeros
606 * Furthermore, $j is always kept so that $j == $other_len or
607 * $other_changed[$j] == false.
609 while ($j < $other_len && $other_changed[$j])
612 while ($i < $len && ! $changed[$i]) {
613 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
615 while ($j < $other_len && $other_changed[$j])
624 // Find the end of this run of changes.
625 while (++
$i < $len && $changed[$i])
630 * Record the length of this run of changes, so that
631 * we can later determine whether the run has grown.
633 $runlength = $i - $start;
636 * Move the changed region back, so long as the
637 * previous unchanged line matches the last changed one.
638 * This merges with previous changed regions.
640 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
641 $changed[--$start] = 1;
642 $changed[--$i] = false;
643 while ($start > 0 && $changed[$start - 1])
645 USE_ASSERTS
&& assert('$j > 0');
646 while ($other_changed[--$j])
648 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
652 * Set CORRESPONDING to the end of the changed run, at the last
653 * point where it corresponds to a changed run in the other file.
654 * CORRESPONDING == LEN means no such point has been found.
656 $corresponding = $j < $other_len ?
$i : $len;
659 * Move the changed region forward, so long as the
660 * first changed line matches the following unchanged one.
661 * This merges with following changed regions.
662 * Do this second, so that if there are no merges,
663 * the changed region is moved forward as far as possible.
665 while ($i < $len && $lines[$start] == $lines[$i]) {
666 $changed[$start++
] = false;
668 while ($i < $len && $changed[$i])
671 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
673 if ($j < $other_len && $other_changed[$j]) {
675 while ($j < $other_len && $other_changed[$j])
679 } while ($runlength != $i - $start);
682 * If possible, move the fully-merged run of changes
683 * back to a corresponding run in the other file.
685 while ($corresponding < $i) {
686 $changed[--$start] = 1;
688 USE_ASSERTS
&& assert('$j > 0');
689 while ($other_changed[--$j])
691 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
698 * Class representing a 'diff' between two sequences of strings.
706 * Computes diff between sequences of strings.
708 * @param $from_lines array An array of strings.
709 * (Typically these are lines from a file.)
710 * @param $to_lines array An array of strings.
712 function Diff($from_lines, $to_lines) {
713 $eng = new _DiffEngine
;
714 $this->edits
= $eng->diff($from_lines, $to_lines);
715 //$this->_check($from_lines, $to_lines);
719 * Compute reversed Diff.
723 * $diff = new Diff($lines1, $lines2);
724 * $rev = $diff->reverse();
725 * @return object A Diff object representing the inverse of the
728 function reverse () {
730 $rev->edits
= array();
731 foreach ($this->edits
as $edit) {
732 $rev->edits
[] = $edit->reverse();
738 * Check for empty diff.
740 * @return bool True iff two sequences were identical.
742 function isEmpty () {
743 foreach ($this->edits
as $edit) {
744 if ($edit->type
!= 'copy')
751 * Compute the length of the Longest Common Subsequence (LCS).
753 * This is mostly for diagnostic purposed.
755 * @return int The length of the LCS.
759 foreach ($this->edits
as $edit) {
760 if ($edit->type
== 'copy')
761 $lcs +
= sizeof($edit->orig
);
767 * Get the original set of lines.
769 * This reconstructs the $from_lines parameter passed to the
772 * @return array The original sequence of strings.
777 foreach ($this->edits
as $edit) {
779 array_splice($lines, sizeof($lines), 0, $edit->orig
);
785 * Get the closing set of lines.
787 * This reconstructs the $to_lines parameter passed to the
790 * @return array The sequence of strings.
795 foreach ($this->edits
as $edit) {
797 array_splice($lines, sizeof($lines), 0, $edit->closing
);
803 * Check a Diff for validity.
805 * This is here only for debugging purposes.
807 function _check ($from_lines, $to_lines) {
808 if (serialize($from_lines) != serialize($this->orig()))
809 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
810 if (serialize($to_lines) != serialize($this->closing()))
811 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
813 $rev = $this->reverse();
814 if (serialize($to_lines) != serialize($rev->orig()))
815 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
816 if (serialize($from_lines) != serialize($rev->closing()))
817 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
821 foreach ($this->edits
as $edit) {
822 if ( $prevtype == $edit->type
)
823 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
824 $prevtype = $edit->type
;
828 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
841 * Computes diff between sequences of strings.
843 * This can be used to compute things like
844 * case-insensitve diffs, or diffs which ignore
845 * changes in white-space.
847 * @param $from_lines array An array of strings.
848 * (Typically these are lines from a file.)
850 * @param $to_lines array An array of strings.
852 * @param $mapped_from_lines array This array should
853 * have the same size number of elements as $from_lines.
854 * The elements in $mapped_from_lines and
855 * $mapped_to_lines are what is actually compared
856 * when computing the diff.
858 * @param $mapped_to_lines array This array should
859 * have the same number of elements as $to_lines.
861 function MappedDiff($from_lines, $to_lines,
862 $mapped_from_lines, $mapped_to_lines) {
864 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
865 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
867 $this->Diff($mapped_from_lines, $mapped_to_lines);
870 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
871 $orig = &$this->edits
[$i]->orig
;
872 if (is_array($orig)) {
873 $orig = array_slice($from_lines, $xi, sizeof($orig));
874 $xi +
= sizeof($orig);
877 $closing = &$this->edits
[$i]->closing
;
878 if (is_array($closing)) {
879 $closing = array_slice($to_lines, $yi, sizeof($closing));
880 $yi +
= sizeof($closing);
887 * A class to format Diffs
889 * This class formats the diff in classic diff format.
890 * It is intended that this class be customized via inheritance,
891 * to obtain fancier outputs.
896 * Number of leading context "lines" to preserve.
898 * This should be left at zero for this class, but subclasses
899 * may want to set this to other values.
901 var $leading_context_lines = 0;
904 * Number of trailing context "lines" to preserve.
906 * This should be left at zero for this class, but subclasses
907 * may want to set this to other values.
909 var $trailing_context_lines = 0;
914 * @param $diff object A Diff object.
915 * @return string The formatted output.
917 function format($diff) {
923 $nlead = $this->leading_context_lines
;
924 $ntrail = $this->trailing_context_lines
;
926 $this->_start_diff();
928 foreach ($diff->edits
as $edit) {
929 if ($edit->type
== 'copy') {
930 if (is_array($block)) {
931 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
936 $context = array_slice($edit->orig
, 0, $ntrail);
937 $block[] = new _DiffOp_Copy($context);
939 $this->_block($x0, $ntrail +
$xi - $x0,
940 $y0, $ntrail +
$yi - $y0,
945 $context = $edit->orig
;
948 if (! is_array($block)) {
949 $context = array_slice($context, sizeof($context) - $nlead);
950 $x0 = $xi - sizeof($context);
951 $y0 = $yi - sizeof($context);
954 $block[] = new _DiffOp_Copy($context);
960 $xi +
= sizeof($edit->orig
);
962 $yi +
= sizeof($edit->closing
);
965 if (is_array($block))
966 $this->_block($x0, $xi - $x0,
970 return $this->_end_diff();
973 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
974 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
975 foreach ($edits as $edit) {
976 if ($edit->type
== 'copy')
977 $this->_context($edit->orig
);
978 elseif ($edit->type
== 'add')
979 $this->_added($edit->closing
);
980 elseif ($edit->type
== 'delete')
981 $this->_deleted($edit->orig
);
982 elseif ($edit->type
== 'change')
983 $this->_changed($edit->orig
, $edit->closing
);
985 trigger_error('Unknown edit type', E_USER_ERROR
);
990 function _start_diff() {
994 function _end_diff() {
995 $val = ob_get_contents();
1000 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1002 $xbeg .= "," . ($xbeg +
$xlen - 1);
1004 $ybeg .= "," . ($ybeg +
$ylen - 1);
1006 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1009 function _start_block($header) {
1013 function _end_block() {
1016 function _lines($lines, $prefix = ' ') {
1017 foreach ($lines as $line)
1018 echo "$prefix $line\n";
1021 function _context($lines) {
1022 $this->_lines($lines);
1025 function _added($lines) {
1026 $this->_lines($lines, '>');
1028 function _deleted($lines) {
1029 $this->_lines($lines, '<');
1032 function _changed($orig, $closing) {
1033 $this->_deleted($orig);
1035 $this->_added($closing);
1041 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1045 define('NBSP', ' '); // iso-8859-x non-breaking space.
1047 class _HWLDF_WordAccumulator
{
1048 function _HWLDF_WordAccumulator () {
1049 $this->_lines
= array();
1055 function _flushGroup ($new_tag) {
1056 if ($this->_group
!== '') {
1057 if ($this->_tag
== 'mark')
1058 $this->_line
.= '<span class="diffchange">'.htmlspecialchars ( $this->_group
).'</span>';
1060 $this->_line
.= htmlspecialchars ( $this->_group
);
1063 $this->_tag
= $new_tag;
1066 function _flushLine ($new_tag) {
1067 $this->_flushGroup($new_tag);
1068 if ($this->_line
!= '')
1069 array_push ( $this->_lines
, $this->_line
);
1071 array_push ( $this->_lines
, NBSP
);
1075 function addWords ($words, $tag = '') {
1076 if ($tag != $this->_tag
)
1077 $this->_flushGroup($tag);
1079 foreach ($words as $word) {
1080 // new-line should only come as first char of word.
1083 if ($word[0] == "\n") {
1084 $this->_flushLine($tag);
1085 $word = substr($word, 1);
1087 assert(!strstr($word, "\n"));
1088 $this->_group
.= $word;
1092 function getLines() {
1093 $this->_flushLine('~done');
1094 return $this->_lines
;
1098 class WordLevelDiff
extends MappedDiff
1100 function WordLevelDiff ($orig_lines, $closing_lines) {
1101 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1102 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1105 $this->MappedDiff($orig_words, $closing_words,
1106 $orig_stripped, $closing_stripped);
1109 function _split($lines) {
1110 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1111 implode("\n", $lines),
1113 return array(array(''), array(''));
1115 return array($m[0], $m[1]);
1119 $orig = new _HWLDF_WordAccumulator
;
1121 foreach ($this->edits
as $edit) {
1122 if ($edit->type
== 'copy')
1123 $orig->addWords($edit->orig
);
1124 elseif ($edit->orig
)
1125 $orig->addWords($edit->orig
, 'mark');
1127 return $orig->getLines();
1130 function closing () {
1131 $closing = new _HWLDF_WordAccumulator
;
1133 foreach ($this->edits
as $edit) {
1134 if ($edit->type
== 'copy')
1135 $closing->addWords($edit->closing
);
1136 elseif ($edit->closing
)
1137 $closing->addWords($edit->closing
, 'mark');
1139 return $closing->getLines();
1144 * Wikipedia Table style diff formatter.
1147 class TableDiffFormatter
extends DiffFormatter
1149 function TableDiffFormatter() {
1150 $this->leading_context_lines
= 2;
1151 $this->trailing_context_lines
= 2;
1154 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1155 $l1 = wfMsg( 'lineno', $xbeg );
1156 $l2 = wfMsg( 'lineno', $ybeg );
1158 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1159 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1163 function _start_block( $header ) {
1165 $wgOut->addHTML( $header );
1168 function _end_block() {
1171 function _lines( $lines, $prefix=' ', $color='white' ) {
1174 function addedLine( $line ) {
1175 return '<td>+</td><td class="diff-addedline">' .
1179 function deletedLine( $line ) {
1180 return '<td>-</td><td class="diff-deletedline">' .
1184 function emptyLine() {
1185 return '<td colspan="2"> </td>';
1188 function contextLine( $line ) {
1189 return '<td> </td><td class="diff-context">' .
1190 htmlspecialchars ( $line ) . '</td>';
1193 function _added($lines) {
1195 foreach ($lines as $line) {
1196 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1197 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1201 function _deleted($lines) {
1203 foreach ($lines as $line) {
1204 $wgOut->addHTML( '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1205 $this->emptyLine() . "</tr>\n" );
1209 function _context( $lines ) {
1211 foreach ($lines as $line) {
1212 $wgOut->addHTML( '<tr>' . $this->contextLine( $line ) .
1213 $this->contextLine( $line ) . "</tr>\n" );
1217 function _changed( $orig, $closing ) {
1219 $diff = new WordLevelDiff( $orig, $closing );
1220 $del = $diff->orig();
1221 $add = $diff->closing();
1223 while ( $line = array_shift( $del ) ) {
1224 $aline = array_shift( $add );
1225 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1226 $this->addedLine( $aline ) . "</tr>\n" );
1228 $this->_added( $add ); # If any leftovers