Release 2015-08-10 "Detritus"
[dokuwiki.git] / inc / DifferenceEngine.php
blob210d1c0eb9a0ecc84108eedb8efd3b7cfe9705db
1 <?php
2 /**
3 * A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
5 * Additions by Axel Boldt for MediaWiki
7 * @copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
8 * @license You may copy this code freely under the conditions of the GPL.
9 */
10 define('USE_ASSERTS', function_exists('assert'));
12 class _DiffOp {
13 var $type;
14 var $orig;
15 var $closing;
17 /**
18 * @return _DiffOp
20 function reverse() {
21 trigger_error("pure virtual", E_USER_ERROR);
24 function norig() {
25 return $this->orig ? count($this->orig) : 0;
28 function nclosing() {
29 return $this->closing ? count($this->closing) : 0;
33 class _DiffOp_Copy extends _DiffOp {
34 var $type = 'copy';
36 function __construct($orig, $closing = false) {
37 if (!is_array($closing))
38 $closing = $orig;
39 $this->orig = $orig;
40 $this->closing = $closing;
43 function reverse() {
44 return new _DiffOp_Copy($this->closing, $this->orig);
48 class _DiffOp_Delete extends _DiffOp {
49 var $type = 'delete';
51 function __construct($lines) {
52 $this->orig = $lines;
53 $this->closing = false;
56 function reverse() {
57 return new _DiffOp_Add($this->orig);
61 class _DiffOp_Add extends _DiffOp {
62 var $type = 'add';
64 function __construct($lines) {
65 $this->closing = $lines;
66 $this->orig = false;
69 function reverse() {
70 return new _DiffOp_Delete($this->closing);
74 class _DiffOp_Change extends _DiffOp {
75 var $type = 'change';
77 function __construct($orig, $closing) {
78 $this->orig = $orig;
79 $this->closing = $closing;
82 function reverse() {
83 return new _DiffOp_Change($this->closing, $this->orig);
88 /**
89 * Class used internally by Diff to actually compute the diffs.
91 * The algorithm used here is mostly lifted from the perl module
92 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
93 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
95 * More ideas are taken from:
96 * http://www.ics.uci.edu/~eppstein/161/960229.html
98 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
99 * diffutils-2.7, which can be found at:
100 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
102 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
103 * are my own.
105 * @author Geoffrey T. Dairiki
106 * @access private
108 class _DiffEngine {
110 var $xchanged = array();
111 var $ychanged = array();
112 var $xv = array();
113 var $yv = array();
114 var $xind = array();
115 var $yind = array();
116 var $seq;
117 var $in_seq;
118 var $lcs;
121 * @param array $from_lines
122 * @param array $to_lines
123 * @return _DiffOp[]
125 function diff($from_lines, $to_lines) {
126 $n_from = count($from_lines);
127 $n_to = count($to_lines);
129 $this->xchanged = $this->ychanged = array();
130 $this->xv = $this->yv = array();
131 $this->xind = $this->yind = array();
132 unset($this->seq);
133 unset($this->in_seq);
134 unset($this->lcs);
136 // Skip leading common lines.
137 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
138 if ($from_lines[$skip] != $to_lines[$skip])
139 break;
140 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
142 // Skip trailing common lines.
143 $xi = $n_from;
144 $yi = $n_to;
145 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
146 if ($from_lines[$xi] != $to_lines[$yi])
147 break;
148 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
151 // Ignore lines which do not exist in both files.
152 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
153 $xhash[$from_lines[$xi]] = 1;
154 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
155 $line = $to_lines[$yi];
156 if (($this->ychanged[$yi] = empty($xhash[$line])))
157 continue;
158 $yhash[$line] = 1;
159 $this->yv[] = $line;
160 $this->yind[] = $yi;
162 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
163 $line = $from_lines[$xi];
164 if (($this->xchanged[$xi] = empty($yhash[$line])))
165 continue;
166 $this->xv[] = $line;
167 $this->xind[] = $xi;
170 // Find the LCS.
171 $this->_compareseq(0, count($this->xv), 0, count($this->yv));
173 // Merge edits when possible
174 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
175 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
177 // Compute the edit operations.
178 $edits = array();
179 $xi = $yi = 0;
180 while ($xi < $n_from || $yi < $n_to) {
181 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
182 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
184 // Skip matching "snake".
185 $copy = array();
186 while ($xi < $n_from && $yi < $n_to && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
187 $copy[] = $from_lines[$xi++];
188 ++$yi;
190 if ($copy)
191 $edits[] = new _DiffOp_Copy($copy);
193 // Find deletes & adds.
194 $delete = array();
195 while ($xi < $n_from && $this->xchanged[$xi])
196 $delete[] = $from_lines[$xi++];
198 $add = array();
199 while ($yi < $n_to && $this->ychanged[$yi])
200 $add[] = $to_lines[$yi++];
202 if ($delete && $add)
203 $edits[] = new _DiffOp_Change($delete, $add);
204 elseif ($delete)
205 $edits[] = new _DiffOp_Delete($delete);
206 elseif ($add)
207 $edits[] = new _DiffOp_Add($add);
209 return $edits;
214 * Divide the Largest Common Subsequence (LCS) of the sequences
215 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
216 * sized segments.
218 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
219 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
220 * sub sequences. The first sub-sequence is contained in [X0, X1),
221 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
222 * that (X0, Y0) == (XOFF, YOFF) and
223 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
225 * This function assumes that the first lines of the specified portions
226 * of the two files do not match, and likewise that the last lines do not
227 * match. The caller must trim matching lines from the beginning and end
228 * of the portions it is going to specify.
230 function _diag($xoff, $xlim, $yoff, $ylim, $nchunks) {
231 $flip = false;
233 if ($xlim - $xoff > $ylim - $yoff) {
234 // Things seems faster (I'm not sure I understand why)
235 // when the shortest sequence in X.
236 $flip = true;
237 list ($xoff, $xlim, $yoff, $ylim) = array($yoff, $ylim, $xoff, $xlim);
240 if ($flip)
241 for ($i = $ylim - 1; $i >= $yoff; $i--)
242 $ymatches[$this->xv[$i]][] = $i;
243 else
244 for ($i = $ylim - 1; $i >= $yoff; $i--)
245 $ymatches[$this->yv[$i]][] = $i;
247 $this->lcs = 0;
248 $this->seq[0]= $yoff - 1;
249 $this->in_seq = array();
250 $ymids[0] = array();
252 $numer = $xlim - $xoff + $nchunks - 1;
253 $x = $xoff;
254 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
255 if ($chunk > 0)
256 for ($i = 0; $i <= $this->lcs; $i++)
257 $ymids[$i][$chunk-1] = $this->seq[$i];
259 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
260 for ( ; $x < $x1; $x++) {
261 $line = $flip ? $this->yv[$x] : $this->xv[$x];
262 if (empty($ymatches[$line]))
263 continue;
264 $matches = $ymatches[$line];
265 reset($matches);
266 while (list ($junk, $y) = each($matches))
267 if (empty($this->in_seq[$y])) {
268 $k = $this->_lcs_pos($y);
269 USE_ASSERTS && assert($k > 0);
270 $ymids[$k] = $ymids[$k-1];
271 break;
273 while (list ($junk, $y) = each($matches)) {
274 if ($y > $this->seq[$k-1]) {
275 USE_ASSERTS && assert($y < $this->seq[$k]);
276 // Optimization: this is a common case:
277 // next match is just replacing previous match.
278 $this->in_seq[$this->seq[$k]] = false;
279 $this->seq[$k] = $y;
280 $this->in_seq[$y] = 1;
282 else if (empty($this->in_seq[$y])) {
283 $k = $this->_lcs_pos($y);
284 USE_ASSERTS && assert($k > 0);
285 $ymids[$k] = $ymids[$k-1];
291 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
292 $ymid = $ymids[$this->lcs];
293 for ($n = 0; $n < $nchunks - 1; $n++) {
294 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
295 $y1 = $ymid[$n] + 1;
296 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
298 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
300 return array($this->lcs, $seps);
303 function _lcs_pos($ypos) {
304 $end = $this->lcs;
305 if ($end == 0 || $ypos > $this->seq[$end]) {
306 $this->seq[++$this->lcs] = $ypos;
307 $this->in_seq[$ypos] = 1;
308 return $this->lcs;
311 $beg = 1;
312 while ($beg < $end) {
313 $mid = (int)(($beg + $end) / 2);
314 if ($ypos > $this->seq[$mid])
315 $beg = $mid + 1;
316 else
317 $end = $mid;
320 USE_ASSERTS && assert($ypos != $this->seq[$end]);
322 $this->in_seq[$this->seq[$end]] = false;
323 $this->seq[$end] = $ypos;
324 $this->in_seq[$ypos] = 1;
325 return $end;
329 * Find LCS of two sequences.
331 * The results are recorded in the vectors $this->{x,y}changed[], by
332 * storing a 1 in the element for each line that is an insertion
333 * or deletion (ie. is not in the LCS).
335 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
337 * Note that XLIM, YLIM are exclusive bounds.
338 * All line numbers are origin-0 and discarded lines are not counted.
340 function _compareseq($xoff, $xlim, $yoff, $ylim) {
341 // Slide down the bottom initial diagonal.
342 while ($xoff < $xlim && $yoff < $ylim && $this->xv[$xoff] == $this->yv[$yoff]) {
343 ++$xoff;
344 ++$yoff;
347 // Slide up the top initial diagonal.
348 while ($xlim > $xoff && $ylim > $yoff && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
349 --$xlim;
350 --$ylim;
353 if ($xoff == $xlim || $yoff == $ylim)
354 $lcs = 0;
355 else {
356 // This is ad hoc but seems to work well.
357 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
358 //$nchunks = max(2,min(8,(int)$nchunks));
359 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
360 list ($lcs, $seps)
361 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
364 if ($lcs == 0) {
365 // X and Y sequences have no common subsequence:
366 // mark all changed.
367 while ($yoff < $ylim)
368 $this->ychanged[$this->yind[$yoff++]] = 1;
369 while ($xoff < $xlim)
370 $this->xchanged[$this->xind[$xoff++]] = 1;
372 else {
373 // Use the partitions to split this problem into subproblems.
374 reset($seps);
375 $pt1 = $seps[0];
376 while ($pt2 = next($seps)) {
377 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
378 $pt1 = $pt2;
384 * Adjust inserts/deletes of identical lines to join changes
385 * as much as possible.
387 * We do something when a run of changed lines include a
388 * line at one end and has an excluded, identical line at the other.
389 * We are free to choose which identical line is included.
390 * `compareseq' usually chooses the one at the beginning,
391 * but usually it is cleaner to consider the following identical line
392 * to be the "change".
394 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
396 function _shift_boundaries($lines, &$changed, $other_changed) {
397 $i = 0;
398 $j = 0;
400 USE_ASSERTS && assert('count($lines) == count($changed)');
401 $len = count($lines);
402 $other_len = count($other_changed);
404 while (1) {
406 * Scan forwards to find beginning of another run of changes.
407 * Also keep track of the corresponding point in the other file.
409 * Throughout this code, $i and $j are adjusted together so that
410 * the first $i elements of $changed and the first $j elements
411 * of $other_changed both contain the same number of zeros
412 * (unchanged lines).
413 * Furthermore, $j is always kept so that $j == $other_len or
414 * $other_changed[$j] == false.
416 while ($j < $other_len && $other_changed[$j])
417 $j++;
419 while ($i < $len && ! $changed[$i]) {
420 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
421 $i++;
422 $j++;
423 while ($j < $other_len && $other_changed[$j])
424 $j++;
427 if ($i == $len)
428 break;
430 $start = $i;
432 // Find the end of this run of changes.
433 while (++$i < $len && $changed[$i])
434 continue;
436 do {
438 * Record the length of this run of changes, so that
439 * we can later determine whether the run has grown.
441 $runlength = $i - $start;
444 * Move the changed region back, so long as the
445 * previous unchanged line matches the last changed one.
446 * This merges with previous changed regions.
448 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
449 $changed[--$start] = 1;
450 $changed[--$i] = false;
451 while ($start > 0 && $changed[$start - 1])
452 $start--;
453 USE_ASSERTS && assert('$j > 0');
454 while ($other_changed[--$j])
455 continue;
456 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
460 * Set CORRESPONDING to the end of the changed run, at the last
461 * point where it corresponds to a changed run in the other file.
462 * CORRESPONDING == LEN means no such point has been found.
464 $corresponding = $j < $other_len ? $i : $len;
467 * Move the changed region forward, so long as the
468 * first changed line matches the following unchanged one.
469 * This merges with following changed regions.
470 * Do this second, so that if there are no merges,
471 * the changed region is moved forward as far as possible.
473 while ($i < $len && $lines[$start] == $lines[$i]) {
474 $changed[$start++] = false;
475 $changed[$i++] = 1;
476 while ($i < $len && $changed[$i])
477 $i++;
479 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
480 $j++;
481 if ($j < $other_len && $other_changed[$j]) {
482 $corresponding = $i;
483 while ($j < $other_len && $other_changed[$j])
484 $j++;
487 } while ($runlength != $i - $start);
490 * If possible, move the fully-merged run of changes
491 * back to a corresponding run in the other file.
493 while ($corresponding < $i) {
494 $changed[--$start] = 1;
495 $changed[--$i] = 0;
496 USE_ASSERTS && assert('$j > 0');
497 while ($other_changed[--$j])
498 continue;
499 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
506 * Class representing a 'diff' between two sequences of strings.
508 class Diff {
510 var $edits;
513 * Constructor.
514 * Computes diff between sequences of strings.
516 * @param array $from_lines An array of strings.
517 * (Typically these are lines from a file.)
518 * @param array $to_lines An array of strings.
520 function __construct($from_lines, $to_lines) {
521 $eng = new _DiffEngine;
522 $this->edits = $eng->diff($from_lines, $to_lines);
523 //$this->_check($from_lines, $to_lines);
527 * Compute reversed Diff.
529 * SYNOPSIS:
531 * $diff = new Diff($lines1, $lines2);
532 * $rev = $diff->reverse();
534 * @return Diff A Diff object representing the inverse of the
535 * original diff.
537 function reverse() {
538 $rev = $this;
539 $rev->edits = array();
540 foreach ($this->edits as $edit) {
541 $rev->edits[] = $edit->reverse();
543 return $rev;
547 * Check for empty diff.
549 * @return bool True iff two sequences were identical.
551 function isEmpty() {
552 foreach ($this->edits as $edit) {
553 if ($edit->type != 'copy')
554 return false;
556 return true;
560 * Compute the length of the Longest Common Subsequence (LCS).
562 * This is mostly for diagnostic purposed.
564 * @return int The length of the LCS.
566 function lcs() {
567 $lcs = 0;
568 foreach ($this->edits as $edit) {
569 if ($edit->type == 'copy')
570 $lcs += count($edit->orig);
572 return $lcs;
576 * Get the original set of lines.
578 * This reconstructs the $from_lines parameter passed to the
579 * constructor.
581 * @return array The original sequence of strings.
583 function orig() {
584 $lines = array();
586 foreach ($this->edits as $edit) {
587 if ($edit->orig)
588 array_splice($lines, count($lines), 0, $edit->orig);
590 return $lines;
594 * Get the closing set of lines.
596 * This reconstructs the $to_lines parameter passed to the
597 * constructor.
599 * @return array The sequence of strings.
601 function closing() {
602 $lines = array();
604 foreach ($this->edits as $edit) {
605 if ($edit->closing)
606 array_splice($lines, count($lines), 0, $edit->closing);
608 return $lines;
612 * Check a Diff for validity.
614 * This is here only for debugging purposes.
616 function _check($from_lines, $to_lines) {
617 if (serialize($from_lines) != serialize($this->orig()))
618 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
619 if (serialize($to_lines) != serialize($this->closing()))
620 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
622 $rev = $this->reverse();
623 if (serialize($to_lines) != serialize($rev->orig()))
624 trigger_error("Reversed original doesn't match", E_USER_ERROR);
625 if (serialize($from_lines) != serialize($rev->closing()))
626 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
628 $prevtype = 'none';
629 foreach ($this->edits as $edit) {
630 if ($prevtype == $edit->type)
631 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
632 $prevtype = $edit->type;
635 $lcs = $this->lcs();
636 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
641 * FIXME: bad name.
643 class MappedDiff extends Diff {
645 * Constructor.
647 * Computes diff between sequences of strings.
649 * This can be used to compute things like
650 * case-insensitve diffs, or diffs which ignore
651 * changes in white-space.
653 * @param string[] $from_lines An array of strings.
654 * (Typically these are lines from a file.)
656 * @param string[] $to_lines An array of strings.
658 * @param string[] $mapped_from_lines This array should
659 * have the same size number of elements as $from_lines.
660 * The elements in $mapped_from_lines and
661 * $mapped_to_lines are what is actually compared
662 * when computing the diff.
664 * @param string[] $mapped_to_lines This array should
665 * have the same number of elements as $to_lines.
667 function __construct($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) {
669 assert(count($from_lines) == count($mapped_from_lines));
670 assert(count($to_lines) == count($mapped_to_lines));
672 parent::__construct($mapped_from_lines, $mapped_to_lines);
674 $xi = $yi = 0;
675 $ecnt = count($this->edits);
676 for ($i = 0; $i < $ecnt; $i++) {
677 $orig = &$this->edits[$i]->orig;
678 if (is_array($orig)) {
679 $orig = array_slice($from_lines, $xi, count($orig));
680 $xi += count($orig);
683 $closing = &$this->edits[$i]->closing;
684 if (is_array($closing)) {
685 $closing = array_slice($to_lines, $yi, count($closing));
686 $yi += count($closing);
693 * A class to format Diffs
695 * This class formats the diff in classic diff format.
696 * It is intended that this class be customized via inheritance,
697 * to obtain fancier outputs.
699 class DiffFormatter {
701 * Number of leading context "lines" to preserve.
703 * This should be left at zero for this class, but subclasses
704 * may want to set this to other values.
706 var $leading_context_lines = 0;
709 * Number of trailing context "lines" to preserve.
711 * This should be left at zero for this class, but subclasses
712 * may want to set this to other values.
714 var $trailing_context_lines = 0;
717 * Format a diff.
719 * @param Diff $diff A Diff object.
720 * @return string The formatted output.
722 function format($diff) {
724 $xi = $yi = 1;
725 $x0 = $y0 = 0;
726 $block = false;
727 $context = array();
729 $nlead = $this->leading_context_lines;
730 $ntrail = $this->trailing_context_lines;
732 $this->_start_diff();
734 foreach ($diff->edits as $edit) {
735 if ($edit->type == 'copy') {
736 if (is_array($block)) {
737 if (count($edit->orig) <= $nlead + $ntrail) {
738 $block[] = $edit;
740 else{
741 if ($ntrail) {
742 $context = array_slice($edit->orig, 0, $ntrail);
743 $block[] = new _DiffOp_Copy($context);
745 $this->_block($x0, $ntrail + $xi - $x0, $y0, $ntrail + $yi - $y0, $block);
746 $block = false;
749 $context = $edit->orig;
751 else {
752 if (! is_array($block)) {
753 $context = array_slice($context, count($context) - $nlead);
754 $x0 = $xi - count($context);
755 $y0 = $yi - count($context);
756 $block = array();
757 if ($context)
758 $block[] = new _DiffOp_Copy($context);
760 $block[] = $edit;
763 if ($edit->orig)
764 $xi += count($edit->orig);
765 if ($edit->closing)
766 $yi += count($edit->closing);
769 if (is_array($block))
770 $this->_block($x0, $xi - $x0, $y0, $yi - $y0, $block);
772 return $this->_end_diff();
776 * @param int $xbeg
777 * @param int $xlen
778 * @param int $ybeg
779 * @param int $ylen
780 * @param array $edits
782 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
783 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
784 foreach ($edits as $edit) {
785 if ($edit->type == 'copy')
786 $this->_context($edit->orig);
787 elseif ($edit->type == 'add')
788 $this->_added($edit->closing);
789 elseif ($edit->type == 'delete')
790 $this->_deleted($edit->orig);
791 elseif ($edit->type == 'change')
792 $this->_changed($edit->orig, $edit->closing);
793 else
794 trigger_error("Unknown edit type", E_USER_ERROR);
796 $this->_end_block();
799 function _start_diff() {
800 ob_start();
803 function _end_diff() {
804 $val = ob_get_contents();
805 ob_end_clean();
806 return $val;
810 * @param int $xbeg
811 * @param int $xlen
812 * @param int $ybeg
813 * @param int $ylen
814 * @return string
816 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
817 if ($xlen > 1)
818 $xbeg .= "," . ($xbeg + $xlen - 1);
819 if ($ylen > 1)
820 $ybeg .= "," . ($ybeg + $ylen - 1);
822 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
826 * @param string $header
828 function _start_block($header) {
829 echo $header;
832 function _end_block() {
835 function _lines($lines, $prefix = ' ') {
836 foreach ($lines as $line)
837 echo "$prefix ".$this->_escape($line)."\n";
840 function _context($lines) {
841 $this->_lines($lines);
844 function _added($lines) {
845 $this->_lines($lines, ">");
847 function _deleted($lines) {
848 $this->_lines($lines, "<");
851 function _changed($orig, $closing) {
852 $this->_deleted($orig);
853 echo "---\n";
854 $this->_added($closing);
858 * Escape string
860 * Override this method within other formatters if escaping required.
861 * Base class requires $str to be returned WITHOUT escaping.
863 * @param $str string Text string to escape
864 * @return string The escaped string.
866 function _escape($str){
867 return $str;
872 * Utilityclass for styling HTML formatted diffs
874 * Depends on global var $DIFF_INLINESTYLES, if true some minimal predefined
875 * inline styles are used. Useful for HTML mails and RSS feeds
877 * @author Andreas Gohr <andi@splitbrain.org>
879 class HTMLDiff {
881 * Holds the style names and basic CSS
883 static public $styles = array(
884 'diff-addedline' => 'background-color: #ddffdd;',
885 'diff-deletedline' => 'background-color: #ffdddd;',
886 'diff-context' => 'background-color: #f5f5f5;',
887 'diff-mark' => 'color: #ff0000;',
891 * Return a class or style parameter
893 static function css($classname){
894 global $DIFF_INLINESTYLES;
896 if($DIFF_INLINESTYLES){
897 if(!isset(self::$styles[$classname])) return '';
898 return 'style="'.self::$styles[$classname].'"';
899 }else{
900 return 'class="'.$classname.'"';
906 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
910 define('NBSP', "\xC2\xA0"); // utf-8 non-breaking space.
912 class _HWLDF_WordAccumulator {
914 function __construct() {
915 $this->_lines = array();
916 $this->_line = '';
917 $this->_group = '';
918 $this->_tag = '';
921 function _flushGroup($new_tag) {
922 if ($this->_group !== '') {
923 if ($this->_tag == 'mark')
924 $this->_line .= '<strong '.HTMLDiff::css('diff-mark').'>'.$this->_escape($this->_group).'</strong>';
925 elseif ($this->_tag == 'add')
926 $this->_line .= '<span '.HTMLDiff::css('diff-addedline').'>'.$this->_escape($this->_group).'</span>';
927 elseif ($this->_tag == 'del')
928 $this->_line .= '<span '.HTMLDiff::css('diff-deletedline').'><del>'.$this->_escape($this->_group).'</del></span>';
929 else
930 $this->_line .= $this->_escape($this->_group);
932 $this->_group = '';
933 $this->_tag = $new_tag;
937 * @param string $new_tag
939 function _flushLine($new_tag) {
940 $this->_flushGroup($new_tag);
941 if ($this->_line != '')
942 $this->_lines[] = $this->_line;
943 $this->_line = '';
946 function addWords($words, $tag = '') {
947 if ($tag != $this->_tag)
948 $this->_flushGroup($tag);
950 foreach ($words as $word) {
951 // new-line should only come as first char of word.
952 if ($word == '')
953 continue;
954 if ($word[0] == "\n") {
955 $this->_group .= NBSP;
956 $this->_flushLine($tag);
957 $word = substr($word, 1);
959 assert(!strstr($word, "\n"));
960 $this->_group .= $word;
964 function getLines() {
965 $this->_flushLine('~done');
966 return $this->_lines;
969 function _escape($str){
970 return hsc($str);
974 class WordLevelDiff extends MappedDiff {
976 function __construct($orig_lines, $closing_lines) {
977 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
978 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
980 parent::__construct($orig_words, $closing_words, $orig_stripped, $closing_stripped);
983 function _split($lines) {
984 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xsu',
985 implode("\n", $lines), $m)) {
986 return array(array(''), array(''));
988 return array($m[0], $m[1]);
991 function orig() {
992 $orig = new _HWLDF_WordAccumulator;
994 foreach ($this->edits as $edit) {
995 if ($edit->type == 'copy')
996 $orig->addWords($edit->orig);
997 elseif ($edit->orig)
998 $orig->addWords($edit->orig, 'mark');
1000 return $orig->getLines();
1003 function closing() {
1004 $closing = new _HWLDF_WordAccumulator;
1006 foreach ($this->edits as $edit) {
1007 if ($edit->type == 'copy')
1008 $closing->addWords($edit->closing);
1009 elseif ($edit->closing)
1010 $closing->addWords($edit->closing, 'mark');
1012 return $closing->getLines();
1016 class InlineWordLevelDiff extends MappedDiff {
1018 function __construct($orig_lines, $closing_lines) {
1019 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1020 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1022 parent::__construct($orig_words, $closing_words, $orig_stripped, $closing_stripped);
1025 function _split($lines) {
1026 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xsu',
1027 implode("\n", $lines), $m)) {
1028 return array(array(''), array(''));
1030 return array($m[0], $m[1]);
1033 function inline() {
1034 $orig = new _HWLDF_WordAccumulator;
1035 foreach ($this->edits as $edit) {
1036 if ($edit->type == 'copy')
1037 $orig->addWords($edit->closing);
1038 elseif ($edit->type == 'change'){
1039 $orig->addWords($edit->orig, 'del');
1040 $orig->addWords($edit->closing, 'add');
1041 } elseif ($edit->type == 'delete')
1042 $orig->addWords($edit->orig, 'del');
1043 elseif ($edit->type == 'add')
1044 $orig->addWords($edit->closing, 'add');
1045 elseif ($edit->orig)
1046 $orig->addWords($edit->orig, 'del');
1048 return $orig->getLines();
1053 * "Unified" diff formatter.
1055 * This class formats the diff in classic "unified diff" format.
1057 * NOTE: output is plain text and unsafe for use in HTML without escaping.
1059 class UnifiedDiffFormatter extends DiffFormatter {
1061 function __construct($context_lines = 4) {
1062 $this->leading_context_lines = $context_lines;
1063 $this->trailing_context_lines = $context_lines;
1066 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1067 if ($xlen != 1)
1068 $xbeg .= "," . $xlen;
1069 if ($ylen != 1)
1070 $ybeg .= "," . $ylen;
1071 return "@@ -$xbeg +$ybeg @@\n";
1074 function _added($lines) {
1075 $this->_lines($lines, "+");
1077 function _deleted($lines) {
1078 $this->_lines($lines, "-");
1080 function _changed($orig, $final) {
1081 $this->_deleted($orig);
1082 $this->_added($final);
1087 * Wikipedia Table style diff formatter.
1090 class TableDiffFormatter extends DiffFormatter {
1091 var $colspan = 2;
1093 function __construct() {
1094 $this->leading_context_lines = 2;
1095 $this->trailing_context_lines = 2;
1099 * @param Diff $diff
1100 * @return string
1102 function format($diff) {
1103 // Preserve whitespaces by converting some to non-breaking spaces.
1104 // Do not convert all of them to allow word-wrap.
1105 $val = parent::format($diff);
1106 $val = str_replace(' ','&#160; ', $val);
1107 $val = preg_replace('/ (?=<)|(?<=[ >]) /', '&#160;', $val);
1108 return $val;
1111 function _pre($text){
1112 $text = htmlspecialchars($text);
1113 return $text;
1116 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1117 global $lang;
1118 $l1 = $lang['line'].' '.$xbeg;
1119 $l2 = $lang['line'].' '.$ybeg;
1120 $r = '<tr><td '.HTMLDiff::css('diff-blockheader').' colspan="'.$this->colspan.'">'.$l1.":</td>\n".
1121 '<td '.HTMLDiff::css('diff-blockheader').' colspan="'.$this->colspan.'">'.$l2.":</td>\n".
1122 "</tr>\n";
1123 return $r;
1126 function _start_block($header) {
1127 print($header);
1130 function _end_block() {
1133 function _lines($lines, $prefix=' ', $color="white") {
1136 function addedLine($line,$escaped=false) {
1137 if (!$escaped){
1138 $line = $this->_escape($line);
1140 return '<td '.HTMLDiff::css('diff-lineheader').'>+</td>'.
1141 '<td '.HTMLDiff::css('diff-addedline').'>' . $line.'</td>';
1144 function deletedLine($line,$escaped=false) {
1145 if (!$escaped){
1146 $line = $this->_escape($line);
1148 return '<td '.HTMLDiff::css('diff-lineheader').'>-</td>'.
1149 '<td '.HTMLDiff::css('diff-deletedline').'>' . $line.'</td>';
1152 function emptyLine() {
1153 return '<td colspan="'.$this->colspan.'">&#160;</td>';
1156 function contextLine($line) {
1157 return '<td '.HTMLDiff::css('diff-lineheader').'>&#160;</td>'.
1158 '<td '.HTMLDiff::css('diff-context').'>'.$this->_escape($line).'</td>';
1161 function _added($lines) {
1162 $this->_addedLines($lines,false);
1165 function _addedLines($lines,$escaped=false){
1166 foreach ($lines as $line) {
1167 print('<tr>' . $this->emptyLine() . $this->addedLine($line,$escaped) . "</tr>\n");
1171 function _deleted($lines) {
1172 foreach ($lines as $line) {
1173 print('<tr>' . $this->deletedLine($line) . $this->emptyLine() . "</tr>\n");
1177 function _context($lines) {
1178 foreach ($lines as $line) {
1179 print('<tr>' . $this->contextLine($line) . $this->contextLine($line) . "</tr>\n");
1183 function _changed($orig, $closing) {
1184 $diff = new WordLevelDiff($orig, $closing); // this escapes the diff data
1185 $del = $diff->orig();
1186 $add = $diff->closing();
1188 while ($line = array_shift($del)) {
1189 $aline = array_shift($add);
1190 print('<tr>' . $this->deletedLine($line,true) . $this->addedLine($aline,true) . "</tr>\n");
1192 $this->_addedLines($add,true); # If any leftovers
1195 function _escape($str) {
1196 return hsc($str);
1201 * Inline style diff formatter.
1204 class InlineDiffFormatter extends DiffFormatter {
1205 var $colspan = 2;
1207 function __construct() {
1208 $this->leading_context_lines = 2;
1209 $this->trailing_context_lines = 2;
1213 * @param Diff $diff
1214 * @return string
1216 function format($diff) {
1217 // Preserve whitespaces by converting some to non-breaking spaces.
1218 // Do not convert all of them to allow word-wrap.
1219 $val = parent::format($diff);
1220 $val = str_replace(' ','&#160; ', $val);
1221 $val = preg_replace('/ (?=<)|(?<=[ >]) /', '&#160;', $val);
1222 return $val;
1225 function _pre($text){
1226 $text = htmlspecialchars($text);
1227 return $text;
1230 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1231 global $lang;
1232 if ($xlen != 1)
1233 $xbeg .= "," . $xlen;
1234 if ($ylen != 1)
1235 $ybeg .= "," . $ylen;
1236 $r = '<tr><td colspan="'.$this->colspan.'" '.HTMLDiff::css('diff-blockheader').'>@@ '.$lang['line']." -$xbeg +$ybeg @@";
1237 $r .= ' <span '.HTMLDiff::css('diff-deletedline').'><del>'.$lang['deleted'].'</del></span>';
1238 $r .= ' <span '.HTMLDiff::css('diff-addedline').'>'.$lang['created'].'</span>';
1239 $r .= "</td></tr>\n";
1240 return $r;
1243 function _start_block($header) {
1244 print($header."\n");
1247 function _end_block() {
1250 function _lines($lines, $prefix=' ', $color="white") {
1253 function _added($lines) {
1254 foreach ($lines as $line) {
1255 print('<tr><td '.HTMLDiff::css('diff-lineheader').'>&#160;</td><td '.HTMLDiff::css('diff-addedline').'>'. $this->_escape($line) . "</td></tr>\n");
1259 function _deleted($lines) {
1260 foreach ($lines as $line) {
1261 print('<tr><td '.HTMLDiff::css('diff-lineheader').'>&#160;</td><td '.HTMLDiff::css('diff-deletedline').'><del>' . $this->_escape($line) . "</del></td></tr>\n");
1265 function _context($lines) {
1266 foreach ($lines as $line) {
1267 print('<tr><td '.HTMLDiff::css('diff-lineheader').'>&#160;</td><td '.HTMLDiff::css('diff-context').'>'. $this->_escape($line) ."</td></tr>\n");
1271 function _changed($orig, $closing) {
1272 $diff = new InlineWordLevelDiff($orig, $closing); // this escapes the diff data
1273 $add = $diff->inline();
1275 foreach ($add as $line)
1276 print('<tr><td '.HTMLDiff::css('diff-lineheader').'>&#160;</td><td>'.$line."</td></tr>\n");
1279 function _escape($str) {
1280 return hsc($str);
1285 //Setup VIM: ex: et ts=4 :