3 * @defgroup DifferenceEngine DifferenceEngine
6 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
8 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
9 // You may copy this code freely under the conditions of the GPL.
15 * @ingroup DifferenceEngine
23 trigger_error('pure virtual', E_USER_ERROR
);
27 return $this->orig ?
sizeof($this->orig
) : 0;
31 return $this->closing ?
sizeof($this->closing
) : 0;
38 * @ingroup DifferenceEngine
40 class _DiffOp_Copy
extends _DiffOp
{
43 function _DiffOp_Copy ($orig, $closing = false) {
44 if (!is_array($closing))
47 $this->closing
= $closing;
51 return new _DiffOp_Copy($this->closing
, $this->orig
);
58 * @ingroup DifferenceEngine
60 class _DiffOp_Delete
extends _DiffOp
{
63 function _DiffOp_Delete ($lines) {
65 $this->closing
= false;
69 return new _DiffOp_Add($this->orig
);
76 * @ingroup DifferenceEngine
78 class _DiffOp_Add
extends _DiffOp
{
81 function _DiffOp_Add ($lines) {
82 $this->closing
= $lines;
87 return new _DiffOp_Delete($this->closing
);
94 * @ingroup DifferenceEngine
96 class _DiffOp_Change
extends _DiffOp
{
99 function _DiffOp_Change ($orig, $closing) {
101 $this->closing
= $closing;
105 return new _DiffOp_Change($this->closing
, $this->orig
);
110 * Class used internally by Diff to actually compute the diffs.
112 * The algorithm used here is mostly lifted from the perl module
113 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
114 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
116 * More ideas are taken from:
117 * http://www.ics.uci.edu/~eppstein/161/960229.html
119 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
120 * diffutils-2.7, which can be found at:
121 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
123 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
126 * Line length limits for robustness added by Tim Starling, 2005-08-31
127 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
129 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
131 * @ingroup DifferenceEngine
135 const MAX_XREF_LENGTH
= 10000;
137 function diff ($from_lines, $to_lines){
138 wfProfileIn( __METHOD__
);
140 // Diff and store locally
141 $this->diff_local($from_lines, $to_lines);
143 // Merge edits when possible
144 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
145 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
147 // Compute the edit operations.
148 $n_from = sizeof($from_lines);
149 $n_to = sizeof($to_lines);
153 while ($xi < $n_from ||
$yi < $n_to) {
154 assert($yi < $n_to ||
$this->xchanged
[$xi]);
155 assert($xi < $n_from ||
$this->ychanged
[$yi]);
157 // Skip matching "snake".
159 while ( $xi < $n_from && $yi < $n_to
160 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
161 $copy[] = $from_lines[$xi++
];
165 $edits[] = new _DiffOp_Copy($copy);
167 // Find deletes & adds.
169 while ($xi < $n_from && $this->xchanged
[$xi])
170 $delete[] = $from_lines[$xi++
];
173 while ($yi < $n_to && $this->ychanged
[$yi])
174 $add[] = $to_lines[$yi++
];
177 $edits[] = new _DiffOp_Change($delete, $add);
179 $edits[] = new _DiffOp_Delete($delete);
181 $edits[] = new _DiffOp_Add($add);
183 wfProfileOut( __METHOD__
);
187 function diff_local ($from_lines, $to_lines) {
188 global $wgExternalDiffEngine;
189 wfProfileIn( __METHOD__
);
191 if($wgExternalDiffEngine == 'wikidiff3'){
193 $wikidiff3 = new WikiDiff3();
194 $wikidiff3->diff($from_lines, $to_lines);
195 $this->xchanged
= $wikidiff3->removed
;
196 $this->ychanged
= $wikidiff3->added
;
200 $n_from = sizeof($from_lines);
201 $n_to = sizeof($to_lines);
202 $this->xchanged
= $this->ychanged
= array();
203 $this->xv
= $this->yv
= array();
204 $this->xind
= $this->yind
= array();
206 unset($this->in_seq
);
209 // Skip leading common lines.
210 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
211 if ($from_lines[$skip] !== $to_lines[$skip])
213 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
215 // Skip trailing common lines.
216 $xi = $n_from; $yi = $n_to;
217 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
218 if ($from_lines[$xi] !== $to_lines[$yi])
220 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
223 // Ignore lines which do not exist in both files.
224 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
225 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
228 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
229 $line = $to_lines[$yi];
230 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
232 $yhash[$this->_line_hash($line)] = 1;
236 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
237 $line = $from_lines[$xi];
238 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
245 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
247 wfProfileOut( __METHOD__
);
251 * Returns the whole line if it's small enough, or the MD5 hash otherwise
253 function _line_hash( $line ) {
254 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
261 /* Divide the Largest Common Subsequence (LCS) of the sequences
262 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
265 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
266 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
267 * sub sequences. The first sub-sequence is contained in [X0, X1),
268 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
269 * that (X0, Y0) == (XOFF, YOFF) and
270 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
272 * This function assumes that the first lines of the specified portions
273 * of the two files do not match, and likewise that the last lines do not
274 * match. The caller must trim matching lines from the beginning and end
275 * of the portions it is going to specify.
277 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
280 if ($xlim - $xoff > $ylim - $yoff) {
281 // Things seems faster (I'm not sure I understand why)
282 // when the shortest sequence in X.
284 list ($xoff, $xlim, $yoff, $ylim)
285 = array( $yoff, $ylim, $xoff, $xlim);
289 for ($i = $ylim - 1; $i >= $yoff; $i--)
290 $ymatches[$this->xv
[$i]][] = $i;
292 for ($i = $ylim - 1; $i >= $yoff; $i--)
293 $ymatches[$this->yv
[$i]][] = $i;
296 $this->seq
[0]= $yoff - 1;
297 $this->in_seq
= array();
300 $numer = $xlim - $xoff +
$nchunks - 1;
302 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
304 for ($i = 0; $i <= $this->lcs
; $i++
)
305 $ymids[$i][$chunk-1] = $this->seq
[$i];
307 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
308 for ( ; $x < $x1; $x++
) {
309 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
310 if (empty($ymatches[$line]))
312 $matches = $ymatches[$line];
314 while (list ($junk, $y) = each($matches))
315 if (empty($this->in_seq
[$y])) {
316 $k = $this->_lcs_pos($y);
318 $ymids[$k] = $ymids[$k-1];
321 while (list ( /* $junk */, $y) = each($matches)) {
322 if ($y > $this->seq
[$k-1]) {
323 assert($y < $this->seq
[$k]);
324 // Optimization: this is a common case:
325 // next match is just replacing previous match.
326 $this->in_seq
[$this->seq
[$k]] = false;
328 $this->in_seq
[$y] = 1;
329 } else if (empty($this->in_seq
[$y])) {
330 $k = $this->_lcs_pos($y);
332 $ymids[$k] = $ymids[$k-1];
338 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
339 $ymid = $ymids[$this->lcs
];
340 for ($n = 0; $n < $nchunks - 1; $n++
) {
341 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
343 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
345 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
347 return array($this->lcs
, $seps);
350 function _lcs_pos ($ypos) {
352 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
353 $this->seq
[++
$this->lcs
] = $ypos;
354 $this->in_seq
[$ypos] = 1;
359 while ($beg < $end) {
360 $mid = (int)(($beg +
$end) / 2);
361 if ( $ypos > $this->seq
[$mid] )
367 assert($ypos != $this->seq
[$end]);
369 $this->in_seq
[$this->seq
[$end]] = false;
370 $this->seq
[$end] = $ypos;
371 $this->in_seq
[$ypos] = 1;
375 /* Find LCS of two sequences.
377 * The results are recorded in the vectors $this->{x,y}changed[], by
378 * storing a 1 in the element for each line that is an insertion
379 * or deletion (ie. is not in the LCS).
381 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
383 * Note that XLIM, YLIM are exclusive bounds.
384 * All line numbers are origin-0 and discarded lines are not counted.
386 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
387 // Slide down the bottom initial diagonal.
388 while ($xoff < $xlim && $yoff < $ylim
389 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
394 // Slide up the top initial diagonal.
395 while ($xlim > $xoff && $ylim > $yoff
396 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
401 if ($xoff == $xlim ||
$yoff == $ylim)
404 // This is ad hoc but seems to work well.
405 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
406 //$nchunks = max(2,min(8,(int)$nchunks));
407 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
409 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
413 // X and Y sequences have no common subsequence:
415 while ($yoff < $ylim)
416 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
417 while ($xoff < $xlim)
418 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
420 // Use the partitions to split this problem into subproblems.
423 while ($pt2 = next($seps)) {
424 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
430 /* Adjust inserts/deletes of identical lines to join changes
431 * as much as possible.
433 * We do something when a run of changed lines include a
434 * line at one end and has an excluded, identical line at the other.
435 * We are free to choose which identical line is included.
436 * `compareseq' usually chooses the one at the beginning,
437 * but usually it is cleaner to consider the following identical line
438 * to be the "change".
440 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
442 function _shift_boundaries ($lines, &$changed, $other_changed) {
443 wfProfileIn( __METHOD__
);
447 assert('sizeof($lines) == sizeof($changed)');
448 $len = sizeof($lines);
449 $other_len = sizeof($other_changed);
453 * Scan forwards to find beginning of another run of changes.
454 * Also keep track of the corresponding point in the other file.
456 * Throughout this code, $i and $j are adjusted together so that
457 * the first $i elements of $changed and the first $j elements
458 * of $other_changed both contain the same number of zeros
460 * Furthermore, $j is always kept so that $j == $other_len or
461 * $other_changed[$j] == false.
463 while ($j < $other_len && $other_changed[$j])
466 while ($i < $len && ! $changed[$i]) {
467 assert('$j < $other_len && ! $other_changed[$j]');
469 while ($j < $other_len && $other_changed[$j])
478 // Find the end of this run of changes.
479 while (++
$i < $len && $changed[$i])
484 * Record the length of this run of changes, so that
485 * we can later determine whether the run has grown.
487 $runlength = $i - $start;
490 * Move the changed region back, so long as the
491 * previous unchanged line matches the last changed one.
492 * This merges with previous changed regions.
494 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
495 $changed[--$start] = 1;
496 $changed[--$i] = false;
497 while ($start > 0 && $changed[$start - 1])
500 while ($other_changed[--$j])
502 assert('$j >= 0 && !$other_changed[$j]');
506 * Set CORRESPONDING to the end of the changed run, at the last
507 * point where it corresponds to a changed run in the other file.
508 * CORRESPONDING == LEN means no such point has been found.
510 $corresponding = $j < $other_len ?
$i : $len;
513 * Move the changed region forward, so long as the
514 * first changed line matches the following unchanged one.
515 * This merges with following changed regions.
516 * Do this second, so that if there are no merges,
517 * the changed region is moved forward as far as possible.
519 while ($i < $len && $lines[$start] == $lines[$i]) {
520 $changed[$start++
] = false;
522 while ($i < $len && $changed[$i])
525 assert('$j < $other_len && ! $other_changed[$j]');
527 if ($j < $other_len && $other_changed[$j]) {
529 while ($j < $other_len && $other_changed[$j])
533 } while ($runlength != $i - $start);
536 * If possible, move the fully-merged run of changes
537 * back to a corresponding run in the other file.
539 while ($corresponding < $i) {
540 $changed[--$start] = 1;
543 while ($other_changed[--$j])
545 assert('$j >= 0 && !$other_changed[$j]');
548 wfProfileOut( __METHOD__
);
553 * Class representing a 'diff' between two sequences of strings.
556 * @ingroup DifferenceEngine
564 * Computes diff between sequences of strings.
566 * @param $from_lines array An array of strings.
567 * (Typically these are lines from a file.)
568 * @param $to_lines array An array of strings.
570 function Diff($from_lines, $to_lines) {
571 $eng = new _DiffEngine
;
572 $this->edits
= $eng->diff($from_lines, $to_lines);
573 //$this->_check($from_lines, $to_lines);
577 * Compute reversed Diff.
581 * $diff = new Diff($lines1, $lines2);
582 * $rev = $diff->reverse();
583 * @return object A Diff object representing the inverse of the
586 function reverse () {
588 $rev->edits
= array();
589 foreach ($this->edits
as $edit) {
590 $rev->edits
[] = $edit->reverse();
596 * Check for empty diff.
598 * @return bool True iff two sequences were identical.
600 function isEmpty () {
601 foreach ($this->edits
as $edit) {
602 if ($edit->type
!= 'copy')
609 * Compute the length of the Longest Common Subsequence (LCS).
611 * This is mostly for diagnostic purposed.
613 * @return int The length of the LCS.
617 foreach ($this->edits
as $edit) {
618 if ($edit->type
== 'copy')
619 $lcs +
= sizeof($edit->orig
);
625 * Get the original set of lines.
627 * This reconstructs the $from_lines parameter passed to the
630 * @return array The original sequence of strings.
635 foreach ($this->edits
as $edit) {
637 array_splice($lines, sizeof($lines), 0, $edit->orig
);
643 * Get the closing set of lines.
645 * This reconstructs the $to_lines parameter passed to the
648 * @return array The sequence of strings.
653 foreach ($this->edits
as $edit) {
655 array_splice($lines, sizeof($lines), 0, $edit->closing
);
661 * Check a Diff for validity.
663 * This is here only for debugging purposes.
665 function _check ($from_lines, $to_lines) {
666 wfProfileIn( __METHOD__
);
667 if (serialize($from_lines) != serialize($this->orig()))
668 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
669 if (serialize($to_lines) != serialize($this->closing()))
670 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
672 $rev = $this->reverse();
673 if (serialize($to_lines) != serialize($rev->orig()))
674 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
675 if (serialize($from_lines) != serialize($rev->closing()))
676 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
680 foreach ($this->edits
as $edit) {
681 if ( $prevtype == $edit->type
)
682 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
683 $prevtype = $edit->type
;
687 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
688 wfProfileOut( __METHOD__
);
693 * @todo document, bad name.
695 * @ingroup DifferenceEngine
697 class MappedDiff
extends Diff
702 * Computes diff between sequences of strings.
704 * This can be used to compute things like
705 * case-insensitve diffs, or diffs which ignore
706 * changes in white-space.
708 * @param $from_lines array An array of strings.
709 * (Typically these are lines from a file.)
711 * @param $to_lines array An array of strings.
713 * @param $mapped_from_lines array This array should
714 * have the same size number of elements as $from_lines.
715 * The elements in $mapped_from_lines and
716 * $mapped_to_lines are what is actually compared
717 * when computing the diff.
719 * @param $mapped_to_lines array This array should
720 * have the same number of elements as $to_lines.
722 function MappedDiff($from_lines, $to_lines,
723 $mapped_from_lines, $mapped_to_lines) {
724 wfProfileIn( __METHOD__
);
726 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
727 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
729 $this->Diff($mapped_from_lines, $mapped_to_lines);
732 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
733 $orig = &$this->edits
[$i]->orig
;
734 if (is_array($orig)) {
735 $orig = array_slice($from_lines, $xi, sizeof($orig));
736 $xi +
= sizeof($orig);
739 $closing = &$this->edits
[$i]->closing
;
740 if (is_array($closing)) {
741 $closing = array_slice($to_lines, $yi, sizeof($closing));
742 $yi +
= sizeof($closing);
745 wfProfileOut( __METHOD__
);
750 * A class to format Diffs
752 * This class formats the diff in classic diff format.
753 * It is intended that this class be customized via inheritance,
754 * to obtain fancier outputs.
757 * @ingroup DifferenceEngine
759 class DiffFormatter
{
761 * Number of leading context "lines" to preserve.
763 * This should be left at zero for this class, but subclasses
764 * may want to set this to other values.
766 var $leading_context_lines = 0;
769 * Number of trailing context "lines" to preserve.
771 * This should be left at zero for this class, but subclasses
772 * may want to set this to other values.
774 var $trailing_context_lines = 0;
779 * @param $diff object A Diff object.
780 * @return string The formatted output.
782 function format($diff) {
783 wfProfileIn( __METHOD__
);
789 $nlead = $this->leading_context_lines
;
790 $ntrail = $this->trailing_context_lines
;
792 $this->_start_diff();
794 foreach ($diff->edits
as $edit) {
795 if ($edit->type
== 'copy') {
796 if (is_array($block)) {
797 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
802 $context = array_slice($edit->orig
, 0, $ntrail);
803 $block[] = new _DiffOp_Copy($context);
805 $this->_block($x0, $ntrail +
$xi - $x0,
806 $y0, $ntrail +
$yi - $y0,
811 $context = $edit->orig
;
814 if (! is_array($block)) {
815 $context = array_slice($context, sizeof($context) - $nlead);
816 $x0 = $xi - sizeof($context);
817 $y0 = $yi - sizeof($context);
820 $block[] = new _DiffOp_Copy($context);
826 $xi +
= sizeof($edit->orig
);
828 $yi +
= sizeof($edit->closing
);
831 if (is_array($block))
832 $this->_block($x0, $xi - $x0,
836 $end = $this->_end_diff();
837 wfProfileOut( __METHOD__
);
841 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
842 wfProfileIn( __METHOD__
);
843 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
844 foreach ($edits as $edit) {
845 if ($edit->type
== 'copy')
846 $this->_context($edit->orig
);
847 elseif ($edit->type
== 'add')
848 $this->_added($edit->closing
);
849 elseif ($edit->type
== 'delete')
850 $this->_deleted($edit->orig
);
851 elseif ($edit->type
== 'change')
852 $this->_changed($edit->orig
, $edit->closing
);
854 trigger_error('Unknown edit type', E_USER_ERROR
);
857 wfProfileOut( __METHOD__
);
860 function _start_diff() {
864 function _end_diff() {
865 $val = ob_get_contents();
870 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
872 $xbeg .= "," . ($xbeg +
$xlen - 1);
874 $ybeg .= "," . ($ybeg +
$ylen - 1);
876 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
879 function _start_block($header) {
883 function _end_block() {
886 function _lines($lines, $prefix = ' ') {
887 foreach ($lines as $line)
888 echo "$prefix $line\n";
891 function _context($lines) {
892 $this->_lines($lines);
895 function _added($lines) {
896 $this->_lines($lines, '>');
898 function _deleted($lines) {
899 $this->_lines($lines, '<');
902 function _changed($orig, $closing) {
903 $this->_deleted($orig);
905 $this->_added($closing);
910 * A formatter that outputs unified diffs
911 * @ingroup DifferenceEngine
914 class UnifiedDiffFormatter
extends DiffFormatter
{
915 var $leading_context_lines = 2;
916 var $trailing_context_lines = 2;
918 function _added($lines) {
919 $this->_lines($lines, '+');
921 function _deleted($lines) {
922 $this->_lines($lines, '-');
924 function _changed($orig, $closing) {
925 $this->_deleted($orig);
926 $this->_added($closing);
928 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
929 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
934 * A pseudo-formatter that just passes along the Diff::$edits array
935 * @ingroup DifferenceEngine
937 class ArrayDiffFormatter
extends DiffFormatter
{
938 function format($diff) {
942 foreach($diff->edits
as $edit)
943 switch($edit->type
) {
945 foreach($edit->closing
as $l) {
949 'newline' => $newline++
954 foreach($edit->orig
as $l) {
956 'action' => 'delete',
958 'oldline' => $oldline++
,
963 foreach($edit->orig
as $i => $l) {
965 'action' => 'change',
967 'new' => @$edit->closing
[$i],
968 'oldline' => $oldline++
,
969 'newline' => $newline++
,
974 $oldline +
= count($edit->orig
);
975 $newline +
= count($edit->orig
);
982 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
986 define('NBSP', ' '); // iso-8859-x non-breaking space.
991 * @ingroup DifferenceEngine
993 class _HWLDF_WordAccumulator
{
994 function _HWLDF_WordAccumulator () {
995 $this->_lines
= array();
1001 function _flushGroup ($new_tag) {
1002 if ($this->_group
!== '') {
1003 if ($this->_tag
== 'ins')
1004 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1005 htmlspecialchars ( $this->_group
) . '</ins>';
1006 elseif ($this->_tag
== 'del')
1007 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1008 htmlspecialchars ( $this->_group
) . '</del>';
1010 $this->_line
.= htmlspecialchars ( $this->_group
);
1013 $this->_tag
= $new_tag;
1016 function _flushLine ($new_tag) {
1017 $this->_flushGroup($new_tag);
1018 if ($this->_line
!= '')
1019 array_push ( $this->_lines
, $this->_line
);
1021 # make empty lines visible by inserting an NBSP
1022 array_push ( $this->_lines
, NBSP
);
1026 function addWords ($words, $tag = '') {
1027 if ($tag != $this->_tag
)
1028 $this->_flushGroup($tag);
1030 foreach ($words as $word) {
1031 // new-line should only come as first char of word.
1034 if ($word[0] == "\n") {
1035 $this->_flushLine($tag);
1036 $word = substr($word, 1);
1038 assert(!strstr($word, "\n"));
1039 $this->_group
.= $word;
1043 function getLines() {
1044 $this->_flushLine('~done');
1045 return $this->_lines
;
1052 * @ingroup DifferenceEngine
1054 class WordLevelDiff
extends MappedDiff
{
1055 const MAX_LINE_LENGTH
= 10000;
1057 function WordLevelDiff ($orig_lines, $closing_lines) {
1058 wfProfileIn( __METHOD__
);
1060 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1061 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1063 $this->MappedDiff($orig_words, $closing_words,
1064 $orig_stripped, $closing_stripped);
1065 wfProfileOut( __METHOD__
);
1068 function _split($lines) {
1069 wfProfileIn( __METHOD__
);
1072 $stripped = array();
1074 foreach ( $lines as $line ) {
1075 # If the line is too long, just pretend the entire line is one big word
1076 # This prevents resource exhaustion problems
1083 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1085 $stripped[] = $line;
1088 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1091 $words = array_merge( $words, $m[0] );
1092 $stripped = array_merge( $stripped, $m[1] );
1096 wfProfileOut( __METHOD__
);
1097 return array($words, $stripped);
1101 wfProfileIn( __METHOD__
);
1102 $orig = new _HWLDF_WordAccumulator
;
1104 foreach ($this->edits
as $edit) {
1105 if ($edit->type
== 'copy')
1106 $orig->addWords($edit->orig
);
1107 elseif ($edit->orig
)
1108 $orig->addWords($edit->orig
, 'del');
1110 $lines = $orig->getLines();
1111 wfProfileOut( __METHOD__
);
1115 function closing () {
1116 wfProfileIn( __METHOD__
);
1117 $closing = new _HWLDF_WordAccumulator
;
1119 foreach ($this->edits
as $edit) {
1120 if ($edit->type
== 'copy')
1121 $closing->addWords($edit->closing
);
1122 elseif ($edit->closing
)
1123 $closing->addWords($edit->closing
, 'ins');
1125 $lines = $closing->getLines();
1126 wfProfileOut( __METHOD__
);
1132 * Wikipedia Table style diff formatter.
1135 * @ingroup DifferenceEngine
1137 class TableDiffFormatter
extends DiffFormatter
{
1138 function TableDiffFormatter() {
1139 $this->leading_context_lines
= 2;
1140 $this->trailing_context_lines
= 2;
1143 public static function escapeWhiteSpace( $msg ) {
1144 $msg = preg_replace( '/^ /m', '  ', $msg );
1145 $msg = preg_replace( '/ $/m', '  ', $msg );
1146 $msg = preg_replace( '/ /', '  ', $msg );
1150 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1151 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1152 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1156 function _start_block( $header ) {
1160 function _end_block() {
1163 function _lines( $lines, $prefix=' ', $color='white' ) {
1166 # HTML-escape parameter before calling this
1167 function addedLine( $line ) {
1168 return $this->wrapLine( '+', 'diff-addedline', $line );
1171 # HTML-escape parameter before calling this
1172 function deletedLine( $line ) {
1173 return $this->wrapLine( '-', 'diff-deletedline', $line );
1176 # HTML-escape parameter before calling this
1177 function contextLine( $line ) {
1178 return $this->wrapLine( ' ', 'diff-context', $line );
1181 private function wrapLine( $marker, $class, $line ) {
1182 if( $line !== '' ) {
1183 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1184 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1186 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1189 function emptyLine() {
1190 return '<td colspan="2"> </td>';
1193 function _added( $lines ) {
1194 foreach ($lines as $line) {
1195 echo '<tr>' . $this->emptyLine() .
1196 $this->addedLine( '<ins class="diffchange">' .
1197 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1201 function _deleted($lines) {
1202 foreach ($lines as $line) {
1203 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1204 htmlspecialchars ( $line ) . '</del>' ) .
1205 $this->emptyLine() . "</tr>\n";
1209 function _context( $lines ) {
1210 foreach ($lines as $line) {
1212 $this->contextLine( htmlspecialchars ( $line ) ) .
1213 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1217 function _changed( $orig, $closing ) {
1218 wfProfileIn( __METHOD__
);
1220 $diff = new WordLevelDiff( $orig, $closing );
1221 $del = $diff->orig();
1222 $add = $diff->closing();
1224 # Notice that WordLevelDiff returns HTML-escaped output.
1225 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1227 while ( $line = array_shift( $del ) ) {
1228 $aline = array_shift( $add );
1229 echo '<tr>' . $this->deletedLine( $line ) .
1230 $this->addedLine( $aline ) . "</tr>\n";
1232 foreach ($add as $line) { # If any leftovers
1233 echo '<tr>' . $this->emptyLine() .
1234 $this->addedLine( $line ) . "</tr>\n";
1236 wfProfileOut( __METHOD__
);