3 * A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
5 * Copyright © 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
6 * You may copy this code freely under the conditions of the GPL.
9 * @ingroup DifferenceEngine
10 * @defgroup DifferenceEngine DifferenceEngine
16 * @ingroup DifferenceEngine
24 trigger_error('pure virtual', E_USER_ERROR
);
28 return $this->orig ?
sizeof($this->orig
) : 0;
32 return $this->closing ?
sizeof($this->closing
) : 0;
39 * @ingroup DifferenceEngine
41 class _DiffOp_Copy
extends _DiffOp
{
44 function __construct ($orig, $closing = false) {
45 if (!is_array($closing))
48 $this->closing
= $closing;
52 return new _DiffOp_Copy($this->closing
, $this->orig
);
59 * @ingroup DifferenceEngine
61 class _DiffOp_Delete
extends _DiffOp
{
64 function __construct ($lines) {
66 $this->closing
= false;
70 return new _DiffOp_Add($this->orig
);
77 * @ingroup DifferenceEngine
79 class _DiffOp_Add
extends _DiffOp
{
82 function __construct ($lines) {
83 $this->closing
= $lines;
88 return new _DiffOp_Delete($this->closing
);
95 * @ingroup DifferenceEngine
97 class _DiffOp_Change
extends _DiffOp
{
100 function __construct ($orig, $closing) {
102 $this->closing
= $closing;
106 return new _DiffOp_Change($this->closing
, $this->orig
);
111 * Class used internally by Diff to actually compute the diffs.
113 * The algorithm used here is mostly lifted from the perl module
114 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
115 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
117 * More ideas are taken from:
118 * http://www.ics.uci.edu/~eppstein/161/960229.html
120 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
121 * diffutils-2.7, which can be found at:
122 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
124 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
127 * Line length limits for robustness added by Tim Starling, 2005-08-31
128 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
130 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
132 * @ingroup DifferenceEngine
136 const MAX_XREF_LENGTH
= 10000;
138 function diff ($from_lines, $to_lines){
139 wfProfileIn( __METHOD__
);
141 // Diff and store locally
142 $this->diff_local($from_lines, $to_lines);
144 // Merge edits when possible
145 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
146 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
148 // Compute the edit operations.
149 $n_from = sizeof($from_lines);
150 $n_to = sizeof($to_lines);
154 while ($xi < $n_from ||
$yi < $n_to) {
155 assert($yi < $n_to ||
$this->xchanged
[$xi]);
156 assert($xi < $n_from ||
$this->ychanged
[$yi]);
158 // Skip matching "snake".
160 while ( $xi < $n_from && $yi < $n_to
161 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
162 $copy[] = $from_lines[$xi++
];
166 $edits[] = new _DiffOp_Copy($copy);
168 // Find deletes & adds.
170 while ($xi < $n_from && $this->xchanged
[$xi])
171 $delete[] = $from_lines[$xi++
];
174 while ($yi < $n_to && $this->ychanged
[$yi])
175 $add[] = $to_lines[$yi++
];
178 $edits[] = new _DiffOp_Change($delete, $add);
180 $edits[] = new _DiffOp_Delete($delete);
182 $edits[] = new _DiffOp_Add($add);
184 wfProfileOut( __METHOD__
);
188 function diff_local ($from_lines, $to_lines) {
189 global $wgExternalDiffEngine;
190 wfProfileIn( __METHOD__
);
192 if($wgExternalDiffEngine == 'wikidiff3'){
194 $wikidiff3 = new WikiDiff3();
195 $wikidiff3->diff($from_lines, $to_lines);
196 $this->xchanged
= $wikidiff3->removed
;
197 $this->ychanged
= $wikidiff3->added
;
201 $n_from = sizeof($from_lines);
202 $n_to = sizeof($to_lines);
203 $this->xchanged
= $this->ychanged
= array();
204 $this->xv
= $this->yv
= array();
205 $this->xind
= $this->yind
= array();
207 unset($this->in_seq
);
210 // Skip leading common lines.
211 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
212 if ($from_lines[$skip] !== $to_lines[$skip])
214 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
216 // Skip trailing common lines.
217 $xi = $n_from; $yi = $n_to;
218 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
219 if ($from_lines[$xi] !== $to_lines[$yi])
221 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
224 // Ignore lines which do not exist in both files.
225 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
226 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
229 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
230 $line = $to_lines[$yi];
231 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
233 $yhash[$this->_line_hash($line)] = 1;
237 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
238 $line = $from_lines[$xi];
239 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
246 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
248 wfProfileOut( __METHOD__
);
252 * Returns the whole line if it's small enough, or the MD5 hash otherwise
254 function _line_hash( $line ) {
255 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
262 /* Divide the Largest Common Subsequence (LCS) of the sequences
263 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
266 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
267 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
268 * sub sequences. The first sub-sequence is contained in [X0, X1),
269 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
270 * that (X0, Y0) == (XOFF, YOFF) and
271 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
273 * This function assumes that the first lines of the specified portions
274 * of the two files do not match, and likewise that the last lines do not
275 * match. The caller must trim matching lines from the beginning and end
276 * of the portions it is going to specify.
278 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
281 if ($xlim - $xoff > $ylim - $yoff) {
282 // Things seems faster (I'm not sure I understand why)
283 // when the shortest sequence in X.
285 list ($xoff, $xlim, $yoff, $ylim)
286 = array( $yoff, $ylim, $xoff, $xlim);
290 for ($i = $ylim - 1; $i >= $yoff; $i--)
291 $ymatches[$this->xv
[$i]][] = $i;
293 for ($i = $ylim - 1; $i >= $yoff; $i--)
294 $ymatches[$this->yv
[$i]][] = $i;
297 $this->seq
[0]= $yoff - 1;
298 $this->in_seq
= array();
301 $numer = $xlim - $xoff +
$nchunks - 1;
303 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
305 for ($i = 0; $i <= $this->lcs
; $i++
)
306 $ymids[$i][$chunk-1] = $this->seq
[$i];
308 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
309 for ( ; $x < $x1; $x++
) {
310 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
311 if (empty($ymatches[$line]))
313 $matches = $ymatches[$line];
315 while ( list( $junk, $y ) = each( $matches ) ) {
316 if ( empty( $this->in_seq
[$y] ) ) {
317 $k = $this->_lcs_pos( $y );
319 $ymids[$k] = $ymids[$k-1];
323 while (list ( /* $junk */, $y) = each($matches)) {
324 if ($y > $this->seq
[$k-1]) {
325 assert($y < $this->seq
[$k]);
326 // Optimization: this is a common case:
327 // next match is just replacing previous match.
328 $this->in_seq
[$this->seq
[$k]] = false;
330 $this->in_seq
[$y] = 1;
331 } else if (empty($this->in_seq
[$y])) {
332 $k = $this->_lcs_pos($y);
334 $ymids[$k] = $ymids[$k-1];
340 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
341 $ymid = $ymids[$this->lcs
];
342 for ($n = 0; $n < $nchunks - 1; $n++
) {
343 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
345 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
347 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
349 return array($this->lcs
, $seps);
352 function _lcs_pos ($ypos) {
354 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
355 $this->seq
[++
$this->lcs
] = $ypos;
356 $this->in_seq
[$ypos] = 1;
361 while ($beg < $end) {
362 $mid = (int)(($beg +
$end) / 2);
363 if ( $ypos > $this->seq
[$mid] )
369 assert($ypos != $this->seq
[$end]);
371 $this->in_seq
[$this->seq
[$end]] = false;
372 $this->seq
[$end] = $ypos;
373 $this->in_seq
[$ypos] = 1;
377 /* Find LCS of two sequences.
379 * The results are recorded in the vectors $this->{x,y}changed[], by
380 * storing a 1 in the element for each line that is an insertion
381 * or deletion (ie. is not in the LCS).
383 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
385 * Note that XLIM, YLIM are exclusive bounds.
386 * All line numbers are origin-0 and discarded lines are not counted.
388 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
389 // Slide down the bottom initial diagonal.
390 while ($xoff < $xlim && $yoff < $ylim
391 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
396 // Slide up the top initial diagonal.
397 while ($xlim > $xoff && $ylim > $yoff
398 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
403 if ($xoff == $xlim ||
$yoff == $ylim)
406 // This is ad hoc but seems to work well.
407 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
408 //$nchunks = max(2,min(8,(int)$nchunks));
409 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
411 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
415 // X and Y sequences have no common subsequence:
417 while ($yoff < $ylim)
418 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
419 while ($xoff < $xlim)
420 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
422 // Use the partitions to split this problem into subproblems.
425 while ($pt2 = next($seps)) {
426 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
432 /* Adjust inserts/deletes of identical lines to join changes
433 * as much as possible.
435 * We do something when a run of changed lines include a
436 * line at one end and has an excluded, identical line at the other.
437 * We are free to choose which identical line is included.
438 * `compareseq' usually chooses the one at the beginning,
439 * but usually it is cleaner to consider the following identical line
440 * to be the "change".
442 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
444 function _shift_boundaries ($lines, &$changed, $other_changed) {
445 wfProfileIn( __METHOD__
);
449 assert('sizeof($lines) == sizeof($changed)');
450 $len = sizeof($lines);
451 $other_len = sizeof($other_changed);
455 * Scan forwards to find beginning of another run of changes.
456 * Also keep track of the corresponding point in the other file.
458 * Throughout this code, $i and $j are adjusted together so that
459 * the first $i elements of $changed and the first $j elements
460 * of $other_changed both contain the same number of zeros
462 * Furthermore, $j is always kept so that $j == $other_len or
463 * $other_changed[$j] == false.
465 while ($j < $other_len && $other_changed[$j])
468 while ($i < $len && ! $changed[$i]) {
469 assert('$j < $other_len && ! $other_changed[$j]');
471 while ($j < $other_len && $other_changed[$j])
480 // Find the end of this run of changes.
481 while (++
$i < $len && $changed[$i])
486 * Record the length of this run of changes, so that
487 * we can later determine whether the run has grown.
489 $runlength = $i - $start;
492 * Move the changed region back, so long as the
493 * previous unchanged line matches the last changed one.
494 * This merges with previous changed regions.
496 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
497 $changed[--$start] = 1;
498 $changed[--$i] = false;
499 while ($start > 0 && $changed[$start - 1])
502 while ($other_changed[--$j])
504 assert('$j >= 0 && !$other_changed[$j]');
508 * Set CORRESPONDING to the end of the changed run, at the last
509 * point where it corresponds to a changed run in the other file.
510 * CORRESPONDING == LEN means no such point has been found.
512 $corresponding = $j < $other_len ?
$i : $len;
515 * Move the changed region forward, so long as the
516 * first changed line matches the following unchanged one.
517 * This merges with following changed regions.
518 * Do this second, so that if there are no merges,
519 * the changed region is moved forward as far as possible.
521 while ($i < $len && $lines[$start] == $lines[$i]) {
522 $changed[$start++
] = false;
524 while ($i < $len && $changed[$i])
527 assert('$j < $other_len && ! $other_changed[$j]');
529 if ($j < $other_len && $other_changed[$j]) {
531 while ($j < $other_len && $other_changed[$j])
535 } while ($runlength != $i - $start);
538 * If possible, move the fully-merged run of changes
539 * back to a corresponding run in the other file.
541 while ($corresponding < $i) {
542 $changed[--$start] = 1;
545 while ($other_changed[--$j])
547 assert('$j >= 0 && !$other_changed[$j]');
550 wfProfileOut( __METHOD__
);
555 * Class representing a 'diff' between two sequences of strings.
558 * @ingroup DifferenceEngine
566 * Computes diff between sequences of strings.
568 * @param $from_lines array An array of strings.
569 * (Typically these are lines from a file.)
570 * @param $to_lines array An array of strings.
572 function __construct($from_lines, $to_lines) {
573 $eng = new _DiffEngine
;
574 $this->edits
= $eng->diff($from_lines, $to_lines);
575 //$this->_check($from_lines, $to_lines);
579 * Compute reversed Diff.
583 * $diff = new Diff($lines1, $lines2);
584 * $rev = $diff->reverse();
585 * @return object A Diff object representing the inverse of the
588 function reverse () {
590 $rev->edits
= array();
591 foreach ($this->edits
as $edit) {
592 $rev->edits
[] = $edit->reverse();
598 * Check for empty diff.
600 * @return bool True iff two sequences were identical.
602 function isEmpty () {
603 foreach ($this->edits
as $edit) {
604 if ($edit->type
!= 'copy')
611 * Compute the length of the Longest Common Subsequence (LCS).
613 * This is mostly for diagnostic purposed.
615 * @return int The length of the LCS.
619 foreach ($this->edits
as $edit) {
620 if ($edit->type
== 'copy')
621 $lcs +
= sizeof($edit->orig
);
627 * Get the original set of lines.
629 * This reconstructs the $from_lines parameter passed to the
632 * @return array The original sequence of strings.
637 foreach ($this->edits
as $edit) {
639 array_splice($lines, sizeof($lines), 0, $edit->orig
);
645 * Get the closing set of lines.
647 * This reconstructs the $to_lines parameter passed to the
650 * @return array The sequence of strings.
655 foreach ($this->edits
as $edit) {
657 array_splice($lines, sizeof($lines), 0, $edit->closing
);
663 * Check a Diff for validity.
665 * This is here only for debugging purposes.
667 function _check ($from_lines, $to_lines) {
668 wfProfileIn( __METHOD__
);
669 if (serialize($from_lines) != serialize($this->orig()))
670 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
671 if (serialize($to_lines) != serialize($this->closing()))
672 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
674 $rev = $this->reverse();
675 if (serialize($to_lines) != serialize($rev->orig()))
676 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
677 if (serialize($from_lines) != serialize($rev->closing()))
678 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
682 foreach ($this->edits
as $edit) {
683 if ( $prevtype == $edit->type
)
684 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
685 $prevtype = $edit->type
;
689 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
690 wfProfileOut( __METHOD__
);
695 * @todo document, bad name.
697 * @ingroup DifferenceEngine
699 class MappedDiff
extends Diff
704 * Computes diff between sequences of strings.
706 * This can be used to compute things like
707 * case-insensitve diffs, or diffs which ignore
708 * changes in white-space.
710 * @param $from_lines array An array of strings.
711 * (Typically these are lines from a file.)
713 * @param $to_lines array An array of strings.
715 * @param $mapped_from_lines array This array should
716 * have the same size number of elements as $from_lines.
717 * The elements in $mapped_from_lines and
718 * $mapped_to_lines are what is actually compared
719 * when computing the diff.
721 * @param $mapped_to_lines array This array should
722 * have the same number of elements as $to_lines.
724 function __construct($from_lines, $to_lines,
725 $mapped_from_lines, $mapped_to_lines) {
726 wfProfileIn( __METHOD__
);
728 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
729 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
731 parent
::__construct($mapped_from_lines, $mapped_to_lines);
734 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
735 $orig = &$this->edits
[$i]->orig
;
736 if (is_array($orig)) {
737 $orig = array_slice($from_lines, $xi, sizeof($orig));
738 $xi +
= sizeof($orig);
741 $closing = &$this->edits
[$i]->closing
;
742 if (is_array($closing)) {
743 $closing = array_slice($to_lines, $yi, sizeof($closing));
744 $yi +
= sizeof($closing);
747 wfProfileOut( __METHOD__
);
752 * A class to format Diffs
754 * This class formats the diff in classic diff format.
755 * It is intended that this class be customized via inheritance,
756 * to obtain fancier outputs.
759 * @ingroup DifferenceEngine
761 class DiffFormatter
{
763 * Number of leading context "lines" to preserve.
765 * This should be left at zero for this class, but subclasses
766 * may want to set this to other values.
768 var $leading_context_lines = 0;
771 * Number of trailing context "lines" to preserve.
773 * This should be left at zero for this class, but subclasses
774 * may want to set this to other values.
776 var $trailing_context_lines = 0;
781 * @param $diff object A Diff object.
782 * @return string The formatted output.
784 function format($diff) {
785 wfProfileIn( __METHOD__
);
791 $nlead = $this->leading_context_lines
;
792 $ntrail = $this->trailing_context_lines
;
794 $this->_start_diff();
796 foreach ($diff->edits
as $edit) {
797 if ($edit->type
== 'copy') {
798 if (is_array($block)) {
799 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
804 $context = array_slice($edit->orig
, 0, $ntrail);
805 $block[] = new _DiffOp_Copy($context);
807 $this->_block($x0, $ntrail +
$xi - $x0,
808 $y0, $ntrail +
$yi - $y0,
813 $context = $edit->orig
;
816 if (! is_array($block)) {
817 $context = array_slice($context, sizeof($context) - $nlead);
818 $x0 = $xi - sizeof($context);
819 $y0 = $yi - sizeof($context);
822 $block[] = new _DiffOp_Copy($context);
828 $xi +
= sizeof($edit->orig
);
830 $yi +
= sizeof($edit->closing
);
833 if (is_array($block))
834 $this->_block($x0, $xi - $x0,
838 $end = $this->_end_diff();
839 wfProfileOut( __METHOD__
);
843 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
844 wfProfileIn( __METHOD__
);
845 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
846 foreach ($edits as $edit) {
847 if ($edit->type
== 'copy')
848 $this->_context($edit->orig
);
849 elseif ($edit->type
== 'add')
850 $this->_added($edit->closing
);
851 elseif ($edit->type
== 'delete')
852 $this->_deleted($edit->orig
);
853 elseif ($edit->type
== 'change')
854 $this->_changed($edit->orig
, $edit->closing
);
856 trigger_error('Unknown edit type', E_USER_ERROR
);
859 wfProfileOut( __METHOD__
);
862 function _start_diff() {
866 function _end_diff() {
867 $val = ob_get_contents();
872 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
874 $xbeg .= "," . ($xbeg +
$xlen - 1);
876 $ybeg .= "," . ($ybeg +
$ylen - 1);
878 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
881 function _start_block($header) {
885 function _end_block() {
888 function _lines($lines, $prefix = ' ') {
889 foreach ($lines as $line)
890 echo "$prefix $line\n";
893 function _context($lines) {
894 $this->_lines($lines);
897 function _added($lines) {
898 $this->_lines($lines, '>');
900 function _deleted($lines) {
901 $this->_lines($lines, '<');
904 function _changed($orig, $closing) {
905 $this->_deleted($orig);
907 $this->_added($closing);
912 * A formatter that outputs unified diffs
913 * @ingroup DifferenceEngine
916 class UnifiedDiffFormatter
extends DiffFormatter
{
917 var $leading_context_lines = 2;
918 var $trailing_context_lines = 2;
920 function _added($lines) {
921 $this->_lines($lines, '+');
923 function _deleted($lines) {
924 $this->_lines($lines, '-');
926 function _changed($orig, $closing) {
927 $this->_deleted($orig);
928 $this->_added($closing);
930 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
931 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
936 * A pseudo-formatter that just passes along the Diff::$edits array
937 * @ingroup DifferenceEngine
939 class ArrayDiffFormatter
extends DiffFormatter
{
940 function format($diff) {
944 foreach($diff->edits
as $edit)
945 switch($edit->type
) {
947 foreach($edit->closing
as $l) {
951 'newline' => $newline++
956 foreach($edit->orig
as $l) {
958 'action' => 'delete',
960 'oldline' => $oldline++
,
965 foreach($edit->orig
as $i => $l) {
967 'action' => 'change',
969 'new' => @$edit->closing
[$i],
970 'oldline' => $oldline++
,
971 'newline' => $newline++
,
976 $oldline +
= count($edit->orig
);
977 $newline +
= count($edit->orig
);
984 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
988 define('NBSP', ' '); // iso-8859-x non-breaking space.
993 * @ingroup DifferenceEngine
995 class _HWLDF_WordAccumulator
{
996 function __construct () {
997 $this->_lines
= array();
1003 function _flushGroup ($new_tag) {
1004 if ($this->_group
!== '') {
1005 if ($this->_tag
== 'ins')
1006 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1007 htmlspecialchars ( $this->_group
) . '</ins>';
1008 elseif ($this->_tag
== 'del')
1009 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1010 htmlspecialchars ( $this->_group
) . '</del>';
1012 $this->_line
.= htmlspecialchars ( $this->_group
);
1015 $this->_tag
= $new_tag;
1018 function _flushLine ($new_tag) {
1019 $this->_flushGroup($new_tag);
1020 if ($this->_line
!= '')
1021 array_push ( $this->_lines
, $this->_line
);
1023 # make empty lines visible by inserting an NBSP
1024 array_push ( $this->_lines
, NBSP
);
1028 function addWords ($words, $tag = '') {
1029 if ($tag != $this->_tag
)
1030 $this->_flushGroup($tag);
1032 foreach ($words as $word) {
1033 // new-line should only come as first char of word.
1036 if ($word[0] == "\n") {
1037 $this->_flushLine($tag);
1038 $word = substr($word, 1);
1040 assert(!strstr($word, "\n"));
1041 $this->_group
.= $word;
1045 function getLines() {
1046 $this->_flushLine('~done');
1047 return $this->_lines
;
1054 * @ingroup DifferenceEngine
1056 class WordLevelDiff
extends MappedDiff
{
1057 const MAX_LINE_LENGTH
= 10000;
1059 function __construct ($orig_lines, $closing_lines) {
1060 wfProfileIn( __METHOD__
);
1062 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1063 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1065 parent
::__construct($orig_words, $closing_words,
1066 $orig_stripped, $closing_stripped);
1067 wfProfileOut( __METHOD__
);
1070 function _split($lines) {
1071 wfProfileIn( __METHOD__
);
1074 $stripped = array();
1076 foreach ( $lines as $line ) {
1077 # If the line is too long, just pretend the entire line is one big word
1078 # This prevents resource exhaustion problems
1085 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1087 $stripped[] = $line;
1090 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1093 $words = array_merge( $words, $m[0] );
1094 $stripped = array_merge( $stripped, $m[1] );
1098 wfProfileOut( __METHOD__
);
1099 return array($words, $stripped);
1103 wfProfileIn( __METHOD__
);
1104 $orig = new _HWLDF_WordAccumulator
;
1106 foreach ($this->edits
as $edit) {
1107 if ($edit->type
== 'copy')
1108 $orig->addWords($edit->orig
);
1109 elseif ($edit->orig
)
1110 $orig->addWords($edit->orig
, 'del');
1112 $lines = $orig->getLines();
1113 wfProfileOut( __METHOD__
);
1117 function closing () {
1118 wfProfileIn( __METHOD__
);
1119 $closing = new _HWLDF_WordAccumulator
;
1121 foreach ($this->edits
as $edit) {
1122 if ($edit->type
== 'copy')
1123 $closing->addWords($edit->closing
);
1124 elseif ($edit->closing
)
1125 $closing->addWords($edit->closing
, 'ins');
1127 $lines = $closing->getLines();
1128 wfProfileOut( __METHOD__
);
1134 * Wikipedia Table style diff formatter.
1137 * @ingroup DifferenceEngine
1139 class TableDiffFormatter
extends DiffFormatter
{
1140 function __construct() {
1141 $this->leading_context_lines
= 2;
1142 $this->trailing_context_lines
= 2;
1145 public static function escapeWhiteSpace( $msg ) {
1146 $msg = preg_replace( '/^ /m', '  ', $msg );
1147 $msg = preg_replace( '/ $/m', '  ', $msg );
1148 $msg = preg_replace( '/ /', '  ', $msg );
1152 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1153 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1154 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1158 function _start_block( $header ) {
1162 function _end_block() {
1165 function _lines( $lines, $prefix=' ', $color='white' ) {
1168 # HTML-escape parameter before calling this
1169 function addedLine( $line ) {
1170 return $this->wrapLine( '+', 'diff-addedline', $line );
1173 # HTML-escape parameter before calling this
1174 function deletedLine( $line ) {
1175 return $this->wrapLine( '−', 'diff-deletedline', $line );
1178 # HTML-escape parameter before calling this
1179 function contextLine( $line ) {
1180 return $this->wrapLine( ' ', 'diff-context', $line );
1183 private function wrapLine( $marker, $class, $line ) {
1184 if( $line !== '' ) {
1185 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1186 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1188 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1191 function emptyLine() {
1192 return '<td colspan="2"> </td>';
1195 function _added( $lines ) {
1196 foreach ($lines as $line) {
1197 echo '<tr>' . $this->emptyLine() .
1198 $this->addedLine( '<ins class="diffchange">' .
1199 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1203 function _deleted($lines) {
1204 foreach ($lines as $line) {
1205 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1206 htmlspecialchars ( $line ) . '</del>' ) .
1207 $this->emptyLine() . "</tr>\n";
1211 function _context( $lines ) {
1212 foreach ($lines as $line) {
1214 $this->contextLine( htmlspecialchars ( $line ) ) .
1215 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1219 function _changed( $orig, $closing ) {
1220 wfProfileIn( __METHOD__
);
1222 $diff = new WordLevelDiff( $orig, $closing );
1223 $del = $diff->orig();
1224 $add = $diff->closing();
1226 # Notice that WordLevelDiff returns HTML-escaped output.
1227 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1229 while ( $line = array_shift( $del ) ) {
1230 $aline = array_shift( $add );
1231 echo '<tr>' . $this->deletedLine( $line ) .
1232 $this->addedLine( $aline ) . "</tr>\n";
1234 foreach ($add as $line) { # If any leftovers
1235 echo '<tr>' . $this->emptyLine() .
1236 $this->addedLine( $line ) . "</tr>\n";
1238 wfProfileOut( __METHOD__
);