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