4 class DifferenceEngine
{
5 /* private */ var $mOldid, $mNewid;
6 /* private */ var $mOldtitle, $mNewtitle;
7 /* private */ var $mOldtext, $mNewtext;
8 /* private */ var $mOldUser, $mNewUser;
10 function DifferenceEngine( $old, $new )
16 function showDiffPage()
18 global $wgUser, $wgTitle, $wgOut, $wgLang;
20 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
22 $mtext = wfMsg( "missingarticle", $t );
24 $wgOut->setArticleFlag( false );
25 if ( ! $this->loadText() ) {
26 $wgOut->setPagetitle( wfMsg( "errorpagetitle" ) );
27 $wgOut->addHTML( $mtext );
30 $wgOut->supressQuickbar();
31 $wgOut->setSubtitle( wfMsg( "difference" ) );
32 $wgOut->setRobotpolicy( "noindex,follow" );
34 $sk = $wgUser->getSkin();
35 $oldUserTitle = Title
::makeTitle( NS_USER
, $this->mOldUser
);
36 $newUserTitle = Title
::makeTitle( NS_USER
, $this->mNewUser
);
37 $oldUserLink = $sk->makeLinkObj( $oldUserTitle, $this->mOldUser
);
38 $newUserLink = $sk->makeLinkObj( $newUserTitle, $this->mNewUser
);
39 $oldHeader = "<strong>{$this->mOldtitle}</strong><br>$oldUserLink";
40 $newHeader = "<strong>{$this->mNewtitle}</strong><br>$newUserLink";
42 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
43 $oldHeader, $newHeader );
44 $wgOut->addHTML( "<hr><h2>{$this->mNewtitle}</h2>\n" );
45 $wgOut->addWikiText( $this->mNewtext
);
48 function showDiff( $otext, $ntext, $otitle, $ntitle )
52 $ota = explode( "\n", str_replace( "\r\n", "\n",
53 htmlspecialchars( $otext ) ) );
54 $nta = explode( "\n", str_replace( "\r\n", "\n",
55 htmlspecialchars( $ntext ) ) );
57 $wgOut->addHTML( "<table width='98%' border=0
58 cellpadding=0 cellspacing='4px'><tr>
59 <td colspan=2 width='50%' align=center bgcolor='#cccccc'>
61 <td colspan=2 width='50%' align=center bgcolor='#cccccc'>
65 $diffs = new Diff( $ota, $nta );
66 $formatter = new TableDiffFormatter();
67 $formatter->format( $diffs );
68 $wgOut->addHTML( "</table>\n" );
71 # Load the text of the articles to compare. If newid is 0, then compare
72 # the old article in oldid to the current article; if oldid is 0, then
73 # compare the current article to the immediately previous one (ignoring
74 # the value of newid).
78 global $wgTitle, $wgOut, $wgLang;
79 $fname = "DifferenceEngine::loadText";
81 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
82 $wgOut->setArticleFlag( true );
83 $this->mNewtitle
= wfMsg( "currentrev" );
84 $id = $wgTitle->getArticleID();
86 $sql = "SELECT cur_text, cur_user_text FROM cur WHERE cur_id={$id}";
87 $res = wfQuery( $sql, DB_READ
, $fname );
88 if ( 0 == wfNumRows( $res ) ) { return false; }
90 $s = wfFetchObject( $res );
91 $this->mNewtext
= $s->cur_text
;
92 $this->mNewUser
= $s->cur_user_text
;
94 $sql = "SELECT old_timestamp,old_text,old_flags,old_user_text FROM old WHERE " .
95 "old_id={$this->mNewid}";
97 $res = wfQuery( $sql, DB_READ
, $fname );
98 if ( 0 == wfNumRows( $res ) ) { return false; }
100 $s = wfFetchObject( $res );
101 $this->mNewtext
= Article
::getRevisionText( $s );
103 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
104 $this->mNewtitle
= wfMsg( "revisionasof", $t );
105 $this->mNewUser
= $s->old_user_text
;
107 if ( 0 == $this->mOldid
) {
108 $sql = "SELECT old_timestamp,old_text,old_flags,old_user_text " .
109 "FROM old USE INDEX (name_title_timestamp) WHERE " .
110 "old_namespace=" . $wgTitle->getNamespace() . " AND " .
111 "old_title='" . wfStrencode( $wgTitle->getDBkey() ) .
112 "' ORDER BY inverse_timestamp LIMIT 1";
113 $res = wfQuery( $sql, DB_READ
, $fname );
115 $sql = "SELECT old_timestamp,old_text,old_flags,old_user_text FROM old WHERE " .
116 "old_id={$this->mOldid}";
117 $res = wfQuery( $sql, DB_READ
, $fname );
119 if ( 0 == wfNumRows( $res ) ) { return false; }
121 $s = wfFetchObject( $res );
122 $this->mOldtext
= Article
::getRevisionText( $s );
124 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
125 $this->mOldtitle
= wfMsg( "revisionasof", $t );
126 $this->mOldUser
= $s->old_user_text
;
132 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
134 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
135 // You may copy this code freely under the conditions of the GPL.
138 define('USE_ASSERTS', function_exists('assert'));
146 trigger_error("pure virtual", E_USER_ERROR
);
150 return $this->orig ?
sizeof($this->orig
) : 0;
153 function nclosing() {
154 return $this->closing ?
sizeof($this->closing
) : 0;
158 class _DiffOp_Copy
extends _DiffOp
{
161 function _DiffOp_Copy ($orig, $closing = false) {
162 if (!is_array($closing))
165 $this->closing
= $closing;
169 return new _DiffOp_Copy($this->closing
, $this->orig
);
173 class _DiffOp_Delete
extends _DiffOp
{
174 var $type = 'delete';
176 function _DiffOp_Delete ($lines) {
177 $this->orig
= $lines;
178 $this->closing
= false;
182 return new _DiffOp_Add($this->orig
);
186 class _DiffOp_Add
extends _DiffOp
{
189 function _DiffOp_Add ($lines) {
190 $this->closing
= $lines;
195 return new _DiffOp_Delete($this->closing
);
199 class _DiffOp_Change
extends _DiffOp
{
200 var $type = 'change';
202 function _DiffOp_Change ($orig, $closing) {
204 $this->closing
= $closing;
208 return new _DiffOp_Change($this->closing
, $this->orig
);
214 * Class used internally by Diff to actually compute the diffs.
216 * The algorithm used here is mostly lifted from the perl module
217 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
218 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
220 * More ideas are taken from:
221 * http://www.ics.uci.edu/~eppstein/161/960229.html
223 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
224 * diffutils-2.7, which can be found at:
225 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
227 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
230 * @author Geoffrey T. Dairiki
235 function diff ($from_lines, $to_lines) {
236 $n_from = sizeof($from_lines);
237 $n_to = sizeof($to_lines);
239 $this->xchanged
= $this->ychanged
= array();
240 $this->xv
= $this->yv
= array();
241 $this->xind
= $this->yind
= array();
243 unset($this->in_seq
);
246 // Skip leading common lines.
247 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
248 if ($from_lines[$skip] != $to_lines[$skip])
250 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
252 // Skip trailing common lines.
253 $xi = $n_from; $yi = $n_to;
254 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
255 if ($from_lines[$xi] != $to_lines[$yi])
257 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
260 // Ignore lines which do not exist in both files.
261 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
262 $xhash[$from_lines[$xi]] = 1;
263 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
264 $line = $to_lines[$yi];
265 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
271 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
272 $line = $from_lines[$xi];
273 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
280 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
282 // Merge edits when possible
283 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
284 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
286 // Compute the edit operations.
289 while ($xi < $n_from ||
$yi < $n_to) {
290 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
291 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
293 // Skip matching "snake".
295 while ( $xi < $n_from && $yi < $n_to
296 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
297 $copy[] = $from_lines[$xi++
];
301 $edits[] = new _DiffOp_Copy($copy);
303 // Find deletes & adds.
305 while ($xi < $n_from && $this->xchanged
[$xi])
306 $delete[] = $from_lines[$xi++
];
309 while ($yi < $n_to && $this->ychanged
[$yi])
310 $add[] = $to_lines[$yi++
];
313 $edits[] = new _DiffOp_Change($delete, $add);
315 $edits[] = new _DiffOp_Delete($delete);
317 $edits[] = new _DiffOp_Add($add);
323 /* Divide the Largest Common Subsequence (LCS) of the sequences
324 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
327 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
328 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
329 * sub sequences. The first sub-sequence is contained in [X0, X1),
330 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
331 * that (X0, Y0) == (XOFF, YOFF) and
332 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
334 * This function assumes that the first lines of the specified portions
335 * of the two files do not match, and likewise that the last lines do not
336 * match. The caller must trim matching lines from the beginning and end
337 * of the portions it is going to specify.
339 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
342 if ($xlim - $xoff > $ylim - $yoff) {
343 // Things seems faster (I'm not sure I understand why)
344 // when the shortest sequence in X.
346 list ($xoff, $xlim, $yoff, $ylim)
347 = array( $yoff, $ylim, $xoff, $xlim);
351 for ($i = $ylim - 1; $i >= $yoff; $i--)
352 $ymatches[$this->xv
[$i]][] = $i;
354 for ($i = $ylim - 1; $i >= $yoff; $i--)
355 $ymatches[$this->yv
[$i]][] = $i;
358 $this->seq
[0]= $yoff - 1;
359 $this->in_seq
= array();
362 $numer = $xlim - $xoff +
$nchunks - 1;
364 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
366 for ($i = 0; $i <= $this->lcs
; $i++
)
367 $ymids[$i][$chunk-1] = $this->seq
[$i];
369 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
370 for ( ; $x < $x1; $x++
) {
371 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
372 if (empty($ymatches[$line]))
374 $matches = $ymatches[$line];
376 while (list ($junk, $y) = each($matches))
377 if (empty($this->in_seq
[$y])) {
378 $k = $this->_lcs_pos($y);
379 USE_ASSERTS
&& assert($k > 0);
380 $ymids[$k] = $ymids[$k-1];
383 while (list ($junk, $y) = each($matches)) {
384 if ($y > $this->seq
[$k-1]) {
385 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
386 // Optimization: this is a common case:
387 // next match is just replacing previous match.
388 $this->in_seq
[$this->seq
[$k]] = false;
390 $this->in_seq
[$y] = 1;
392 else if (empty($this->in_seq
[$y])) {
393 $k = $this->_lcs_pos($y);
394 USE_ASSERTS
&& assert($k > 0);
395 $ymids[$k] = $ymids[$k-1];
401 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
402 $ymid = $ymids[$this->lcs
];
403 for ($n = 0; $n < $nchunks - 1; $n++
) {
404 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
406 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
408 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
410 return array($this->lcs
, $seps);
413 function _lcs_pos ($ypos) {
415 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
416 $this->seq
[++
$this->lcs
] = $ypos;
417 $this->in_seq
[$ypos] = 1;
422 while ($beg < $end) {
423 $mid = (int)(($beg +
$end) / 2);
424 if ( $ypos > $this->seq
[$mid] )
430 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
432 $this->in_seq
[$this->seq
[$end]] = false;
433 $this->seq
[$end] = $ypos;
434 $this->in_seq
[$ypos] = 1;
438 /* Find LCS of two sequences.
440 * The results are recorded in the vectors $this->{x,y}changed[], by
441 * storing a 1 in the element for each line that is an insertion
442 * or deletion (ie. is not in the LCS).
444 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
446 * Note that XLIM, YLIM are exclusive bounds.
447 * All line numbers are origin-0 and discarded lines are not counted.
449 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
450 // Slide down the bottom initial diagonal.
451 while ($xoff < $xlim && $yoff < $ylim
452 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
457 // Slide up the top initial diagonal.
458 while ($xlim > $xoff && $ylim > $yoff
459 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
464 if ($xoff == $xlim ||
$yoff == $ylim)
467 // This is ad hoc but seems to work well.
468 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
469 //$nchunks = max(2,min(8,(int)$nchunks));
470 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
472 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
476 // X and Y sequences have no common subsequence:
478 while ($yoff < $ylim)
479 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
480 while ($xoff < $xlim)
481 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
484 // Use the partitions to split this problem into subproblems.
487 while ($pt2 = next($seps)) {
488 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
494 /* Adjust inserts/deletes of identical lines to join changes
495 * as much as possible.
497 * We do something when a run of changed lines include a
498 * line at one end and has an excluded, identical line at the other.
499 * We are free to choose which identical line is included.
500 * `compareseq' usually chooses the one at the beginning,
501 * but usually it is cleaner to consider the following identical line
502 * to be the "change".
504 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
506 function _shift_boundaries ($lines, &$changed, $other_changed) {
510 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
511 $len = sizeof($lines);
512 $other_len = sizeof($other_changed);
516 * Scan forwards to find beginning of another run of changes.
517 * Also keep track of the corresponding point in the other file.
519 * Throughout this code, $i and $j are adjusted together so that
520 * the first $i elements of $changed and the first $j elements
521 * of $other_changed both contain the same number of zeros
523 * Furthermore, $j is always kept so that $j == $other_len or
524 * $other_changed[$j] == false.
526 while ($j < $other_len && $other_changed[$j])
529 while ($i < $len && ! $changed[$i]) {
530 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
532 while ($j < $other_len && $other_changed[$j])
541 // Find the end of this run of changes.
542 while (++
$i < $len && $changed[$i])
547 * Record the length of this run of changes, so that
548 * we can later determine whether the run has grown.
550 $runlength = $i - $start;
553 * Move the changed region back, so long as the
554 * previous unchanged line matches the last changed one.
555 * This merges with previous changed regions.
557 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
558 $changed[--$start] = 1;
559 $changed[--$i] = false;
560 while ($start > 0 && $changed[$start - 1])
562 USE_ASSERTS
&& assert('$j > 0');
563 while ($other_changed[--$j])
565 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
569 * Set CORRESPONDING to the end of the changed run, at the last
570 * point where it corresponds to a changed run in the other file.
571 * CORRESPONDING == LEN means no such point has been found.
573 $corresponding = $j < $other_len ?
$i : $len;
576 * Move the changed region forward, so long as the
577 * first changed line matches the following unchanged one.
578 * This merges with following changed regions.
579 * Do this second, so that if there are no merges,
580 * the changed region is moved forward as far as possible.
582 while ($i < $len && $lines[$start] == $lines[$i]) {
583 $changed[$start++
] = false;
585 while ($i < $len && $changed[$i])
588 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
590 if ($j < $other_len && $other_changed[$j]) {
592 while ($j < $other_len && $other_changed[$j])
596 } while ($runlength != $i - $start);
599 * If possible, move the fully-merged run of changes
600 * back to a corresponding run in the other file.
602 while ($corresponding < $i) {
603 $changed[--$start] = 1;
605 USE_ASSERTS
&& assert('$j > 0');
606 while ($other_changed[--$j])
608 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
615 * Class representing a 'diff' between two sequences of strings.
623 * Computes diff between sequences of strings.
625 * @param $from_lines array An array of strings.
626 * (Typically these are lines from a file.)
627 * @param $to_lines array An array of strings.
629 function Diff($from_lines, $to_lines) {
630 $eng = new _DiffEngine
;
631 $this->edits
= $eng->diff($from_lines, $to_lines);
632 //$this->_check($from_lines, $to_lines);
636 * Compute reversed Diff.
640 * $diff = new Diff($lines1, $lines2);
641 * $rev = $diff->reverse();
642 * @return object A Diff object representing the inverse of the
645 function reverse () {
647 $rev->edits
= array();
648 foreach ($this->edits
as $edit) {
649 $rev->edits
[] = $edit->reverse();
655 * Check for empty diff.
657 * @return bool True iff two sequences were identical.
659 function isEmpty () {
660 foreach ($this->edits
as $edit) {
661 if ($edit->type
!= 'copy')
668 * Compute the length of the Longest Common Subsequence (LCS).
670 * This is mostly for diagnostic purposed.
672 * @return int The length of the LCS.
676 foreach ($this->edits
as $edit) {
677 if ($edit->type
== 'copy')
678 $lcs +
= sizeof($edit->orig
);
684 * Get the original set of lines.
686 * This reconstructs the $from_lines parameter passed to the
689 * @return array The original sequence of strings.
694 foreach ($this->edits
as $edit) {
696 array_splice($lines, sizeof($lines), 0, $edit->orig
);
702 * Get the closing set of lines.
704 * This reconstructs the $to_lines parameter passed to the
707 * @return array The sequence of strings.
712 foreach ($this->edits
as $edit) {
714 array_splice($lines, sizeof($lines), 0, $edit->closing
);
720 * Check a Diff for validity.
722 * This is here only for debugging purposes.
724 function _check ($from_lines, $to_lines) {
725 if (serialize($from_lines) != serialize($this->orig()))
726 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
727 if (serialize($to_lines) != serialize($this->closing()))
728 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
730 $rev = $this->reverse();
731 if (serialize($to_lines) != serialize($rev->orig()))
732 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
733 if (serialize($from_lines) != serialize($rev->closing()))
734 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
738 foreach ($this->edits
as $edit) {
739 if ( $prevtype == $edit->type
)
740 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
741 $prevtype = $edit->type
;
745 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE
);
758 * Computes diff between sequences of strings.
760 * This can be used to compute things like
761 * case-insensitve diffs, or diffs which ignore
762 * changes in white-space.
764 * @param $from_lines array An array of strings.
765 * (Typically these are lines from a file.)
767 * @param $to_lines array An array of strings.
769 * @param $mapped_from_lines array This array should
770 * have the same size number of elements as $from_lines.
771 * The elements in $mapped_from_lines and
772 * $mapped_to_lines are what is actually compared
773 * when computing the diff.
775 * @param $mapped_to_lines array This array should
776 * have the same number of elements as $to_lines.
778 function MappedDiff($from_lines, $to_lines,
779 $mapped_from_lines, $mapped_to_lines) {
781 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
782 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
784 $this->Diff($mapped_from_lines, $mapped_to_lines);
787 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
788 $orig = &$this->edits
[$i]->orig
;
789 if (is_array($orig)) {
790 $orig = array_slice($from_lines, $xi, sizeof($orig));
791 $xi +
= sizeof($orig);
794 $closing = &$this->edits
[$i]->closing
;
795 if (is_array($closing)) {
796 $closing = array_slice($to_lines, $yi, sizeof($closing));
797 $yi +
= sizeof($closing);
804 * A class to format Diffs
806 * This class formats the diff in classic diff format.
807 * It is intended that this class be customized via inheritance,
808 * to obtain fancier outputs.
813 * Number of leading context "lines" to preserve.
815 * This should be left at zero for this class, but subclasses
816 * may want to set this to other values.
818 var $leading_context_lines = 0;
821 * Number of trailing context "lines" to preserve.
823 * This should be left at zero for this class, but subclasses
824 * may want to set this to other values.
826 var $trailing_context_lines = 0;
831 * @param $diff object A Diff object.
832 * @return string The formatted output.
834 function format($diff) {
840 $nlead = $this->leading_context_lines
;
841 $ntrail = $this->trailing_context_lines
;
843 $this->_start_diff();
845 foreach ($diff->edits
as $edit) {
846 if ($edit->type
== 'copy') {
847 if (is_array($block)) {
848 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
853 $context = array_slice($edit->orig
, 0, $ntrail);
854 $block[] = new _DiffOp_Copy($context);
856 $this->_block($x0, $ntrail +
$xi - $x0,
857 $y0, $ntrail +
$yi - $y0,
862 $context = $edit->orig
;
865 if (! is_array($block)) {
866 $context = array_slice($context, sizeof($context) - $nlead);
867 $x0 = $xi - sizeof($context);
868 $y0 = $yi - sizeof($context);
871 $block[] = new _DiffOp_Copy($context);
877 $xi +
= sizeof($edit->orig
);
879 $yi +
= sizeof($edit->closing
);
882 if (is_array($block))
883 $this->_block($x0, $xi - $x0,
887 return $this->_end_diff();
890 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
891 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
892 foreach ($edits as $edit) {
893 if ($edit->type
== 'copy')
894 $this->_context($edit->orig
);
895 elseif ($edit->type
== 'add')
896 $this->_added($edit->closing
);
897 elseif ($edit->type
== 'delete')
898 $this->_deleted($edit->orig
);
899 elseif ($edit->type
== 'change')
900 $this->_changed($edit->orig
, $edit->closing
);
902 trigger_error("Unknown edit type", E_USER_ERROR
);
907 function _start_diff() {
911 function _end_diff() {
912 $val = ob_get_contents();
917 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
919 $xbeg .= "," . ($xbeg +
$xlen - 1);
921 $ybeg .= "," . ($ybeg +
$ylen - 1);
923 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
926 function _start_block($header) {
930 function _end_block() {
933 function _lines($lines, $prefix = ' ') {
934 foreach ($lines as $line)
935 echo "$prefix $line\n";
938 function _context($lines) {
939 $this->_lines($lines);
942 function _added($lines) {
943 $this->_lines($lines, ">");
945 function _deleted($lines) {
946 $this->_lines($lines, "<");
949 function _changed($orig, $closing) {
950 $this->_deleted($orig);
952 $this->_added($closing);
958 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
962 define('NBSP', "\xA0"); // iso-8859-x non-breaking space.
964 class _HWLDF_WordAccumulator
{
965 function _HWLDF_WordAccumulator () {
966 $this->_lines
= array();
972 function _flushGroup ($new_tag) {
973 if ($this->_group
!== '') {
974 if ($this->_tag
== 'mark')
975 $this->_line
.= "<font color=\"red\">$this->_group</font>";
977 $this->_line
.= $this->_group
;
980 $this->_tag
= $new_tag;
983 function _flushLine ($new_tag) {
984 $this->_flushGroup($new_tag);
985 if ($this->_line
!= '')
986 $this->_lines
[] = $this->_line
;
990 function addWords ($words, $tag = '') {
991 if ($tag != $this->_tag
)
992 $this->_flushGroup($tag);
994 foreach ($words as $word) {
995 // new-line should only come as first char of word.
998 if ($word[0] == "\n") {
999 $this->_group
.= NBSP
;
1000 $this->_flushLine($tag);
1001 $word = substr($word, 1);
1003 assert(!strstr($word, "\n"));
1004 $this->_group
.= $word;
1008 function getLines() {
1009 $this->_flushLine('~done');
1010 return $this->_lines
;
1014 class WordLevelDiff
extends MappedDiff
1016 function WordLevelDiff ($orig_lines, $closing_lines) {
1017 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1018 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1021 $this->MappedDiff($orig_words, $closing_words,
1022 $orig_stripped, $closing_stripped);
1025 function _split($lines) {
1026 // FIXME: fix POSIX char class.
1027 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1028 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1029 implode("\n", $lines),
1031 return array(array(''), array(''));
1033 return array($m[0], $m[1]);
1037 $orig = new _HWLDF_WordAccumulator
;
1039 foreach ($this->edits
as $edit) {
1040 if ($edit->type
== 'copy')
1041 $orig->addWords($edit->orig
);
1042 elseif ($edit->orig
)
1043 $orig->addWords($edit->orig
, 'mark');
1045 return $orig->getLines();
1048 function closing () {
1049 $closing = new _HWLDF_WordAccumulator
;
1051 foreach ($this->edits
as $edit) {
1052 if ($edit->type
== 'copy')
1053 $closing->addWords($edit->closing
);
1054 elseif ($edit->closing
)
1055 $closing->addWords($edit->closing
, 'mark');
1057 return $closing->getLines();
1062 * Wikipedia Table style diff formatter.
1065 class TableDiffFormatter
extends DiffFormatter
1067 function TableDiffFormatter() {
1068 $this->leading_context_lines
= 2;
1069 $this->trailing_context_lines
= 2;
1072 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1073 $l1 = wfMsg( "lineno", $xbeg );
1074 $l2 = wfMsg( "lineno", $ybeg );
1076 $r = "<tr><td colspan=2 align=left><strong>{$l1}</strong></td>\n" .
1077 "<td colspan=2 align=left><strong>{$l2}</strong></td></tr>\n";
1081 function _start_block( $header ) {
1083 $wgOut->addHTML( $header );
1086 function _end_block() {
1089 function _lines( $lines, $prefix=' ', $color="white" ) {
1092 function addedLine( $line ) {
1093 return "<td>+</td><td bgcolor='#ccffcc'>" .
1094 "<small>{$line}</small></td>";
1097 function deletedLine( $line ) {
1098 return "<td>-</td><td bgcolor='#ffffaa'>" .
1099 "<small>{$line}</small></td>";
1102 function emptyLine() {
1103 return "<td colspan=2> </td>";
1106 function contextLine( $line ) {
1107 return "<td> </td><td bgcolor='white'><small>{$line}</small></td>";
1110 function _added($lines) {
1112 foreach ($lines as $line) {
1113 $wgOut->addHTML( "<tr>" . $this->emptyLine() .
1114 $this->addedLine( $line ) . "</tr>\n" );
1118 function _deleted($lines) {
1120 foreach ($lines as $line) {
1121 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1122 $this->emptyLine() . "</tr>\n" );
1126 function _context( $lines ) {
1128 foreach ($lines as $line) {
1129 $wgOut->addHTML( "<tr>" . $this->contextLine( $line ) .
1130 $this->contextLine( $line ) . "</tr>\n" );
1134 function _changed( $orig, $closing ) {
1136 $diff = new WordLevelDiff( $orig, $closing );
1137 $del = $diff->orig();
1138 $add = $diff->closing();
1140 while ( $line = array_shift( $del ) ) {
1141 $aline = array_shift( $add );
1142 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1143 $this->addedLine( $aline ) . "</tr>\n" );
1145 $this->_added( $add ); # If any leftovers