4 class DifferenceEngine
{
5 /* private */ var $mOldid, $mNewid;
6 /* private */ var $mOldtitle, $mNewtitle;
7 /* private */ var $mOldtext, $mNewtext;
8 /* private */ var $mOldUser, $mNewUser;
9 /* private */ var $mOldComment, $mNewComment;
10 /* private */ var $mOldPage, $mNewPage;
12 function DifferenceEngine( $old, $new )
18 function showDiffPage()
20 global $wgUser, $wgTitle, $wgOut, $wgLang;
21 $fname = "DifferenceEngine::showDiffPage";
22 wfProfileIn( $fname );
24 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
26 $mtext = wfMsg( "missingarticle", $t );
28 $wgOut->setArticleFlag( false );
29 if ( ! $this->loadText() ) {
30 $wgOut->setPagetitle( wfMsg( "errorpagetitle" ) );
31 $wgOut->addHTML( $mtext );
32 wfProfileOut( $fname );
35 $wgOut->suppressQuickbar();
37 $oldTitle = $this->mOldPage
->getPrefixedText();
38 $newTitle = $this->mNewPage
->getPrefixedText();
39 if( $oldTitle == $newTitle ) {
40 $wgOut->setPageTitle( $newTitle );
42 $wgOut->setPageTitle( $oldTitle . ", " . $newTitle );
44 $wgOut->setSubtitle( wfMsg( "difference" ) );
45 $wgOut->setRobotpolicy( "noindex,follow" );
47 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
50 wfProfileOut( $fname );
54 $sk = $wgUser->getSkin();
55 $talk = $wgLang->getNsText( NS_TALK
);
56 $contribs = wfMsg( "contribslink" );
59 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
60 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
63 $oldUserLink = $sk->makeLinkObj( Title
::makeTitle( NS_USER
, $this->mOldUser
), $this->mOldUser
);
64 $newUserLink = $sk->makeLinkObj( Title
::makeTitle( NS_USER
, $this->mNewUser
), $this->mNewUser
);
65 $oldUTLink = $sk->makeLinkObj( Title
::makeTitle( NS_USER_TALK
, $this->mOldUser
), $talk );
66 $newUTLink = $sk->makeLinkObj( Title
::makeTitle( NS_USER_TALK
, $this->mNewUser
), $talk );
67 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, "Contributions" ), $contribs,
68 "target=" . urlencode($this->mOldUser
) );
69 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, "Contributions" ), $contribs,
70 "target=" . urlencode($this->mNewUser
) );
71 if ( !$this->mNewid
&& $wgUser->isSysop() ) {
72 $rollback = " <strong>[" . $sk->makeKnownLinkObj( $wgTitle, wfMsg( "rollbacklink" ),
73 "action=rollback&from=" . urlencode($this->mNewUser
) ) . "]</strong>";
78 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink ($oldUTLink | $oldContribs)<br />".
80 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink ($newUTLink | $newContribs) $rollback<br />".
83 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
84 $oldHeader, $newHeader );
85 $wgOut->addHTML( "<hr /><h2>{$this->mNewtitle}</h2>\n" );
86 $wgOut->addWikiText( $this->mNewtext
);
88 wfProfileOut( $fname );
91 function showDiff( $otext, $ntext, $otitle, $ntitle )
95 $ota = explode( "\n", str_replace( "\r\n", "\n",
96 htmlspecialchars( $otext ) ) );
97 $nta = explode( "\n", str_replace( "\r\n", "\n",
98 htmlspecialchars( $ntext ) ) );
100 $wgOut->addHTML( "<table border='0' width='98%'
101 cellpadding='0' cellspacing='4px' class='diff'><tr>
102 <td colspan='2' width='50%' align='center' class='diff-otitle'>
104 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
108 $diffs = new Diff( $ota, $nta );
109 $formatter = new TableDiffFormatter();
110 $formatter->format( $diffs );
111 $wgOut->addHTML( "</table>\n" );
114 # Load the text of the articles to compare. If newid is 0, then compare
115 # the old article in oldid to the current article; if oldid is 0, then
116 # compare the current article to the immediately previous one (ignoring
117 # the value of newid).
121 global $wgTitle, $wgOut, $wgLang, $wgIsMySQL;
122 $fname = "DifferenceEngine::loadText";
124 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
125 $wgOut->setArticleFlag( true );
126 $this->mNewtitle
= wfMsg( "currentrev" );
127 $id = $wgTitle->getArticleID();
129 $sql = "SELECT cur_text, cur_user_text, cur_comment FROM cur WHERE cur_id={$id}";
130 $res = wfQuery( $sql, DB_READ
, $fname );
131 if ( 0 == wfNumRows( $res ) ) { return false; }
133 $s = wfFetchObject( $res );
134 $this->mNewPage
= &$wgTitle;
135 $this->mNewtext
= $s->cur_text
;
136 $this->mNewUser
= $s->cur_user_text
;
137 $this->mNewComment
= $s->cur_comment
;
139 $sql = "SELECT old_namespace,old_title,old_timestamp,old_text,old_flags,old_user_text,old_comment FROM old WHERE " .
140 "old_id={$this->mNewid}";
142 $res = wfQuery( $sql, DB_READ
, $fname );
143 if ( 0 == wfNumRows( $res ) ) { return false; }
145 $s = wfFetchObject( $res );
146 $this->mNewtext
= Article
::getRevisionText( $s );
148 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
149 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
150 $this->mNewtitle
= wfMsg( "revisionasof", $t );
151 $this->mNewUser
= $s->old_user_text
;
152 $this->mNewComment
= $s->old_comment
;
154 if ( 0 == $this->mOldid
) {
155 $use_index=$wgIsMySQL?
"USE INDEX (name_title_timestamp)":"";
156 $sql = "SELECT old_namespace,old_title,old_timestamp,old_text,old_flags,old_user_text,old_comment " .
157 "FROM old $use_index WHERE " .
158 "old_namespace=" . $this->mNewPage
->getNamespace() . " AND " .
159 "old_title='" . wfStrencode( $this->mNewPage
->getDBkey() ) .
160 "' ORDER BY inverse_timestamp LIMIT 1";
161 $res = wfQuery( $sql, DB_READ
, $fname );
163 $sql = "SELECT old_namespace,old_title,old_timestamp,old_text,old_flags,old_user_text,old_comment FROM old WHERE " .
164 "old_id={$this->mOldid}";
165 $res = wfQuery( $sql, DB_READ
, $fname );
167 if ( 0 == wfNumRows( $res ) ) { return false; }
169 $s = wfFetchObject( $res );
170 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
171 $this->mOldtext
= Article
::getRevisionText( $s );
173 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
174 $this->mOldtitle
= wfMsg( "revisionasof", $t );
175 $this->mOldUser
= $s->old_user_text
;
176 $this->mOldComment
= $s->old_comment
;
182 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
184 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
185 // You may copy this code freely under the conditions of the GPL.
188 define('USE_ASSERTS', function_exists('assert'));
196 trigger_error("pure virtual", E_USER_ERROR
);
200 return $this->orig ?
sizeof($this->orig
) : 0;
203 function nclosing() {
204 return $this->closing ?
sizeof($this->closing
) : 0;
208 class _DiffOp_Copy
extends _DiffOp
{
211 function _DiffOp_Copy ($orig, $closing = false) {
212 if (!is_array($closing))
215 $this->closing
= $closing;
219 return new _DiffOp_Copy($this->closing
, $this->orig
);
223 class _DiffOp_Delete
extends _DiffOp
{
224 var $type = 'delete';
226 function _DiffOp_Delete ($lines) {
227 $this->orig
= $lines;
228 $this->closing
= false;
232 return new _DiffOp_Add($this->orig
);
236 class _DiffOp_Add
extends _DiffOp
{
239 function _DiffOp_Add ($lines) {
240 $this->closing
= $lines;
245 return new _DiffOp_Delete($this->closing
);
249 class _DiffOp_Change
extends _DiffOp
{
250 var $type = 'change';
252 function _DiffOp_Change ($orig, $closing) {
254 $this->closing
= $closing;
258 return new _DiffOp_Change($this->closing
, $this->orig
);
264 * Class used internally by Diff to actually compute the diffs.
266 * The algorithm used here is mostly lifted from the perl module
267 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
268 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
270 * More ideas are taken from:
271 * http://www.ics.uci.edu/~eppstein/161/960229.html
273 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
274 * diffutils-2.7, which can be found at:
275 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
277 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
280 * @author Geoffrey T. Dairiki
285 function diff ($from_lines, $to_lines) {
286 $n_from = sizeof($from_lines);
287 $n_to = sizeof($to_lines);
289 $this->xchanged
= $this->ychanged
= array();
290 $this->xv
= $this->yv
= array();
291 $this->xind
= $this->yind
= array();
293 unset($this->in_seq
);
296 // Skip leading common lines.
297 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
298 if ($from_lines[$skip] != $to_lines[$skip])
300 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
302 // Skip trailing common lines.
303 $xi = $n_from; $yi = $n_to;
304 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
305 if ($from_lines[$xi] != $to_lines[$yi])
307 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
310 // Ignore lines which do not exist in both files.
311 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
312 $xhash[$from_lines[$xi]] = 1;
313 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
314 $line = $to_lines[$yi];
315 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
321 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
322 $line = $from_lines[$xi];
323 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
330 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
332 // Merge edits when possible
333 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
334 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
336 // Compute the edit operations.
339 while ($xi < $n_from ||
$yi < $n_to) {
340 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
341 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
343 // Skip matching "snake".
345 while ( $xi < $n_from && $yi < $n_to
346 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
347 $copy[] = $from_lines[$xi++
];
351 $edits[] = new _DiffOp_Copy($copy);
353 // Find deletes & adds.
355 while ($xi < $n_from && $this->xchanged
[$xi])
356 $delete[] = $from_lines[$xi++
];
359 while ($yi < $n_to && $this->ychanged
[$yi])
360 $add[] = $to_lines[$yi++
];
363 $edits[] = new _DiffOp_Change($delete, $add);
365 $edits[] = new _DiffOp_Delete($delete);
367 $edits[] = new _DiffOp_Add($add);
373 /* Divide the Largest Common Subsequence (LCS) of the sequences
374 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
377 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
378 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
379 * sub sequences. The first sub-sequence is contained in [X0, X1),
380 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
381 * that (X0, Y0) == (XOFF, YOFF) and
382 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
384 * This function assumes that the first lines of the specified portions
385 * of the two files do not match, and likewise that the last lines do not
386 * match. The caller must trim matching lines from the beginning and end
387 * of the portions it is going to specify.
389 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
392 if ($xlim - $xoff > $ylim - $yoff) {
393 // Things seems faster (I'm not sure I understand why)
394 // when the shortest sequence in X.
396 list ($xoff, $xlim, $yoff, $ylim)
397 = array( $yoff, $ylim, $xoff, $xlim);
401 for ($i = $ylim - 1; $i >= $yoff; $i--)
402 $ymatches[$this->xv
[$i]][] = $i;
404 for ($i = $ylim - 1; $i >= $yoff; $i--)
405 $ymatches[$this->yv
[$i]][] = $i;
408 $this->seq
[0]= $yoff - 1;
409 $this->in_seq
= array();
412 $numer = $xlim - $xoff +
$nchunks - 1;
414 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
416 for ($i = 0; $i <= $this->lcs
; $i++
)
417 $ymids[$i][$chunk-1] = $this->seq
[$i];
419 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
420 for ( ; $x < $x1; $x++
) {
421 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
422 if (empty($ymatches[$line]))
424 $matches = $ymatches[$line];
426 while (list ($junk, $y) = each($matches))
427 if (empty($this->in_seq
[$y])) {
428 $k = $this->_lcs_pos($y);
429 USE_ASSERTS
&& assert($k > 0);
430 $ymids[$k] = $ymids[$k-1];
433 while (list ($junk, $y) = each($matches)) {
434 if ($y > $this->seq
[$k-1]) {
435 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
436 // Optimization: this is a common case:
437 // next match is just replacing previous match.
438 $this->in_seq
[$this->seq
[$k]] = false;
440 $this->in_seq
[$y] = 1;
442 else if (empty($this->in_seq
[$y])) {
443 $k = $this->_lcs_pos($y);
444 USE_ASSERTS
&& assert($k > 0);
445 $ymids[$k] = $ymids[$k-1];
451 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
452 $ymid = $ymids[$this->lcs
];
453 for ($n = 0; $n < $nchunks - 1; $n++
) {
454 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
456 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
458 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
460 return array($this->lcs
, $seps);
463 function _lcs_pos ($ypos) {
465 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
466 $this->seq
[++
$this->lcs
] = $ypos;
467 $this->in_seq
[$ypos] = 1;
472 while ($beg < $end) {
473 $mid = (int)(($beg +
$end) / 2);
474 if ( $ypos > $this->seq
[$mid] )
480 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
482 $this->in_seq
[$this->seq
[$end]] = false;
483 $this->seq
[$end] = $ypos;
484 $this->in_seq
[$ypos] = 1;
488 /* Find LCS of two sequences.
490 * The results are recorded in the vectors $this->{x,y}changed[], by
491 * storing a 1 in the element for each line that is an insertion
492 * or deletion (ie. is not in the LCS).
494 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
496 * Note that XLIM, YLIM are exclusive bounds.
497 * All line numbers are origin-0 and discarded lines are not counted.
499 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
500 // Slide down the bottom initial diagonal.
501 while ($xoff < $xlim && $yoff < $ylim
502 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
507 // Slide up the top initial diagonal.
508 while ($xlim > $xoff && $ylim > $yoff
509 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
514 if ($xoff == $xlim ||
$yoff == $ylim)
517 // This is ad hoc but seems to work well.
518 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
519 //$nchunks = max(2,min(8,(int)$nchunks));
520 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
522 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
526 // X and Y sequences have no common subsequence:
528 while ($yoff < $ylim)
529 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
530 while ($xoff < $xlim)
531 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
534 // Use the partitions to split this problem into subproblems.
537 while ($pt2 = next($seps)) {
538 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
544 /* Adjust inserts/deletes of identical lines to join changes
545 * as much as possible.
547 * We do something when a run of changed lines include a
548 * line at one end and has an excluded, identical line at the other.
549 * We are free to choose which identical line is included.
550 * `compareseq' usually chooses the one at the beginning,
551 * but usually it is cleaner to consider the following identical line
552 * to be the "change".
554 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
556 function _shift_boundaries ($lines, &$changed, $other_changed) {
560 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
561 $len = sizeof($lines);
562 $other_len = sizeof($other_changed);
566 * Scan forwards to find beginning of another run of changes.
567 * Also keep track of the corresponding point in the other file.
569 * Throughout this code, $i and $j are adjusted together so that
570 * the first $i elements of $changed and the first $j elements
571 * of $other_changed both contain the same number of zeros
573 * Furthermore, $j is always kept so that $j == $other_len or
574 * $other_changed[$j] == false.
576 while ($j < $other_len && $other_changed[$j])
579 while ($i < $len && ! $changed[$i]) {
580 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
582 while ($j < $other_len && $other_changed[$j])
591 // Find the end of this run of changes.
592 while (++
$i < $len && $changed[$i])
597 * Record the length of this run of changes, so that
598 * we can later determine whether the run has grown.
600 $runlength = $i - $start;
603 * Move the changed region back, so long as the
604 * previous unchanged line matches the last changed one.
605 * This merges with previous changed regions.
607 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
608 $changed[--$start] = 1;
609 $changed[--$i] = false;
610 while ($start > 0 && $changed[$start - 1])
612 USE_ASSERTS
&& assert('$j > 0');
613 while ($other_changed[--$j])
615 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
619 * Set CORRESPONDING to the end of the changed run, at the last
620 * point where it corresponds to a changed run in the other file.
621 * CORRESPONDING == LEN means no such point has been found.
623 $corresponding = $j < $other_len ?
$i : $len;
626 * Move the changed region forward, so long as the
627 * first changed line matches the following unchanged one.
628 * This merges with following changed regions.
629 * Do this second, so that if there are no merges,
630 * the changed region is moved forward as far as possible.
632 while ($i < $len && $lines[$start] == $lines[$i]) {
633 $changed[$start++
] = false;
635 while ($i < $len && $changed[$i])
638 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
640 if ($j < $other_len && $other_changed[$j]) {
642 while ($j < $other_len && $other_changed[$j])
646 } while ($runlength != $i - $start);
649 * If possible, move the fully-merged run of changes
650 * back to a corresponding run in the other file.
652 while ($corresponding < $i) {
653 $changed[--$start] = 1;
655 USE_ASSERTS
&& assert('$j > 0');
656 while ($other_changed[--$j])
658 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
665 * Class representing a 'diff' between two sequences of strings.
673 * Computes diff between sequences of strings.
675 * @param $from_lines array An array of strings.
676 * (Typically these are lines from a file.)
677 * @param $to_lines array An array of strings.
679 function Diff($from_lines, $to_lines) {
680 $eng = new _DiffEngine
;
681 $this->edits
= $eng->diff($from_lines, $to_lines);
682 //$this->_check($from_lines, $to_lines);
686 * Compute reversed Diff.
690 * $diff = new Diff($lines1, $lines2);
691 * $rev = $diff->reverse();
692 * @return object A Diff object representing the inverse of the
695 function reverse () {
697 $rev->edits
= array();
698 foreach ($this->edits
as $edit) {
699 $rev->edits
[] = $edit->reverse();
705 * Check for empty diff.
707 * @return bool True iff two sequences were identical.
709 function isEmpty () {
710 foreach ($this->edits
as $edit) {
711 if ($edit->type
!= 'copy')
718 * Compute the length of the Longest Common Subsequence (LCS).
720 * This is mostly for diagnostic purposed.
722 * @return int The length of the LCS.
726 foreach ($this->edits
as $edit) {
727 if ($edit->type
== 'copy')
728 $lcs +
= sizeof($edit->orig
);
734 * Get the original set of lines.
736 * This reconstructs the $from_lines parameter passed to the
739 * @return array The original sequence of strings.
744 foreach ($this->edits
as $edit) {
746 array_splice($lines, sizeof($lines), 0, $edit->orig
);
752 * Get the closing set of lines.
754 * This reconstructs the $to_lines parameter passed to the
757 * @return array The sequence of strings.
762 foreach ($this->edits
as $edit) {
764 array_splice($lines, sizeof($lines), 0, $edit->closing
);
770 * Check a Diff for validity.
772 * This is here only for debugging purposes.
774 function _check ($from_lines, $to_lines) {
775 if (serialize($from_lines) != serialize($this->orig()))
776 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
777 if (serialize($to_lines) != serialize($this->closing()))
778 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
780 $rev = $this->reverse();
781 if (serialize($to_lines) != serialize($rev->orig()))
782 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
783 if (serialize($from_lines) != serialize($rev->closing()))
784 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
788 foreach ($this->edits
as $edit) {
789 if ( $prevtype == $edit->type
)
790 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
791 $prevtype = $edit->type
;
795 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE
);
808 * Computes diff between sequences of strings.
810 * This can be used to compute things like
811 * case-insensitve diffs, or diffs which ignore
812 * changes in white-space.
814 * @param $from_lines array An array of strings.
815 * (Typically these are lines from a file.)
817 * @param $to_lines array An array of strings.
819 * @param $mapped_from_lines array This array should
820 * have the same size number of elements as $from_lines.
821 * The elements in $mapped_from_lines and
822 * $mapped_to_lines are what is actually compared
823 * when computing the diff.
825 * @param $mapped_to_lines array This array should
826 * have the same number of elements as $to_lines.
828 function MappedDiff($from_lines, $to_lines,
829 $mapped_from_lines, $mapped_to_lines) {
831 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
832 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
834 $this->Diff($mapped_from_lines, $mapped_to_lines);
837 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
838 $orig = &$this->edits
[$i]->orig
;
839 if (is_array($orig)) {
840 $orig = array_slice($from_lines, $xi, sizeof($orig));
841 $xi +
= sizeof($orig);
844 $closing = &$this->edits
[$i]->closing
;
845 if (is_array($closing)) {
846 $closing = array_slice($to_lines, $yi, sizeof($closing));
847 $yi +
= sizeof($closing);
854 * A class to format Diffs
856 * This class formats the diff in classic diff format.
857 * It is intended that this class be customized via inheritance,
858 * to obtain fancier outputs.
863 * Number of leading context "lines" to preserve.
865 * This should be left at zero for this class, but subclasses
866 * may want to set this to other values.
868 var $leading_context_lines = 0;
871 * Number of trailing context "lines" to preserve.
873 * This should be left at zero for this class, but subclasses
874 * may want to set this to other values.
876 var $trailing_context_lines = 0;
881 * @param $diff object A Diff object.
882 * @return string The formatted output.
884 function format($diff) {
890 $nlead = $this->leading_context_lines
;
891 $ntrail = $this->trailing_context_lines
;
893 $this->_start_diff();
895 foreach ($diff->edits
as $edit) {
896 if ($edit->type
== 'copy') {
897 if (is_array($block)) {
898 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
903 $context = array_slice($edit->orig
, 0, $ntrail);
904 $block[] = new _DiffOp_Copy($context);
906 $this->_block($x0, $ntrail +
$xi - $x0,
907 $y0, $ntrail +
$yi - $y0,
912 $context = $edit->orig
;
915 if (! is_array($block)) {
916 $context = array_slice($context, sizeof($context) - $nlead);
917 $x0 = $xi - sizeof($context);
918 $y0 = $yi - sizeof($context);
921 $block[] = new _DiffOp_Copy($context);
927 $xi +
= sizeof($edit->orig
);
929 $yi +
= sizeof($edit->closing
);
932 if (is_array($block))
933 $this->_block($x0, $xi - $x0,
937 return $this->_end_diff();
940 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
941 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
942 foreach ($edits as $edit) {
943 if ($edit->type
== 'copy')
944 $this->_context($edit->orig
);
945 elseif ($edit->type
== 'add')
946 $this->_added($edit->closing
);
947 elseif ($edit->type
== 'delete')
948 $this->_deleted($edit->orig
);
949 elseif ($edit->type
== 'change')
950 $this->_changed($edit->orig
, $edit->closing
);
952 trigger_error("Unknown edit type", E_USER_ERROR
);
957 function _start_diff() {
961 function _end_diff() {
962 $val = ob_get_contents();
967 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
969 $xbeg .= "," . ($xbeg +
$xlen - 1);
971 $ybeg .= "," . ($ybeg +
$ylen - 1);
973 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
976 function _start_block($header) {
980 function _end_block() {
983 function _lines($lines, $prefix = ' ') {
984 foreach ($lines as $line)
985 echo "$prefix $line\n";
988 function _context($lines) {
989 $this->_lines($lines);
992 function _added($lines) {
993 $this->_lines($lines, ">");
995 function _deleted($lines) {
996 $this->_lines($lines, "<");
999 function _changed($orig, $closing) {
1000 $this->_deleted($orig);
1002 $this->_added($closing);
1008 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1012 define('NBSP', "\xA0"); // iso-8859-x non-breaking space.
1014 class _HWLDF_WordAccumulator
{
1015 function _HWLDF_WordAccumulator () {
1016 $this->_lines
= array();
1022 function _flushGroup ($new_tag) {
1023 if ($this->_group
!== '') {
1024 if ($this->_tag
== 'mark')
1025 $this->_line
.= "<font color=\"red\">$this->_group</font>";
1027 $this->_line
.= $this->_group
;
1030 $this->_tag
= $new_tag;
1033 function _flushLine ($new_tag) {
1034 $this->_flushGroup($new_tag);
1035 if ($this->_line
!= '')
1036 $this->_lines
[] = $this->_line
;
1040 function addWords ($words, $tag = '') {
1041 if ($tag != $this->_tag
)
1042 $this->_flushGroup($tag);
1044 foreach ($words as $word) {
1045 // new-line should only come as first char of word.
1048 if ($word[0] == "\n") {
1049 $this->_group
.= NBSP
;
1050 $this->_flushLine($tag);
1051 $word = substr($word, 1);
1053 assert(!strstr($word, "\n"));
1054 $this->_group
.= $word;
1058 function getLines() {
1059 $this->_flushLine('~done');
1060 return $this->_lines
;
1064 class WordLevelDiff
extends MappedDiff
1066 function WordLevelDiff ($orig_lines, $closing_lines) {
1067 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1068 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1071 $this->MappedDiff($orig_words, $closing_words,
1072 $orig_stripped, $closing_stripped);
1075 function _split($lines) {
1076 // FIXME: fix POSIX char class.
1077 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1078 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1079 implode("\n", $lines),
1081 return array(array(''), array(''));
1083 return array($m[0], $m[1]);
1087 $orig = new _HWLDF_WordAccumulator
;
1089 foreach ($this->edits
as $edit) {
1090 if ($edit->type
== 'copy')
1091 $orig->addWords($edit->orig
);
1092 elseif ($edit->orig
)
1093 $orig->addWords($edit->orig
, 'mark');
1095 return $orig->getLines();
1098 function closing () {
1099 $closing = new _HWLDF_WordAccumulator
;
1101 foreach ($this->edits
as $edit) {
1102 if ($edit->type
== 'copy')
1103 $closing->addWords($edit->closing
);
1104 elseif ($edit->closing
)
1105 $closing->addWords($edit->closing
, 'mark');
1107 return $closing->getLines();
1112 * Wikipedia Table style diff formatter.
1115 class TableDiffFormatter
extends DiffFormatter
1117 function TableDiffFormatter() {
1118 $this->leading_context_lines
= 2;
1119 $this->trailing_context_lines
= 2;
1122 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1123 $l1 = wfMsg( "lineno", $xbeg );
1124 $l2 = wfMsg( "lineno", $ybeg );
1126 $r = "<tr><td colspan='2' align='left'><strong>{$l1}</strong></td>\n" .
1127 "<td colspan='2' align='left'><strong>{$l2}</strong></td></tr>\n";
1131 function _start_block( $header ) {
1133 $wgOut->addHTML( $header );
1136 function _end_block() {
1139 function _lines( $lines, $prefix=' ', $color="white" ) {
1142 function addedLine( $line ) {
1143 return "<td>+</td><td class='diff-addedline'>" .
1144 "<small>{$line}</small></td>";
1147 function deletedLine( $line ) {
1148 return "<td>-</td><td class='diff-deletedline'>" .
1149 "<small>{$line}</small></td>";
1152 function emptyLine() {
1153 return "<td colspan='2'> </td>";
1156 function contextLine( $line ) {
1157 return "<td> </td><td class='diff-context'><small>{$line}</small></td>";
1160 function _added($lines) {
1162 foreach ($lines as $line) {
1163 $wgOut->addHTML( "<tr>" . $this->emptyLine() .
1164 $this->addedLine( $line ) . "</tr>\n" );
1168 function _deleted($lines) {
1170 foreach ($lines as $line) {
1171 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1172 $this->emptyLine() . "</tr>\n" );
1176 function _context( $lines ) {
1178 foreach ($lines as $line) {
1179 $wgOut->addHTML( "<tr>" . $this->contextLine( $line ) .
1180 $this->contextLine( $line ) . "</tr>\n" );
1184 function _changed( $orig, $closing ) {
1186 $diff = new WordLevelDiff( $orig, $closing );
1187 $del = $diff->orig();
1188 $add = $diff->closing();
1190 while ( $line = array_shift( $del ) ) {
1191 $aline = array_shift( $add );
1192 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1193 $this->addedLine( $aline ) . "</tr>\n" );
1195 $this->_added( $add ); # If any leftovers