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