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