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