xref: /dokuwiki/inc/DifferenceEngine.php (revision 5b99afc341c66e4c03243d01c27793895fe370f8)
1<?php
2/**
3 * A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
4 *
5 * Additions by Axel Boldt for MediaWiki
6 *
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 */
10define('USE_ASSERTS', function_exists('assert'));
11
12class _DiffOp {
13    var $type;
14    var $orig;
15    var $closing;
16
17    /**
18     * @return _DiffOp
19     */
20    function reverse() {
21        trigger_error("pure virtual", E_USER_ERROR);
22    }
23
24    function norig() {
25        return $this->orig ? count($this->orig) : 0;
26    }
27
28    function nclosing() {
29        return $this->closing ? count($this->closing) : 0;
30    }
31}
32
33class _DiffOp_Copy extends _DiffOp {
34    var $type = 'copy';
35
36    function __construct($orig, $closing = false) {
37        if (!is_array($closing))
38            $closing = $orig;
39        $this->orig = $orig;
40        $this->closing = $closing;
41    }
42
43    function reverse() {
44        return new _DiffOp_Copy($this->closing, $this->orig);
45    }
46}
47
48class _DiffOp_Delete extends _DiffOp {
49    var $type = 'delete';
50
51    function __construct($lines) {
52        $this->orig = $lines;
53        $this->closing = false;
54    }
55
56    function reverse() {
57        return new _DiffOp_Add($this->orig);
58    }
59}
60
61class _DiffOp_Add extends _DiffOp {
62    var $type = 'add';
63
64    function __construct($lines) {
65        $this->closing = $lines;
66        $this->orig = false;
67    }
68
69    function reverse() {
70        return new _DiffOp_Delete($this->closing);
71    }
72}
73
74class _DiffOp_Change extends _DiffOp {
75    var $type = 'change';
76
77    function __construct($orig, $closing) {
78        $this->orig = $orig;
79        $this->closing = $closing;
80    }
81
82    function reverse() {
83        return new _DiffOp_Change($this->closing, $this->orig);
84    }
85}
86
87
88/**
89 * Class used internally by Diff to actually compute the diffs.
90 *
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
94 *
95 * More ideas are taken from:
96 *   http://www.ics.uci.edu/~eppstein/161/960229.html
97 *
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
101 *
102 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
103 * are my own.
104 *
105 * @author Geoffrey T. Dairiki
106 * @access private
107 */
108class _DiffEngine {
109
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;
119
120    /**
121     * @param array $from_lines
122     * @param array $to_lines
123     * @return _DiffOp[]
124     */
125    function diff($from_lines, $to_lines) {
126        $n_from = count($from_lines);
127        $n_to = count($to_lines);
128
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);
135
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;
141        }
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;
149        }
150
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;
161        }
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;
168        }
169
170        // Find the LCS.
171        $this->_compareseq(0, count($this->xv), 0, count($this->yv));
172
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);
176
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]);
183
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;
189            }
190            if ($copy)
191                $edits[] = new _DiffOp_Copy($copy);
192
193            // Find deletes & adds.
194            $delete = array();
195            while ($xi < $n_from && $this->xchanged[$xi])
196                $delete[] = $from_lines[$xi++];
197
198            $add = array();
199            while ($yi < $n_to && $this->ychanged[$yi])
200                $add[] = $to_lines[$yi++];
201
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);
208        }
209        return $edits;
210    }
211
212
213    /**
214     * Divide the Largest Common Subsequence (LCS) of the sequences
215     * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
216     * sized segments.
217     *
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).
224     *
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.
229     */
230    function _diag($xoff, $xlim, $yoff, $ylim, $nchunks) {
231        $flip = false;
232
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);
238        }
239
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;
246
247        $this->lcs = 0;
248        $this->seq[0]= $yoff - 1;
249        $this->in_seq = array();
250        $ymids[0] = array();
251
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];
258
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;
272                    }
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;
281                    }
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];
286                    }
287                }
288            }
289        }
290
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);
297        }
298        $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
299
300        return array($this->lcs, $seps);
301    }
302
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;
309        }
310
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;
318        }
319
320        USE_ASSERTS && assert($ypos != $this->seq[$end]);
321
322        $this->in_seq[$this->seq[$end]] = false;
323        $this->seq[$end] = $ypos;
324        $this->in_seq[$ypos] = 1;
325        return $end;
326    }
327
328    /**
329     * Find LCS of two sequences.
330     *
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).
334     *
335     * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
336     *
337     * Note that XLIM, YLIM are exclusive bounds.
338     * All line numbers are origin-0 and discarded lines are not counted.
339     */
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;
345        }
346
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;
351        }
352
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);
362        }
363
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;
371        }
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;
379            }
380        }
381    }
382
383    /**
384     * Adjust inserts/deletes of identical lines to join changes
385     * as much as possible.
386     *
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".
393     *
394     * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
395     */
396    function _shift_boundaries($lines, &$changed, $other_changed) {
397        $i = 0;
398        $j = 0;
399
400        USE_ASSERTS && assert('count($lines) == count($changed)');
401        $len = count($lines);
402        $other_len = count($other_changed);
403
404        while (1) {
405            /*
406             * Scan forwards to find beginning of another run of changes.
407             * Also keep track of the corresponding point in the other file.
408             *
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.
415             */
416            while ($j < $other_len && $other_changed[$j])
417                $j++;
418
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++;
425            }
426
427            if ($i == $len)
428                break;
429
430            $start = $i;
431
432            // Find the end of this run of changes.
433            while (++$i < $len && $changed[$i])
434                continue;
435
436            do {
437                /*
438                 * Record the length of this run of changes, so that
439                 * we can later determine whether the run has grown.
440                 */
441                $runlength = $i - $start;
442
443                /*
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.
447                 */
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]');
457                }
458
459                /*
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.
463                 */
464                $corresponding = $j < $other_len ? $i : $len;
465
466                /*
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.
472                 */
473                while ($i < $len && $lines[$start] == $lines[$i]) {
474                    $changed[$start++] = false;
475                    $changed[$i++] = 1;
476                    while ($i < $len && $changed[$i])
477                        $i++;
478
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++;
485                    }
486                }
487            } while ($runlength != $i - $start);
488
489            /*
490             * If possible, move the fully-merged run of changes
491             * back to a corresponding run in the other file.
492             */
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]');
500            }
501        }
502    }
503}
504
505/**
506 * Class representing a 'diff' between two sequences of strings.
507 */
508class Diff {
509
510    var $edits;
511
512    /**
513     * Constructor.
514     * Computes diff between sequences of strings.
515     *
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.
519     */
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);
524    }
525
526    /**
527     * Compute reversed Diff.
528     *
529     * SYNOPSIS:
530     *
531     *  $diff = new Diff($lines1, $lines2);
532     *  $rev = $diff->reverse();
533     *
534     * @return Diff  A Diff object representing the inverse of the
535     *               original diff.
536     */
537    function reverse() {
538        $rev = $this;
539        $rev->edits = array();
540        foreach ($this->edits as $edit) {
541            $rev->edits[] = $edit->reverse();
542        }
543        return $rev;
544    }
545
546    /**
547     * Check for empty diff.
548     *
549     * @return bool True iff two sequences were identical.
550     */
551    function isEmpty() {
552        foreach ($this->edits as $edit) {
553            if ($edit->type != 'copy')
554                return false;
555        }
556        return true;
557    }
558
559    /**
560     * Compute the length of the Longest Common Subsequence (LCS).
561     *
562     * This is mostly for diagnostic purposed.
563     *
564     * @return int The length of the LCS.
565     */
566    function lcs() {
567        $lcs = 0;
568        foreach ($this->edits as $edit) {
569            if ($edit->type == 'copy')
570                $lcs += count($edit->orig);
571        }
572        return $lcs;
573    }
574
575    /**
576     * Get the original set of lines.
577     *
578     * This reconstructs the $from_lines parameter passed to the
579     * constructor.
580     *
581     * @return array The original sequence of strings.
582     */
583    function orig() {
584        $lines = array();
585
586        foreach ($this->edits as $edit) {
587            if ($edit->orig)
588                array_splice($lines, count($lines), 0, $edit->orig);
589        }
590        return $lines;
591    }
592
593    /**
594     * Get the closing set of lines.
595     *
596     * This reconstructs the $to_lines parameter passed to the
597     * constructor.
598     *
599     * @return array The sequence of strings.
600     */
601    function closing() {
602        $lines = array();
603
604        foreach ($this->edits as $edit) {
605            if ($edit->closing)
606                array_splice($lines, count($lines), 0, $edit->closing);
607        }
608        return $lines;
609    }
610
611    /**
612     * Check a Diff for validity.
613     *
614     * This is here only for debugging purposes.
615     */
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);
621
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);
627
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;
633        }
634
635        $lcs = $this->lcs();
636        trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
637    }
638}
639
640/**
641 * FIXME: bad name.
642 */
643class MappedDiff extends Diff {
644    /**
645     * Constructor.
646     *
647     * Computes diff between sequences of strings.
648     *
649     * This can be used to compute things like
650     * case-insensitve diffs, or diffs which ignore
651     * changes in white-space.
652     *
653     * @param string[] $from_lines         An array of strings.
654     *                                     (Typically these are lines from a file.)
655     *
656     * @param string[] $to_lines           An array of strings.
657     *
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.
663     *
664     * @param string[] $mapped_to_lines    This array should
665     *                                     have the same number of elements as $to_lines.
666     */
667    function __construct($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) {
668
669        assert(count($from_lines) == count($mapped_from_lines));
670        assert(count($to_lines) == count($mapped_to_lines));
671
672        parent::__construct($mapped_from_lines, $mapped_to_lines);
673
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);
681            }
682
683            $closing = &$this->edits[$i]->closing;
684            if (is_array($closing)) {
685                $closing = array_slice($to_lines, $yi, count($closing));
686                $yi += count($closing);
687            }
688        }
689    }
690}
691
692/**
693 * A class to format Diffs
694 *
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.
698 */
699class DiffFormatter {
700    /**
701     * Number of leading context "lines" to preserve.
702     *
703     * This should be left at zero for this class, but subclasses
704     * may want to set this to other values.
705     */
706    var $leading_context_lines = 0;
707
708    /**
709     * Number of trailing context "lines" to preserve.
710     *
711     * This should be left at zero for this class, but subclasses
712     * may want to set this to other values.
713     */
714    var $trailing_context_lines = 0;
715
716    /**
717     * Format a diff.
718     *
719     * @param Diff $diff A Diff object.
720     * @return string The formatted output.
721     */
722    function format($diff) {
723
724        $xi = $yi = 1;
725        $x0 = $y0 = 0;
726        $block = false;
727        $context = array();
728
729        $nlead = $this->leading_context_lines;
730        $ntrail = $this->trailing_context_lines;
731
732        $this->_start_diff();
733
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;
739                    }
740                    else{
741                        if ($ntrail) {
742                            $context = array_slice($edit->orig, 0, $ntrail);
743                            $block[] = new _DiffOp_Copy($context);
744                        }
745                        $this->_block($x0, $ntrail + $xi - $x0, $y0, $ntrail + $yi - $y0, $block);
746                        $block = false;
747                    }
748                }
749                $context = $edit->orig;
750            }
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);
759                }
760                $block[] = $edit;
761            }
762
763            if ($edit->orig)
764                $xi += count($edit->orig);
765            if ($edit->closing)
766                $yi += count($edit->closing);
767        }
768
769        if (is_array($block))
770            $this->_block($x0, $xi - $x0, $y0, $yi - $y0, $block);
771
772        return $this->_end_diff();
773    }
774
775    /**
776     * @param int $xbeg
777     * @param int $xlen
778     * @param int $ybeg
779     * @param int $ylen
780     * @param array $edits
781     */
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);
795        }
796        $this->_end_block();
797    }
798
799    function _start_diff() {
800        ob_start();
801    }
802
803    function _end_diff() {
804        $val = ob_get_contents();
805        ob_end_clean();
806        return $val;
807    }
808
809    /**
810     * @param int $xbeg
811     * @param int $xlen
812     * @param int $ybeg
813     * @param int $ylen
814     * @return string
815     */
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);
821
822        return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
823    }
824
825    /**
826     * @param string $header
827     */
828    function _start_block($header) {
829        echo $header;
830    }
831
832    function _end_block() {
833    }
834
835    function _lines($lines, $prefix = ' ') {
836        foreach ($lines as $line)
837            echo "$prefix ".$this->_escape($line)."\n";
838    }
839
840    function _context($lines) {
841        $this->_lines($lines);
842    }
843
844    function _added($lines) {
845        $this->_lines($lines, ">");
846    }
847    function _deleted($lines) {
848        $this->_lines($lines, "<");
849    }
850
851    function _changed($orig, $closing) {
852        $this->_deleted($orig);
853        echo "---\n";
854        $this->_added($closing);
855    }
856
857    /**
858     * Escape string
859     *
860     * Override this method within other formatters if escaping required.
861     * Base class requires $str to be returned WITHOUT escaping.
862     *
863     * @param $str string Text string to escape
864     * @return string The escaped string.
865     */
866    function _escape($str){
867        return $str;
868    }
869}
870
871/**
872 * Utilityclass for styling HTML formatted diffs
873 *
874 * Depends on global var $DIFF_INLINESTYLES, if true some minimal predefined
875 * inline styles are used. Useful for HTML mails and RSS feeds
876 *
877 * @author Andreas Gohr <andi@splitbrain.org>
878 */
879class HTMLDiff {
880    /**
881     * Holds the style names and basic CSS
882     */
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;',
888        );
889
890    /**
891     * Return a class or style parameter
892     */
893    static function css($classname){
894        global $DIFF_INLINESTYLES;
895
896        if($DIFF_INLINESTYLES){
897            if(!isset(self::$styles[$classname])) return '';
898            return 'style="'.self::$styles[$classname].'"';
899        }else{
900            return 'class="'.$classname.'"';
901        }
902    }
903}
904
905/**
906 *  Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
907 *
908 */
909
910define('NBSP', "\xC2\xA0");     // utf-8 non-breaking space.
911
912class _HWLDF_WordAccumulator {
913
914    function __construct() {
915        $this->_lines = array();
916        $this->_line = '';
917        $this->_group = '';
918        $this->_tag = '';
919    }
920
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);
931        }
932        $this->_group = '';
933        $this->_tag = $new_tag;
934    }
935
936    /**
937     * @param string $new_tag
938     */
939    function _flushLine($new_tag) {
940        $this->_flushGroup($new_tag);
941        if ($this->_line != '')
942            $this->_lines[] = $this->_line;
943        $this->_line = '';
944    }
945
946    function addWords($words, $tag = '') {
947        if ($tag != $this->_tag)
948            $this->_flushGroup($tag);
949
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);
958            }
959            assert(!strstr($word, "\n"));
960            $this->_group .= $word;
961        }
962    }
963
964    function getLines() {
965        $this->_flushLine('~done');
966        return $this->_lines;
967    }
968
969    function _escape($str){
970        return hsc($str);
971    }
972}
973
974class WordLevelDiff extends MappedDiff {
975
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);
979
980        parent::__construct($orig_words, $closing_words, $orig_stripped, $closing_stripped);
981    }
982
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(''));
987        }
988        return array($m[0], $m[1]);
989    }
990
991    function orig() {
992        $orig = new _HWLDF_WordAccumulator;
993
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');
999        }
1000        return $orig->getLines();
1001    }
1002
1003    function closing() {
1004        $closing = new _HWLDF_WordAccumulator;
1005
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');
1011        }
1012        return $closing->getLines();
1013    }
1014}
1015
1016class InlineWordLevelDiff extends MappedDiff {
1017
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);
1021
1022        parent::__construct($orig_words, $closing_words, $orig_stripped, $closing_stripped);
1023    }
1024
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(''));
1029        }
1030        return array($m[0], $m[1]);
1031    }
1032
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');
1047        }
1048        return $orig->getLines();
1049    }
1050}
1051
1052/**
1053 * "Unified" diff formatter.
1054 *
1055 * This class formats the diff in classic "unified diff" format.
1056 *
1057 * NOTE: output is plain text and unsafe for use in HTML without escaping.
1058 */
1059class UnifiedDiffFormatter extends DiffFormatter {
1060
1061    function __construct($context_lines = 4) {
1062        $this->leading_context_lines = $context_lines;
1063        $this->trailing_context_lines = $context_lines;
1064    }
1065
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";
1072    }
1073
1074    function _added($lines) {
1075        $this->_lines($lines, "+");
1076    }
1077    function _deleted($lines) {
1078        $this->_lines($lines, "-");
1079    }
1080    function _changed($orig, $final) {
1081        $this->_deleted($orig);
1082        $this->_added($final);
1083    }
1084}
1085
1086/**
1087 *  Wikipedia Table style diff formatter.
1088 *
1089 */
1090class TableDiffFormatter extends DiffFormatter {
1091    var $colspan = 2;
1092
1093    function __construct() {
1094        $this->leading_context_lines = 2;
1095        $this->trailing_context_lines = 2;
1096    }
1097
1098    /**
1099     * @param Diff $diff
1100     * @return string
1101     */
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;
1109    }
1110
1111    function _pre($text){
1112        $text = htmlspecialchars($text);
1113        return $text;
1114    }
1115
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;
1124    }
1125
1126    function _start_block($header) {
1127        print($header);
1128    }
1129
1130    function _end_block() {
1131    }
1132
1133    function _lines($lines, $prefix=' ', $color="white") {
1134    }
1135
1136    function addedLine($line,$escaped=false) {
1137        if (!$escaped){
1138            $line = $this->_escape($line);
1139        }
1140        return '<td '.HTMLDiff::css('diff-lineheader').'>+</td>'.
1141               '<td '.HTMLDiff::css('diff-addedline').'>' .  $line.'</td>';
1142    }
1143
1144    function deletedLine($line,$escaped=false) {
1145        if (!$escaped){
1146            $line = $this->_escape($line);
1147        }
1148        return '<td '.HTMLDiff::css('diff-lineheader').'>-</td>'.
1149               '<td '.HTMLDiff::css('diff-deletedline').'>' .  $line.'</td>';
1150    }
1151
1152    function emptyLine() {
1153        return '<td colspan="'.$this->colspan.'">&#160;</td>';
1154    }
1155
1156    function contextLine($line) {
1157        return '<td '.HTMLDiff::css('diff-lineheader').'>&#160;</td>'.
1158               '<td '.HTMLDiff::css('diff-context').'>'.$this->_escape($line).'</td>';
1159    }
1160
1161    function _added($lines) {
1162        $this->_addedLines($lines,false);
1163    }
1164
1165    function _addedLines($lines,$escaped=false){
1166        foreach ($lines as $line) {
1167            print('<tr>' . $this->emptyLine() . $this->addedLine($line,$escaped) . "</tr>\n");
1168        }
1169    }
1170
1171    function _deleted($lines) {
1172        foreach ($lines as $line) {
1173            print('<tr>' . $this->deletedLine($line) . $this->emptyLine() . "</tr>\n");
1174        }
1175    }
1176
1177    function _context($lines) {
1178        foreach ($lines as $line) {
1179            print('<tr>' . $this->contextLine($line) .  $this->contextLine($line) . "</tr>\n");
1180        }
1181    }
1182
1183    function _changed($orig, $closing) {
1184        $diff = new WordLevelDiff($orig, $closing);  // this escapes the diff data
1185        $del = $diff->orig();
1186        $add = $diff->closing();
1187
1188        while ($line = array_shift($del)) {
1189            $aline = array_shift($add);
1190            print('<tr>' . $this->deletedLine($line,true) . $this->addedLine($aline,true) . "</tr>\n");
1191        }
1192        $this->_addedLines($add,true); # If any leftovers
1193    }
1194
1195    function _escape($str) {
1196        return hsc($str);
1197    }
1198}
1199
1200/**
1201 *  Inline style diff formatter.
1202 *
1203 */
1204class InlineDiffFormatter extends DiffFormatter {
1205    var $colspan = 2;
1206
1207    function __construct() {
1208        $this->leading_context_lines = 2;
1209        $this->trailing_context_lines = 2;
1210    }
1211
1212    /**
1213     * @param Diff $diff
1214     * @return string
1215     */
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;
1223    }
1224
1225    function _pre($text){
1226        $text = htmlspecialchars($text);
1227        return $text;
1228    }
1229
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;
1241    }
1242
1243    function _start_block($header) {
1244        print($header."\n");
1245    }
1246
1247    function _end_block() {
1248    }
1249
1250    function _lines($lines, $prefix=' ', $color="white") {
1251    }
1252
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");
1256        }
1257    }
1258
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");
1262        }
1263    }
1264
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");
1268        }
1269    }
1270
1271    function _changed($orig, $closing) {
1272        $diff = new InlineWordLevelDiff($orig, $closing);  // this escapes the diff data
1273        $add = $diff->inline();
1274
1275        foreach ($add as $line)
1276            print('<tr><td '.HTMLDiff::css('diff-lineheader').'>&#160;</td><td>'.$line."</td></tr>\n");
1277    }
1278
1279    function _escape($str) {
1280        return hsc($str);
1281    }
1282}
1283
1284
1285//Setup VIM: ex: et ts=4 :
1286