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