* standardised file headers
[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 _DiffOp_Copy ($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 _DiffOp_Delete ($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 _DiffOp_Add ($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 _DiffOp_Change ($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 while (list ( /* $junk */, $y) = each($matches)) {
323 if ($y > $this->seq[$k-1]) {
324 assert($y < $this->seq[$k]);
325 // Optimization: this is a common case:
326 // next match is just replacing previous match.
327 $this->in_seq[$this->seq[$k]] = false;
328 $this->seq[$k] = $y;
329 $this->in_seq[$y] = 1;
330 } else if (empty($this->in_seq[$y])) {
331 $k = $this->_lcs_pos($y);
332 assert($k > 0);
333 $ymids[$k] = $ymids[$k-1];
334 }
335 }
336 }
337 }
338
339 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
340 $ymid = $ymids[$this->lcs];
341 for ($n = 0; $n < $nchunks - 1; $n++) {
342 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
343 $y1 = $ymid[$n] + 1;
344 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
345 }
346 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
347
348 return array($this->lcs, $seps);
349 }
350
351 function _lcs_pos ($ypos) {
352 $end = $this->lcs;
353 if ($end == 0 || $ypos > $this->seq[$end]) {
354 $this->seq[++$this->lcs] = $ypos;
355 $this->in_seq[$ypos] = 1;
356 return $this->lcs;
357 }
358
359 $beg = 1;
360 while ($beg < $end) {
361 $mid = (int)(($beg + $end) / 2);
362 if ( $ypos > $this->seq[$mid] )
363 $beg = $mid + 1;
364 else
365 $end = $mid;
366 }
367
368 assert($ypos != $this->seq[$end]);
369
370 $this->in_seq[$this->seq[$end]] = false;
371 $this->seq[$end] = $ypos;
372 $this->in_seq[$ypos] = 1;
373 return $end;
374 }
375
376 /* Find LCS of two sequences.
377 *
378 * The results are recorded in the vectors $this->{x,y}changed[], by
379 * storing a 1 in the element for each line that is an insertion
380 * or deletion (ie. is not in the LCS).
381 *
382 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
383 *
384 * Note that XLIM, YLIM are exclusive bounds.
385 * All line numbers are origin-0 and discarded lines are not counted.
386 */
387 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
388 // Slide down the bottom initial diagonal.
389 while ($xoff < $xlim && $yoff < $ylim
390 && $this->xv[$xoff] == $this->yv[$yoff]) {
391 ++$xoff;
392 ++$yoff;
393 }
394
395 // Slide up the top initial diagonal.
396 while ($xlim > $xoff && $ylim > $yoff
397 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
398 --$xlim;
399 --$ylim;
400 }
401
402 if ($xoff == $xlim || $yoff == $ylim)
403 $lcs = 0;
404 else {
405 // This is ad hoc but seems to work well.
406 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
407 //$nchunks = max(2,min(8,(int)$nchunks));
408 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
409 list ($lcs, $seps)
410 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
411 }
412
413 if ($lcs == 0) {
414 // X and Y sequences have no common subsequence:
415 // mark all changed.
416 while ($yoff < $ylim)
417 $this->ychanged[$this->yind[$yoff++]] = 1;
418 while ($xoff < $xlim)
419 $this->xchanged[$this->xind[$xoff++]] = 1;
420 } else {
421 // Use the partitions to split this problem into subproblems.
422 reset($seps);
423 $pt1 = $seps[0];
424 while ($pt2 = next($seps)) {
425 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
426 $pt1 = $pt2;
427 }
428 }
429 }
430
431 /* Adjust inserts/deletes of identical lines to join changes
432 * as much as possible.
433 *
434 * We do something when a run of changed lines include a
435 * line at one end and has an excluded, identical line at the other.
436 * We are free to choose which identical line is included.
437 * `compareseq' usually chooses the one at the beginning,
438 * but usually it is cleaner to consider the following identical line
439 * to be the "change".
440 *
441 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
442 */
443 function _shift_boundaries ($lines, &$changed, $other_changed) {
444 wfProfileIn( __METHOD__ );
445 $i = 0;
446 $j = 0;
447
448 assert('sizeof($lines) == sizeof($changed)');
449 $len = sizeof($lines);
450 $other_len = sizeof($other_changed);
451
452 while (1) {
453 /*
454 * Scan forwards to find beginning of another run of changes.
455 * Also keep track of the corresponding point in the other file.
456 *
457 * Throughout this code, $i and $j are adjusted together so that
458 * the first $i elements of $changed and the first $j elements
459 * of $other_changed both contain the same number of zeros
460 * (unchanged lines).
461 * Furthermore, $j is always kept so that $j == $other_len or
462 * $other_changed[$j] == false.
463 */
464 while ($j < $other_len && $other_changed[$j])
465 $j++;
466
467 while ($i < $len && ! $changed[$i]) {
468 assert('$j < $other_len && ! $other_changed[$j]');
469 $i++; $j++;
470 while ($j < $other_len && $other_changed[$j])
471 $j++;
472 }
473
474 if ($i == $len)
475 break;
476
477 $start = $i;
478
479 // Find the end of this run of changes.
480 while (++$i < $len && $changed[$i])
481 continue;
482
483 do {
484 /*
485 * Record the length of this run of changes, so that
486 * we can later determine whether the run has grown.
487 */
488 $runlength = $i - $start;
489
490 /*
491 * Move the changed region back, so long as the
492 * previous unchanged line matches the last changed one.
493 * This merges with previous changed regions.
494 */
495 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
496 $changed[--$start] = 1;
497 $changed[--$i] = false;
498 while ($start > 0 && $changed[$start - 1])
499 $start--;
500 assert('$j > 0');
501 while ($other_changed[--$j])
502 continue;
503 assert('$j >= 0 && !$other_changed[$j]');
504 }
505
506 /*
507 * Set CORRESPONDING to the end of the changed run, at the last
508 * point where it corresponds to a changed run in the other file.
509 * CORRESPONDING == LEN means no such point has been found.
510 */
511 $corresponding = $j < $other_len ? $i : $len;
512
513 /*
514 * Move the changed region forward, so long as the
515 * first changed line matches the following unchanged one.
516 * This merges with following changed regions.
517 * Do this second, so that if there are no merges,
518 * the changed region is moved forward as far as possible.
519 */
520 while ($i < $len && $lines[$start] == $lines[$i]) {
521 $changed[$start++] = false;
522 $changed[$i++] = 1;
523 while ($i < $len && $changed[$i])
524 $i++;
525
526 assert('$j < $other_len && ! $other_changed[$j]');
527 $j++;
528 if ($j < $other_len && $other_changed[$j]) {
529 $corresponding = $i;
530 while ($j < $other_len && $other_changed[$j])
531 $j++;
532 }
533 }
534 } while ($runlength != $i - $start);
535
536 /*
537 * If possible, move the fully-merged run of changes
538 * back to a corresponding run in the other file.
539 */
540 while ($corresponding < $i) {
541 $changed[--$start] = 1;
542 $changed[--$i] = 0;
543 assert('$j > 0');
544 while ($other_changed[--$j])
545 continue;
546 assert('$j >= 0 && !$other_changed[$j]');
547 }
548 }
549 wfProfileOut( __METHOD__ );
550 }
551 }
552
553 /**
554 * Class representing a 'diff' between two sequences of strings.
555 * @todo document
556 * @private
557 * @ingroup DifferenceEngine
558 */
559 class Diff
560 {
561 var $edits;
562
563 /**
564 * Constructor.
565 * Computes diff between sequences of strings.
566 *
567 * @param $from_lines array An array of strings.
568 * (Typically these are lines from a file.)
569 * @param $to_lines array An array of strings.
570 */
571 function Diff($from_lines, $to_lines) {
572 $eng = new _DiffEngine;
573 $this->edits = $eng->diff($from_lines, $to_lines);
574 //$this->_check($from_lines, $to_lines);
575 }
576
577 /**
578 * Compute reversed Diff.
579 *
580 * SYNOPSIS:
581 *
582 * $diff = new Diff($lines1, $lines2);
583 * $rev = $diff->reverse();
584 * @return object A Diff object representing the inverse of the
585 * original diff.
586 */
587 function reverse () {
588 $rev = $this;
589 $rev->edits = array();
590 foreach ($this->edits as $edit) {
591 $rev->edits[] = $edit->reverse();
592 }
593 return $rev;
594 }
595
596 /**
597 * Check for empty diff.
598 *
599 * @return bool True iff two sequences were identical.
600 */
601 function isEmpty () {
602 foreach ($this->edits as $edit) {
603 if ($edit->type != 'copy')
604 return false;
605 }
606 return true;
607 }
608
609 /**
610 * Compute the length of the Longest Common Subsequence (LCS).
611 *
612 * This is mostly for diagnostic purposed.
613 *
614 * @return int The length of the LCS.
615 */
616 function lcs () {
617 $lcs = 0;
618 foreach ($this->edits as $edit) {
619 if ($edit->type == 'copy')
620 $lcs += sizeof($edit->orig);
621 }
622 return $lcs;
623 }
624
625 /**
626 * Get the original set of lines.
627 *
628 * This reconstructs the $from_lines parameter passed to the
629 * constructor.
630 *
631 * @return array The original sequence of strings.
632 */
633 function orig() {
634 $lines = array();
635
636 foreach ($this->edits as $edit) {
637 if ($edit->orig)
638 array_splice($lines, sizeof($lines), 0, $edit->orig);
639 }
640 return $lines;
641 }
642
643 /**
644 * Get the closing set of lines.
645 *
646 * This reconstructs the $to_lines parameter passed to the
647 * constructor.
648 *
649 * @return array The sequence of strings.
650 */
651 function closing() {
652 $lines = array();
653
654 foreach ($this->edits as $edit) {
655 if ($edit->closing)
656 array_splice($lines, sizeof($lines), 0, $edit->closing);
657 }
658 return $lines;
659 }
660
661 /**
662 * Check a Diff for validity.
663 *
664 * This is here only for debugging purposes.
665 */
666 function _check ($from_lines, $to_lines) {
667 wfProfileIn( __METHOD__ );
668 if (serialize($from_lines) != serialize($this->orig()))
669 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
670 if (serialize($to_lines) != serialize($this->closing()))
671 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
672
673 $rev = $this->reverse();
674 if (serialize($to_lines) != serialize($rev->orig()))
675 trigger_error("Reversed original doesn't match", E_USER_ERROR);
676 if (serialize($from_lines) != serialize($rev->closing()))
677 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
678
679
680 $prevtype = 'none';
681 foreach ($this->edits as $edit) {
682 if ( $prevtype == $edit->type )
683 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
684 $prevtype = $edit->type;
685 }
686
687 $lcs = $this->lcs();
688 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
689 wfProfileOut( __METHOD__ );
690 }
691 }
692
693 /**
694 * @todo document, bad name.
695 * @private
696 * @ingroup DifferenceEngine
697 */
698 class MappedDiff extends Diff
699 {
700 /**
701 * Constructor.
702 *
703 * Computes diff between sequences of strings.
704 *
705 * This can be used to compute things like
706 * case-insensitve diffs, or diffs which ignore
707 * changes in white-space.
708 *
709 * @param $from_lines array An array of strings.
710 * (Typically these are lines from a file.)
711 *
712 * @param $to_lines array An array of strings.
713 *
714 * @param $mapped_from_lines array This array should
715 * have the same size number of elements as $from_lines.
716 * The elements in $mapped_from_lines and
717 * $mapped_to_lines are what is actually compared
718 * when computing the diff.
719 *
720 * @param $mapped_to_lines array This array should
721 * have the same number of elements as $to_lines.
722 */
723 function MappedDiff($from_lines, $to_lines,
724 $mapped_from_lines, $mapped_to_lines) {
725 wfProfileIn( __METHOD__ );
726
727 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
728 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
729
730 $this->Diff($mapped_from_lines, $mapped_to_lines);
731
732 $xi = $yi = 0;
733 for ($i = 0; $i < sizeof($this->edits); $i++) {
734 $orig = &$this->edits[$i]->orig;
735 if (is_array($orig)) {
736 $orig = array_slice($from_lines, $xi, sizeof($orig));
737 $xi += sizeof($orig);
738 }
739
740 $closing = &$this->edits[$i]->closing;
741 if (is_array($closing)) {
742 $closing = array_slice($to_lines, $yi, sizeof($closing));
743 $yi += sizeof($closing);
744 }
745 }
746 wfProfileOut( __METHOD__ );
747 }
748 }
749
750 /**
751 * A class to format Diffs
752 *
753 * This class formats the diff in classic diff format.
754 * It is intended that this class be customized via inheritance,
755 * to obtain fancier outputs.
756 * @todo document
757 * @private
758 * @ingroup DifferenceEngine
759 */
760 class DiffFormatter {
761 /**
762 * Number of leading context "lines" to preserve.
763 *
764 * This should be left at zero for this class, but subclasses
765 * may want to set this to other values.
766 */
767 var $leading_context_lines = 0;
768
769 /**
770 * Number of trailing context "lines" to preserve.
771 *
772 * This should be left at zero for this class, but subclasses
773 * may want to set this to other values.
774 */
775 var $trailing_context_lines = 0;
776
777 /**
778 * Format a diff.
779 *
780 * @param $diff object A Diff object.
781 * @return string The formatted output.
782 */
783 function format($diff) {
784 wfProfileIn( __METHOD__ );
785
786 $xi = $yi = 1;
787 $block = false;
788 $context = array();
789
790 $nlead = $this->leading_context_lines;
791 $ntrail = $this->trailing_context_lines;
792
793 $this->_start_diff();
794
795 foreach ($diff->edits as $edit) {
796 if ($edit->type == 'copy') {
797 if (is_array($block)) {
798 if (sizeof($edit->orig) <= $nlead + $ntrail) {
799 $block[] = $edit;
800 }
801 else{
802 if ($ntrail) {
803 $context = array_slice($edit->orig, 0, $ntrail);
804 $block[] = new _DiffOp_Copy($context);
805 }
806 $this->_block($x0, $ntrail + $xi - $x0,
807 $y0, $ntrail + $yi - $y0,
808 $block);
809 $block = false;
810 }
811 }
812 $context = $edit->orig;
813 }
814 else {
815 if (! is_array($block)) {
816 $context = array_slice($context, sizeof($context) - $nlead);
817 $x0 = $xi - sizeof($context);
818 $y0 = $yi - sizeof($context);
819 $block = array();
820 if ($context)
821 $block[] = new _DiffOp_Copy($context);
822 }
823 $block[] = $edit;
824 }
825
826 if ($edit->orig)
827 $xi += sizeof($edit->orig);
828 if ($edit->closing)
829 $yi += sizeof($edit->closing);
830 }
831
832 if (is_array($block))
833 $this->_block($x0, $xi - $x0,
834 $y0, $yi - $y0,
835 $block);
836
837 $end = $this->_end_diff();
838 wfProfileOut( __METHOD__ );
839 return $end;
840 }
841
842 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
843 wfProfileIn( __METHOD__ );
844 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
845 foreach ($edits as $edit) {
846 if ($edit->type == 'copy')
847 $this->_context($edit->orig);
848 elseif ($edit->type == 'add')
849 $this->_added($edit->closing);
850 elseif ($edit->type == 'delete')
851 $this->_deleted($edit->orig);
852 elseif ($edit->type == 'change')
853 $this->_changed($edit->orig, $edit->closing);
854 else
855 trigger_error('Unknown edit type', E_USER_ERROR);
856 }
857 $this->_end_block();
858 wfProfileOut( __METHOD__ );
859 }
860
861 function _start_diff() {
862 ob_start();
863 }
864
865 function _end_diff() {
866 $val = ob_get_contents();
867 ob_end_clean();
868 return $val;
869 }
870
871 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
872 if ($xlen > 1)
873 $xbeg .= "," . ($xbeg + $xlen - 1);
874 if ($ylen > 1)
875 $ybeg .= "," . ($ybeg + $ylen - 1);
876
877 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
878 }
879
880 function _start_block($header) {
881 echo $header . "\n";
882 }
883
884 function _end_block() {
885 }
886
887 function _lines($lines, $prefix = ' ') {
888 foreach ($lines as $line)
889 echo "$prefix $line\n";
890 }
891
892 function _context($lines) {
893 $this->_lines($lines);
894 }
895
896 function _added($lines) {
897 $this->_lines($lines, '>');
898 }
899 function _deleted($lines) {
900 $this->_lines($lines, '<');
901 }
902
903 function _changed($orig, $closing) {
904 $this->_deleted($orig);
905 echo "---\n";
906 $this->_added($closing);
907 }
908 }
909
910 /**
911 * A formatter that outputs unified diffs
912 * @ingroup DifferenceEngine
913 */
914
915 class UnifiedDiffFormatter extends DiffFormatter {
916 var $leading_context_lines = 2;
917 var $trailing_context_lines = 2;
918
919 function _added($lines) {
920 $this->_lines($lines, '+');
921 }
922 function _deleted($lines) {
923 $this->_lines($lines, '-');
924 }
925 function _changed($orig, $closing) {
926 $this->_deleted($orig);
927 $this->_added($closing);
928 }
929 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
930 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
931 }
932 }
933
934 /**
935 * A pseudo-formatter that just passes along the Diff::$edits array
936 * @ingroup DifferenceEngine
937 */
938 class ArrayDiffFormatter extends DiffFormatter {
939 function format($diff) {
940 $oldline = 1;
941 $newline = 1;
942 $retval = array();
943 foreach($diff->edits as $edit)
944 switch($edit->type) {
945 case 'add':
946 foreach($edit->closing as $l) {
947 $retval[] = array(
948 'action' => 'add',
949 'new'=> $l,
950 'newline' => $newline++
951 );
952 }
953 break;
954 case 'delete':
955 foreach($edit->orig as $l) {
956 $retval[] = array(
957 'action' => 'delete',
958 'old' => $l,
959 'oldline' => $oldline++,
960 );
961 }
962 break;
963 case 'change':
964 foreach($edit->orig as $i => $l) {
965 $retval[] = array(
966 'action' => 'change',
967 'old' => $l,
968 'new' => @$edit->closing[$i],
969 'oldline' => $oldline++,
970 'newline' => $newline++,
971 );
972 }
973 break;
974 case 'copy':
975 $oldline += count($edit->orig);
976 $newline += count($edit->orig);
977 }
978 return $retval;
979 }
980 }
981
982 /**
983 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
984 *
985 */
986
987 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
988
989 /**
990 * @todo document
991 * @private
992 * @ingroup DifferenceEngine
993 */
994 class _HWLDF_WordAccumulator {
995 function _HWLDF_WordAccumulator () {
996 $this->_lines = array();
997 $this->_line = '';
998 $this->_group = '';
999 $this->_tag = '';
1000 }
1001
1002 function _flushGroup ($new_tag) {
1003 if ($this->_group !== '') {
1004 if ($this->_tag == 'ins')
1005 $this->_line .= '<ins class="diffchange diffchange-inline">' .
1006 htmlspecialchars ( $this->_group ) . '</ins>';
1007 elseif ($this->_tag == 'del')
1008 $this->_line .= '<del class="diffchange diffchange-inline">' .
1009 htmlspecialchars ( $this->_group ) . '</del>';
1010 else
1011 $this->_line .= htmlspecialchars ( $this->_group );
1012 }
1013 $this->_group = '';
1014 $this->_tag = $new_tag;
1015 }
1016
1017 function _flushLine ($new_tag) {
1018 $this->_flushGroup($new_tag);
1019 if ($this->_line != '')
1020 array_push ( $this->_lines, $this->_line );
1021 else
1022 # make empty lines visible by inserting an NBSP
1023 array_push ( $this->_lines, NBSP );
1024 $this->_line = '';
1025 }
1026
1027 function addWords ($words, $tag = '') {
1028 if ($tag != $this->_tag)
1029 $this->_flushGroup($tag);
1030
1031 foreach ($words as $word) {
1032 // new-line should only come as first char of word.
1033 if ($word == '')
1034 continue;
1035 if ($word[0] == "\n") {
1036 $this->_flushLine($tag);
1037 $word = substr($word, 1);
1038 }
1039 assert(!strstr($word, "\n"));
1040 $this->_group .= $word;
1041 }
1042 }
1043
1044 function getLines() {
1045 $this->_flushLine('~done');
1046 return $this->_lines;
1047 }
1048 }
1049
1050 /**
1051 * @todo document
1052 * @private
1053 * @ingroup DifferenceEngine
1054 */
1055 class WordLevelDiff extends MappedDiff {
1056 const MAX_LINE_LENGTH = 10000;
1057
1058 function WordLevelDiff ($orig_lines, $closing_lines) {
1059 wfProfileIn( __METHOD__ );
1060
1061 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1062 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1063
1064 $this->MappedDiff($orig_words, $closing_words,
1065 $orig_stripped, $closing_stripped);
1066 wfProfileOut( __METHOD__ );
1067 }
1068
1069 function _split($lines) {
1070 wfProfileIn( __METHOD__ );
1071
1072 $words = array();
1073 $stripped = array();
1074 $first = true;
1075 foreach ( $lines as $line ) {
1076 # If the line is too long, just pretend the entire line is one big word
1077 # This prevents resource exhaustion problems
1078 if ( $first ) {
1079 $first = false;
1080 } else {
1081 $words[] = "\n";
1082 $stripped[] = "\n";
1083 }
1084 if ( strlen( $line ) > self::MAX_LINE_LENGTH ) {
1085 $words[] = $line;
1086 $stripped[] = $line;
1087 } else {
1088 $m = array();
1089 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1090 $line, $m))
1091 {
1092 $words = array_merge( $words, $m[0] );
1093 $stripped = array_merge( $stripped, $m[1] );
1094 }
1095 }
1096 }
1097 wfProfileOut( __METHOD__ );
1098 return array($words, $stripped);
1099 }
1100
1101 function orig () {
1102 wfProfileIn( __METHOD__ );
1103 $orig = new _HWLDF_WordAccumulator;
1104
1105 foreach ($this->edits as $edit) {
1106 if ($edit->type == 'copy')
1107 $orig->addWords($edit->orig);
1108 elseif ($edit->orig)
1109 $orig->addWords($edit->orig, 'del');
1110 }
1111 $lines = $orig->getLines();
1112 wfProfileOut( __METHOD__ );
1113 return $lines;
1114 }
1115
1116 function closing () {
1117 wfProfileIn( __METHOD__ );
1118 $closing = new _HWLDF_WordAccumulator;
1119
1120 foreach ($this->edits as $edit) {
1121 if ($edit->type == 'copy')
1122 $closing->addWords($edit->closing);
1123 elseif ($edit->closing)
1124 $closing->addWords($edit->closing, 'ins');
1125 }
1126 $lines = $closing->getLines();
1127 wfProfileOut( __METHOD__ );
1128 return $lines;
1129 }
1130 }
1131
1132 /**
1133 * Wikipedia Table style diff formatter.
1134 * @todo document
1135 * @private
1136 * @ingroup DifferenceEngine
1137 */
1138 class TableDiffFormatter extends DiffFormatter {
1139 function TableDiffFormatter() {
1140 $this->leading_context_lines = 2;
1141 $this->trailing_context_lines = 2;
1142 }
1143
1144 public static function escapeWhiteSpace( $msg ) {
1145 $msg = preg_replace( '/^ /m', '&#160; ', $msg );
1146 $msg = preg_replace( '/ $/m', ' &#160;', $msg );
1147 $msg = preg_replace( '/ /', '&#160; ', $msg );
1148 return $msg;
1149 }
1150
1151 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1152 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1153 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1154 return $r;
1155 }
1156
1157 function _start_block( $header ) {
1158 echo $header;
1159 }
1160
1161 function _end_block() {
1162 }
1163
1164 function _lines( $lines, $prefix=' ', $color='white' ) {
1165 }
1166
1167 # HTML-escape parameter before calling this
1168 function addedLine( $line ) {
1169 return $this->wrapLine( '+', 'diff-addedline', $line );
1170 }
1171
1172 # HTML-escape parameter before calling this
1173 function deletedLine( $line ) {
1174 return $this->wrapLine( '-', 'diff-deletedline', $line );
1175 }
1176
1177 # HTML-escape parameter before calling this
1178 function contextLine( $line ) {
1179 return $this->wrapLine( ' ', 'diff-context', $line );
1180 }
1181
1182 private function wrapLine( $marker, $class, $line ) {
1183 if( $line !== '' ) {
1184 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1185 $line = Xml::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1186 }
1187 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1188 }
1189
1190 function emptyLine() {
1191 return '<td colspan="2">&#160;</td>';
1192 }
1193
1194 function _added( $lines ) {
1195 foreach ($lines as $line) {
1196 echo '<tr>' . $this->emptyLine() .
1197 $this->addedLine( '<ins class="diffchange">' .
1198 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1199 }
1200 }
1201
1202 function _deleted($lines) {
1203 foreach ($lines as $line) {
1204 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1205 htmlspecialchars ( $line ) . '</del>' ) .
1206 $this->emptyLine() . "</tr>\n";
1207 }
1208 }
1209
1210 function _context( $lines ) {
1211 foreach ($lines as $line) {
1212 echo '<tr>' .
1213 $this->contextLine( htmlspecialchars ( $line ) ) .
1214 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1215 }
1216 }
1217
1218 function _changed( $orig, $closing ) {
1219 wfProfileIn( __METHOD__ );
1220
1221 $diff = new WordLevelDiff( $orig, $closing );
1222 $del = $diff->orig();
1223 $add = $diff->closing();
1224
1225 # Notice that WordLevelDiff returns HTML-escaped output.
1226 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1227
1228 while ( $line = array_shift( $del ) ) {
1229 $aline = array_shift( $add );
1230 echo '<tr>' . $this->deletedLine( $line ) .
1231 $this->addedLine( $aline ) . "</tr>\n";
1232 }
1233 foreach ($add as $line) { # If any leftovers
1234 echo '<tr>' . $this->emptyLine() .
1235 $this->addedLine( $line ) . "</tr>\n";
1236 }
1237 wfProfileOut( __METHOD__ );
1238 }
1239 }