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