source: documentation/trunk/packages/dokuwiki-2011-05-25a/inc/DifferenceEngine.php@ 30098

Last change on this file since 30098 was 25027, checked in by jmt12, 12 years ago

Adding the packages directory, and within it a configured version of dokuwiki all ready to run

File size: 35.4 KB
Line 
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 <[email protected]>
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 function reverse() {
18 trigger_error("pure virtual", E_USER_ERROR);
19 }
20
21 function norig() {
22 return $this->orig ? count($this->orig) : 0;
23 }
24
25 function nclosing() {
26 return $this->closing ? count($this->closing) : 0;
27 }
28}
29
30class _DiffOp_Copy extends _DiffOp {
31 var $type = 'copy';
32
33 function __construct($orig, $closing = false) {
34 if (!is_array($closing))
35 $closing = $orig;
36 $this->orig = $orig;
37 $this->closing = $closing;
38 }
39
40 function reverse() {
41 return new _DiffOp_Copy($this->closing, $this->orig);
42 }
43}
44
45class _DiffOp_Delete extends _DiffOp {
46 var $type = 'delete';
47
48 function __construct($lines) {
49 $this->orig = $lines;
50 $this->closing = false;
51 }
52
53 function reverse() {
54 return new _DiffOp_Add($this->orig);
55 }
56}
57
58class _DiffOp_Add extends _DiffOp {
59 var $type = 'add';
60
61 function __construct($lines) {
62 $this->closing = $lines;
63 $this->orig = false;
64 }
65
66 function reverse() {
67 return new _DiffOp_Delete($this->closing);
68 }
69}
70
71class _DiffOp_Change extends _DiffOp {
72 var $type = 'change';
73
74 function __construct($orig, $closing) {
75 $this->orig = $orig;
76 $this->closing = $closing;
77 }
78
79 function reverse() {
80 return new _DiffOp_Change($this->closing, $this->orig);
81 }
82}
83
84
85/**
86 * Class used internally by Diff to actually compute the diffs.
87 *
88 * The algorithm used here is mostly lifted from the perl module
89 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
90 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
91 *
92 * More ideas are taken from:
93 * http://www.ics.uci.edu/~eppstein/161/960229.html
94 *
95 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
96 * diffutils-2.7, which can be found at:
97 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
98 *
99 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
100 * are my own.
101 *
102 * @author Geoffrey T. Dairiki
103 * @access private
104 */
105class _DiffEngine {
106
107 function diff($from_lines, $to_lines) {
108 $n_from = count($from_lines);
109 $n_to = count($to_lines);
110
111 $this->xchanged = $this->ychanged = array();
112 $this->xv = $this->yv = array();
113 $this->xind = $this->yind = array();
114 unset($this->seq);
115 unset($this->in_seq);
116 unset($this->lcs);
117
118 // Skip leading common lines.
119 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
120 if ($from_lines[$skip] != $to_lines[$skip])
121 break;
122 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
123 }
124 // Skip trailing common lines.
125 $xi = $n_from;
126 $yi = $n_to;
127 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
128 if ($from_lines[$xi] != $to_lines[$yi])
129 break;
130 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
131 }
132
133 // Ignore lines which do not exist in both files.
134 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
135 $xhash[$from_lines[$xi]] = 1;
136 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
137 $line = $to_lines[$yi];
138 if (($this->ychanged[$yi] = empty($xhash[$line])))
139 continue;
140 $yhash[$line] = 1;
141 $this->yv[] = $line;
142 $this->yind[] = $yi;
143 }
144 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
145 $line = $from_lines[$xi];
146 if (($this->xchanged[$xi] = empty($yhash[$line])))
147 continue;
148 $this->xv[] = $line;
149 $this->xind[] = $xi;
150 }
151
152 // Find the LCS.
153 $this->_compareseq(0, count($this->xv), 0, count($this->yv));
154
155 // Merge edits when possible
156 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
157 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
158
159 // Compute the edit operations.
160 $edits = array();
161 $xi = $yi = 0;
162 while ($xi < $n_from || $yi < $n_to) {
163 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
164 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
165
166 // Skip matching "snake".
167 $copy = array();
168 while ($xi < $n_from && $yi < $n_to && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
169 $copy[] = $from_lines[$xi++];
170 ++$yi;
171 }
172 if ($copy)
173 $edits[] = new _DiffOp_Copy($copy);
174
175 // Find deletes & adds.
176 $delete = array();
177 while ($xi < $n_from && $this->xchanged[$xi])
178 $delete[] = $from_lines[$xi++];
179
180 $add = array();
181 while ($yi < $n_to && $this->ychanged[$yi])
182 $add[] = $to_lines[$yi++];
183
184 if ($delete && $add)
185 $edits[] = new _DiffOp_Change($delete, $add);
186 elseif ($delete)
187 $edits[] = new _DiffOp_Delete($delete);
188 elseif ($add)
189 $edits[] = new _DiffOp_Add($add);
190 }
191 return $edits;
192 }
193
194
195 /**
196 * Divide the Largest Common Subsequence (LCS) of the sequences
197 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
198 * sized segments.
199 *
200 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
201 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
202 * sub sequences. The first sub-sequence is contained in [X0, X1),
203 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
204 * that (X0, Y0) == (XOFF, YOFF) and
205 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
206 *
207 * This function assumes that the first lines of the specified portions
208 * of the two files do not match, and likewise that the last lines do not
209 * match. The caller must trim matching lines from the beginning and end
210 * of the portions it is going to specify.
211 */
212 function _diag($xoff, $xlim, $yoff, $ylim, $nchunks) {
213 $flip = false;
214
215 if ($xlim - $xoff > $ylim - $yoff) {
216 // Things seems faster (I'm not sure I understand why)
217 // when the shortest sequence in X.
218 $flip = true;
219 list ($xoff, $xlim, $yoff, $ylim) = array($yoff, $ylim, $xoff, $xlim);
220 }
221
222 if ($flip)
223 for ($i = $ylim - 1; $i >= $yoff; $i--)
224 $ymatches[$this->xv[$i]][] = $i;
225 else
226 for ($i = $ylim - 1; $i >= $yoff; $i--)
227 $ymatches[$this->yv[$i]][] = $i;
228
229 $this->lcs = 0;
230 $this->seq[0]= $yoff - 1;
231 $this->in_seq = array();
232 $ymids[0] = array();
233
234 $numer = $xlim - $xoff + $nchunks - 1;
235 $x = $xoff;
236 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
237 if ($chunk > 0)
238 for ($i = 0; $i <= $this->lcs; $i++)
239 $ymids[$i][$chunk-1] = $this->seq[$i];
240
241 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
242 for ( ; $x < $x1; $x++) {
243 $line = $flip ? $this->yv[$x] : $this->xv[$x];
244 if (empty($ymatches[$line]))
245 continue;
246 $matches = $ymatches[$line];
247 reset($matches);
248 while (list ($junk, $y) = each($matches))
249 if (empty($this->in_seq[$y])) {
250 $k = $this->_lcs_pos($y);
251 USE_ASSERTS && assert($k > 0);
252 $ymids[$k] = $ymids[$k-1];
253 break;
254 }
255 while (list ($junk, $y) = each($matches)) {
256 if ($y > $this->seq[$k-1]) {
257 USE_ASSERTS && assert($y < $this->seq[$k]);
258 // Optimization: this is a common case:
259 // next match is just replacing previous match.
260 $this->in_seq[$this->seq[$k]] = false;
261 $this->seq[$k] = $y;
262 $this->in_seq[$y] = 1;
263 }
264 else if (empty($this->in_seq[$y])) {
265 $k = $this->_lcs_pos($y);
266 USE_ASSERTS && assert($k > 0);
267 $ymids[$k] = $ymids[$k-1];
268 }
269 }
270 }
271 }
272
273 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
274 $ymid = $ymids[$this->lcs];
275 for ($n = 0; $n < $nchunks - 1; $n++) {
276 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
277 $y1 = $ymid[$n] + 1;
278 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
279 }
280 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
281
282 return array($this->lcs, $seps);
283 }
284
285 function _lcs_pos($ypos) {
286 $end = $this->lcs;
287 if ($end == 0 || $ypos > $this->seq[$end]) {
288 $this->seq[++$this->lcs] = $ypos;
289 $this->in_seq[$ypos] = 1;
290 return $this->lcs;
291 }
292
293 $beg = 1;
294 while ($beg < $end) {
295 $mid = (int)(($beg + $end) / 2);
296 if ($ypos > $this->seq[$mid])
297 $beg = $mid + 1;
298 else
299 $end = $mid;
300 }
301
302 USE_ASSERTS && assert($ypos != $this->seq[$end]);
303
304 $this->in_seq[$this->seq[$end]] = false;
305 $this->seq[$end] = $ypos;
306 $this->in_seq[$ypos] = 1;
307 return $end;
308 }
309
310 /**
311 * Find LCS of two sequences.
312 *
313 * The results are recorded in the vectors $this->{x,y}changed[], by
314 * storing a 1 in the element for each line that is an insertion
315 * or deletion (ie. is not in the LCS).
316 *
317 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
318 *
319 * Note that XLIM, YLIM are exclusive bounds.
320 * All line numbers are origin-0 and discarded lines are not counted.
321 */
322 function _compareseq($xoff, $xlim, $yoff, $ylim) {
323 // Slide down the bottom initial diagonal.
324 while ($xoff < $xlim && $yoff < $ylim && $this->xv[$xoff] == $this->yv[$yoff]) {
325 ++$xoff;
326 ++$yoff;
327 }
328
329 // Slide up the top initial diagonal.
330 while ($xlim > $xoff && $ylim > $yoff && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
331 --$xlim;
332 --$ylim;
333 }
334
335 if ($xoff == $xlim || $yoff == $ylim)
336 $lcs = 0;
337 else {
338 // This is ad hoc but seems to work well.
339 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
340 //$nchunks = max(2,min(8,(int)$nchunks));
341 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
342 list ($lcs, $seps)
343 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
344 }
345
346 if ($lcs == 0) {
347 // X and Y sequences have no common subsequence:
348 // mark all changed.
349 while ($yoff < $ylim)
350 $this->ychanged[$this->yind[$yoff++]] = 1;
351 while ($xoff < $xlim)
352 $this->xchanged[$this->xind[$xoff++]] = 1;
353 }
354 else {
355 // Use the partitions to split this problem into subproblems.
356 reset($seps);
357 $pt1 = $seps[0];
358 while ($pt2 = next($seps)) {
359 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
360 $pt1 = $pt2;
361 }
362 }
363 }
364
365 /**
366 * Adjust inserts/deletes of identical lines to join changes
367 * as much as possible.
368 *
369 * We do something when a run of changed lines include a
370 * line at one end and has an excluded, identical line at the other.
371 * We are free to choose which identical line is included.
372 * `compareseq' usually chooses the one at the beginning,
373 * but usually it is cleaner to consider the following identical line
374 * to be the "change".
375 *
376 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
377 */
378 function _shift_boundaries($lines, &$changed, $other_changed) {
379 $i = 0;
380 $j = 0;
381
382 USE_ASSERTS && assert('count($lines) == count($changed)');
383 $len = count($lines);
384 $other_len = count($other_changed);
385
386 while (1) {
387 /*
388 * Scan forwards to find beginning of another run of changes.
389 * Also keep track of the corresponding point in the other file.
390 *
391 * Throughout this code, $i and $j are adjusted together so that
392 * the first $i elements of $changed and the first $j elements
393 * of $other_changed both contain the same number of zeros
394 * (unchanged lines).
395 * Furthermore, $j is always kept so that $j == $other_len or
396 * $other_changed[$j] == false.
397 */
398 while ($j < $other_len && $other_changed[$j])
399 $j++;
400
401 while ($i < $len && ! $changed[$i]) {
402 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
403 $i++;
404 $j++;
405 while ($j < $other_len && $other_changed[$j])
406 $j++;
407 }
408
409 if ($i == $len)
410 break;
411
412 $start = $i;
413
414 // Find the end of this run of changes.
415 while (++$i < $len && $changed[$i])
416 continue;
417
418 do {
419 /*
420 * Record the length of this run of changes, so that
421 * we can later determine whether the run has grown.
422 */
423 $runlength = $i - $start;
424
425 /*
426 * Move the changed region back, so long as the
427 * previous unchanged line matches the last changed one.
428 * This merges with previous changed regions.
429 */
430 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
431 $changed[--$start] = 1;
432 $changed[--$i] = false;
433 while ($start > 0 && $changed[$start - 1])
434 $start--;
435 USE_ASSERTS && assert('$j > 0');
436 while ($other_changed[--$j])
437 continue;
438 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
439 }
440
441 /*
442 * Set CORRESPONDING to the end of the changed run, at the last
443 * point where it corresponds to a changed run in the other file.
444 * CORRESPONDING == LEN means no such point has been found.
445 */
446 $corresponding = $j < $other_len ? $i : $len;
447
448 /*
449 * Move the changed region forward, so long as the
450 * first changed line matches the following unchanged one.
451 * This merges with following changed regions.
452 * Do this second, so that if there are no merges,
453 * the changed region is moved forward as far as possible.
454 */
455 while ($i < $len && $lines[$start] == $lines[$i]) {
456 $changed[$start++] = false;
457 $changed[$i++] = 1;
458 while ($i < $len && $changed[$i])
459 $i++;
460
461 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
462 $j++;
463 if ($j < $other_len && $other_changed[$j]) {
464 $corresponding = $i;
465 while ($j < $other_len && $other_changed[$j])
466 $j++;
467 }
468 }
469 } while ($runlength != $i - $start);
470
471 /*
472 * If possible, move the fully-merged run of changes
473 * back to a corresponding run in the other file.
474 */
475 while ($corresponding < $i) {
476 $changed[--$start] = 1;
477 $changed[--$i] = 0;
478 USE_ASSERTS && assert('$j > 0');
479 while ($other_changed[--$j])
480 continue;
481 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
482 }
483 }
484 }
485}
486
487/**
488 * Class representing a 'diff' between two sequences of strings.
489 */
490class Diff {
491
492 var $edits;
493
494 /**
495 * Constructor.
496 * Computes diff between sequences of strings.
497 *
498 * @param $from_lines array An array of strings.
499 * (Typically these are lines from a file.)
500 * @param $to_lines array An array of strings.
501 */
502 function __construct($from_lines, $to_lines) {
503 $eng = new _DiffEngine;
504 $this->edits = $eng->diff($from_lines, $to_lines);
505 //$this->_check($from_lines, $to_lines);
506 }
507
508 /**
509 * Compute reversed Diff.
510 *
511 * SYNOPSIS:
512 *
513 * $diff = new Diff($lines1, $lines2);
514 * $rev = $diff->reverse();
515 * @return object A Diff object representing the inverse of the
516 * original diff.
517 */
518 function reverse() {
519 $rev = $this;
520 $rev->edits = array();
521 foreach ($this->edits as $edit) {
522 $rev->edits[] = $edit->reverse();
523 }
524 return $rev;
525 }
526
527 /**
528 * Check for empty diff.
529 *
530 * @return bool True iff two sequences were identical.
531 */
532 function isEmpty() {
533 foreach ($this->edits as $edit) {
534 if ($edit->type != 'copy')
535 return false;
536 }
537 return true;
538 }
539
540 /**
541 * Compute the length of the Longest Common Subsequence (LCS).
542 *
543 * This is mostly for diagnostic purposed.
544 *
545 * @return int The length of the LCS.
546 */
547 function lcs() {
548 $lcs = 0;
549 foreach ($this->edits as $edit) {
550 if ($edit->type == 'copy')
551 $lcs += count($edit->orig);
552 }
553 return $lcs;
554 }
555
556 /**
557 * Get the original set of lines.
558 *
559 * This reconstructs the $from_lines parameter passed to the
560 * constructor.
561 *
562 * @return array The original sequence of strings.
563 */
564 function orig() {
565 $lines = array();
566
567 foreach ($this->edits as $edit) {
568 if ($edit->orig)
569 array_splice($lines, count($lines), 0, $edit->orig);
570 }
571 return $lines;
572 }
573
574 /**
575 * Get the closing set of lines.
576 *
577 * This reconstructs the $to_lines parameter passed to the
578 * constructor.
579 *
580 * @return array The sequence of strings.
581 */
582 function closing() {
583 $lines = array();
584
585 foreach ($this->edits as $edit) {
586 if ($edit->closing)
587 array_splice($lines, count($lines), 0, $edit->closing);
588 }
589 return $lines;
590 }
591
592 /**
593 * Check a Diff for validity.
594 *
595 * This is here only for debugging purposes.
596 */
597 function _check($from_lines, $to_lines) {
598 if (serialize($from_lines) != serialize($this->orig()))
599 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
600 if (serialize($to_lines) != serialize($this->closing()))
601 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
602
603 $rev = $this->reverse();
604 if (serialize($to_lines) != serialize($rev->orig()))
605 trigger_error("Reversed original doesn't match", E_USER_ERROR);
606 if (serialize($from_lines) != serialize($rev->closing()))
607 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
608
609 $prevtype = 'none';
610 foreach ($this->edits as $edit) {
611 if ($prevtype == $edit->type)
612 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
613 $prevtype = $edit->type;
614 }
615
616 $lcs = $this->lcs();
617 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
618 }
619}
620
621/**
622 * FIXME: bad name.
623 */
624class MappedDiff extends Diff {
625 /**
626 * Constructor.
627 *
628 * Computes diff between sequences of strings.
629 *
630 * This can be used to compute things like
631 * case-insensitve diffs, or diffs which ignore
632 * changes in white-space.
633 *
634 * @param $from_lines array An array of strings.
635 * (Typically these are lines from a file.)
636 *
637 * @param $to_lines array An array of strings.
638 *
639 * @param $mapped_from_lines array This array should
640 * have the same size number of elements as $from_lines.
641 * The elements in $mapped_from_lines and
642 * $mapped_to_lines are what is actually compared
643 * when computing the diff.
644 *
645 * @param $mapped_to_lines array This array should
646 * have the same number of elements as $to_lines.
647 */
648 function __construct($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) {
649
650 assert(count($from_lines) == count($mapped_from_lines));
651 assert(count($to_lines) == count($mapped_to_lines));
652
653 parent::__construct($mapped_from_lines, $mapped_to_lines);
654
655 $xi = $yi = 0;
656 $ecnt = count($this->edits);
657 for ($i = 0; $i < $ecnt; $i++) {
658 $orig = &$this->edits[$i]->orig;
659 if (is_array($orig)) {
660 $orig = array_slice($from_lines, $xi, count($orig));
661 $xi += count($orig);
662 }
663
664 $closing = &$this->edits[$i]->closing;
665 if (is_array($closing)) {
666 $closing = array_slice($to_lines, $yi, count($closing));
667 $yi += count($closing);
668 }
669 }
670 }
671}
672
673/**
674 * A class to format Diffs
675 *
676 * This class formats the diff in classic diff format.
677 * It is intended that this class be customized via inheritance,
678 * to obtain fancier outputs.
679 */
680class DiffFormatter {
681 /**
682 * Number of leading context "lines" to preserve.
683 *
684 * This should be left at zero for this class, but subclasses
685 * may want to set this to other values.
686 */
687 var $leading_context_lines = 0;
688
689 /**
690 * Number of trailing context "lines" to preserve.
691 *
692 * This should be left at zero for this class, but subclasses
693 * may want to set this to other values.
694 */
695 var $trailing_context_lines = 0;
696
697 /**
698 * Format a diff.
699 *
700 * @param $diff object A Diff object.
701 * @return string The formatted output.
702 */
703 function format($diff) {
704
705 $xi = $yi = 1;
706 $block = false;
707 $context = array();
708
709 $nlead = $this->leading_context_lines;
710 $ntrail = $this->trailing_context_lines;
711
712 $this->_start_diff();
713
714 foreach ($diff->edits as $edit) {
715 if ($edit->type == 'copy') {
716 if (is_array($block)) {
717 if (count($edit->orig) <= $nlead + $ntrail) {
718 $block[] = $edit;
719 }
720 else{
721 if ($ntrail) {
722 $context = array_slice($edit->orig, 0, $ntrail);
723 $block[] = new _DiffOp_Copy($context);
724 }
725 $this->_block($x0, $ntrail + $xi - $x0, $y0, $ntrail + $yi - $y0, $block);
726 $block = false;
727 }
728 }
729 $context = $edit->orig;
730 }
731 else {
732 if (! is_array($block)) {
733 $context = array_slice($context, count($context) - $nlead);
734 $x0 = $xi - count($context);
735 $y0 = $yi - count($context);
736 $block = array();
737 if ($context)
738 $block[] = new _DiffOp_Copy($context);
739 }
740 $block[] = $edit;
741 }
742
743 if ($edit->orig)
744 $xi += count($edit->orig);
745 if ($edit->closing)
746 $yi += count($edit->closing);
747 }
748
749 if (is_array($block))
750 $this->_block($x0, $xi - $x0, $y0, $yi - $y0, $block);
751
752 return $this->_end_diff();
753 }
754
755 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
756 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
757 foreach ($edits as $edit) {
758 if ($edit->type == 'copy')
759 $this->_context($edit->orig);
760 elseif ($edit->type == 'add')
761 $this->_added($edit->closing);
762 elseif ($edit->type == 'delete')
763 $this->_deleted($edit->orig);
764 elseif ($edit->type == 'change')
765 $this->_changed($edit->orig, $edit->closing);
766 else
767 trigger_error("Unknown edit type", E_USER_ERROR);
768 }
769 $this->_end_block();
770 }
771
772 function _start_diff() {
773 ob_start();
774 }
775
776 function _end_diff() {
777 $val = ob_get_contents();
778 ob_end_clean();
779 return $val;
780 }
781
782 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
783 if ($xlen > 1)
784 $xbeg .= "," . ($xbeg + $xlen - 1);
785 if ($ylen > 1)
786 $ybeg .= "," . ($ybeg + $ylen - 1);
787
788 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
789 }
790
791 function _start_block($header) {
792 echo $header;
793 }
794
795 function _end_block() {
796 }
797
798 function _lines($lines, $prefix = ' ') {
799 foreach ($lines as $line)
800 echo "$prefix $line\n";
801 }
802
803 function _context($lines) {
804 $this->_lines($lines);
805 }
806
807 function _added($lines) {
808 $this->_lines($lines, ">");
809 }
810 function _deleted($lines) {
811 $this->_lines($lines, "<");
812 }
813
814 function _changed($orig, $closing) {
815 $this->_deleted($orig);
816 echo "---\n";
817 $this->_added($closing);
818 }
819}
820
821
822/**
823 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
824 *
825 */
826
827define('NBSP', "\xC2\xA0"); // utf-8 non-breaking space.
828
829class _HWLDF_WordAccumulator {
830
831 function __construct() {
832 $this->_lines = array();
833 $this->_line = '';
834 $this->_group = '';
835 $this->_tag = '';
836 }
837
838 function _flushGroup($new_tag) {
839 if ($this->_group !== '') {
840 if ($this->_tag == 'mark')
841 $this->_line .= '<strong>'.$this->_group.'</strong>';
842 elseif ($this->_tag == 'add')
843 $this->_line .= '<span class="diff-addedline">'.$this->_group.'</span>';
844 elseif ($this->_tag == 'del')
845 $this->_line .= '<span class="diff-deletedline"><del>'.$this->_group.'</del></span>';
846 else
847 $this->_line .= $this->_group;
848 }
849 $this->_group = '';
850 $this->_tag = $new_tag;
851 }
852
853 function _flushLine($new_tag) {
854 $this->_flushGroup($new_tag);
855 if ($this->_line != '')
856 $this->_lines[] = $this->_line;
857 $this->_line = '';
858 }
859
860 function addWords($words, $tag = '') {
861 if ($tag != $this->_tag)
862 $this->_flushGroup($tag);
863
864 foreach ($words as $word) {
865 // new-line should only come as first char of word.
866 if ($word == '')
867 continue;
868 if ($word[0] == "\n") {
869 $this->_group .= NBSP;
870 $this->_flushLine($tag);
871 $word = substr($word, 1);
872 }
873 assert(!strstr($word, "\n"));
874 $this->_group .= $word;
875 }
876 }
877
878 function getLines() {
879 $this->_flushLine('~done');
880 return $this->_lines;
881 }
882}
883
884class WordLevelDiff extends MappedDiff {
885
886 function __construct($orig_lines, $closing_lines) {
887 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
888 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
889
890 parent::__construct($orig_words, $closing_words, $orig_stripped, $closing_stripped);
891 }
892
893 function _split($lines) {
894 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xsu',
895 implode("\n", $lines), $m)) {
896 return array(array(''), array(''));
897 }
898 return array($m[0], $m[1]);
899 }
900
901 function orig() {
902 $orig = new _HWLDF_WordAccumulator;
903
904 foreach ($this->edits as $edit) {
905 if ($edit->type == 'copy')
906 $orig->addWords($edit->orig);
907 elseif ($edit->orig)
908 $orig->addWords($edit->orig, 'mark');
909 }
910 return $orig->getLines();
911 }
912
913 function closing() {
914 $closing = new _HWLDF_WordAccumulator;
915
916 foreach ($this->edits as $edit) {
917 if ($edit->type == 'copy')
918 $closing->addWords($edit->closing);
919 elseif ($edit->closing)
920 $closing->addWords($edit->closing, 'mark');
921 }
922 return $closing->getLines();
923 }
924}
925
926class InlineWordLevelDiff extends MappedDiff {
927
928 function __construct($orig_lines, $closing_lines) {
929 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
930 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
931
932 parent::__construct($orig_words, $closing_words, $orig_stripped, $closing_stripped);
933 }
934
935 function _split($lines) {
936 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xsu',
937 implode("\n", $lines), $m)) {
938 return array(array(''), array(''));
939 }
940 return array($m[0], $m[1]);
941 }
942
943 function inline() {
944 $orig = new _HWLDF_WordAccumulator;
945 foreach ($this->edits as $edit) {
946 if ($edit->type == 'copy')
947 $orig->addWords($edit->closing);
948 elseif ($edit->type == 'change'){
949 $orig->addWords($edit->orig, 'del');
950 $orig->addWords($edit->closing, 'add');
951 } elseif ($edit->type == 'delete')
952 $orig->addWords($edit->orig, 'del');
953 elseif ($edit->type == 'add')
954 $orig->addWords($edit->closing, 'add');
955 elseif ($edit->orig)
956 $orig->addWords($edit->orig, 'del');
957 }
958 return $orig->getLines();
959 }
960}
961
962/**
963 * "Unified" diff formatter.
964 *
965 * This class formats the diff in classic "unified diff" format.
966 */
967class UnifiedDiffFormatter extends DiffFormatter {
968
969 function __construct($context_lines = 4) {
970 $this->leading_context_lines = $context_lines;
971 $this->trailing_context_lines = $context_lines;
972 }
973
974 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
975 if ($xlen != 1)
976 $xbeg .= "," . $xlen;
977 if ($ylen != 1)
978 $ybeg .= "," . $ylen;
979 return "@@ -$xbeg +$ybeg @@\n";
980 }
981
982 function _added($lines) {
983 $this->_lines($lines, "+");
984 }
985 function _deleted($lines) {
986 $this->_lines($lines, "-");
987 }
988 function _changed($orig, $final) {
989 $this->_deleted($orig);
990 $this->_added($final);
991 }
992}
993
994/**
995 * Wikipedia Table style diff formatter.
996 *
997 */
998class TableDiffFormatter extends DiffFormatter {
999
1000 function __construct() {
1001 $this->leading_context_lines = 2;
1002 $this->trailing_context_lines = 2;
1003 }
1004
1005 function format($diff) {
1006 // Preserve whitespaces by converting some to non-breaking spaces.
1007 // Do not convert all of them to allow word-wrap.
1008 $val = parent::format($diff);
1009 $val = str_replace(' ','&nbsp; ', $val);
1010 $val = preg_replace('/ (?=<)|(?<=[ >]) /', '&nbsp;', $val);
1011 return $val;
1012 }
1013
1014 function _pre($text){
1015 $text = htmlspecialchars($text);
1016 return $text;
1017 }
1018
1019 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1020 global $lang;
1021 $l1 = $lang['line'].' '.$xbeg;
1022 $l2 = $lang['line'].' '.$ybeg;
1023 $r = '<tr><td class="diff-blockheader" colspan="2">'.$l1.":</td>\n".
1024 '<td class="diff-blockheader" colspan="2">'.$l2.":</td>\n".
1025 "</tr>\n";
1026 return $r;
1027 }
1028
1029 function _start_block($header) {
1030 print($header);
1031 }
1032
1033 function _end_block() {
1034 }
1035
1036 function _lines($lines, $prefix=' ', $color="white") {
1037 }
1038
1039 function addedLine($line) {
1040 return '<td>+</td><td class="diff-addedline">' . $line.'</td>';
1041 }
1042
1043 function deletedLine($line) {
1044 return '<td>-</td><td class="diff-deletedline">' . $line.'</td>';
1045 }
1046
1047 function emptyLine() {
1048 return '<td colspan="2">&nbsp;</td>';
1049 }
1050
1051 function contextLine($line) {
1052 return '<td> </td><td class="diff-context">'.$line.'</td>';
1053 }
1054
1055 function _added($lines) {
1056 foreach ($lines as $line) {
1057 print('<tr>' . $this->emptyLine() . $this->addedLine($line) . "</tr>\n");
1058 }
1059 }
1060
1061 function _deleted($lines) {
1062 foreach ($lines as $line) {
1063 print('<tr>' . $this->deletedLine($line) . $this->emptyLine() . "</tr>\n");
1064 }
1065 }
1066
1067 function _context($lines) {
1068 foreach ($lines as $line) {
1069 print('<tr>' . $this->contextLine($line) . $this->contextLine($line) . "</tr>\n");
1070 }
1071 }
1072
1073 function _changed($orig, $closing) {
1074 $diff = new WordLevelDiff($orig, $closing);
1075 $del = $diff->orig();
1076 $add = $diff->closing();
1077
1078 while ($line = array_shift($del)) {
1079 $aline = array_shift($add);
1080 print('<tr>' . $this->deletedLine($line) . $this->addedLine($aline) . "</tr>\n");
1081 }
1082 $this->_added($add); # If any leftovers
1083 }
1084}
1085
1086/**
1087 * Inline style diff formatter.
1088 *
1089 */
1090class InlineDiffFormatter extends DiffFormatter {
1091 var $colspan = 4;
1092
1093 function __construct() {
1094 $this->leading_context_lines = 2;
1095 $this->trailing_context_lines = 2;
1096 }
1097
1098 function format($diff) {
1099 // Preserve whitespaces by converting some to non-breaking spaces.
1100 // Do not convert all of them to allow word-wrap.
1101 $val = parent::format($diff);
1102 $val = str_replace(' ','&nbsp; ', $val);
1103 $val = preg_replace('/ (?=<)|(?<=[ >]) /', '&nbsp;', $val);
1104 return $val;
1105 }
1106
1107 function _pre($text){
1108 $text = htmlspecialchars($text);
1109 return $text;
1110 }
1111
1112 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1113 global $lang;
1114 if ($xlen != 1)
1115 $xbeg .= "," . $xlen;
1116 if ($ylen != 1)
1117 $ybeg .= "," . $ylen;
1118 $r = '<tr><td colspan="'.$this->colspan.'" class="diff-blockheader">@@ '.$lang['line']." -$xbeg +$ybeg @@";
1119 $r .= ' <span class="diff-deletedline"><del>'.$lang['deleted'].'</del></span>';
1120 $r .= ' <span class="diff-addedline">'.$lang['created'].'</span>';
1121 $r .= "</td></tr>\n";
1122 return $r;
1123 }
1124
1125 function _start_block($header) {
1126 print($header."\n");
1127 }
1128
1129 function _end_block() {
1130 }
1131
1132 function _lines($lines, $prefix=' ', $color="white") {
1133 }
1134
1135 function _added($lines) {
1136 foreach ($lines as $line) {
1137 print('<tr><td colspan="'.$this->colspan.'" class="diff-addedline">'. $line . "</td></tr>\n");
1138 }
1139 }
1140
1141 function _deleted($lines) {
1142 foreach ($lines as $line) {
1143 print('<tr><td colspan="'.$this->colspan.'" class="diff-deletedline"><del>' . $line . "</del></td></tr>\n");
1144 }
1145 }
1146
1147 function _context($lines) {
1148 foreach ($lines as $line) {
1149 print('<tr><td colspan="'.$this->colspan.'" class="diff-context">'.$line."</td></tr>\n");
1150 }
1151 }
1152
1153 function _changed($orig, $closing) {
1154 $diff = new InlineWordLevelDiff($orig, $closing);
1155 $add = $diff->inline();
1156
1157 foreach ($add as $line)
1158 print('<tr><td colspan="'.$this->colspan.'">'.$line."</td></tr>\n");
1159 }
1160}
1161
1162
1163//Setup VIM: ex: et ts=4 :
Note: See TracBrowser for help on using the repository browser.