bug fix in range block code, spelling error
[mediawiki.git] / includes / DifferenceEngine.php
blob712690c5f2ca8c277b6034046f880b0ba5698480
1 <?
2 # See diff.doc
4 class DifferenceEngine {
5 /* private */ var $mOldid, $mNewid;
6 /* private */ var $mOldtitle, $mNewtitle;
7 /* private */ var $mOldtext, $mNewtext;
9 function DifferenceEngine( $old, $new )
11 $this->mOldid = $old;
12 $this->mNewid = $new;
15 function showDiffPage()
17 global $wgUser, $wgTitle, $wgOut, $wgLang;
19 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
20 "{$this->mNewid})";
21 $mtext = wfMsg( "missingarticle", $t );
23 $wgOut->setArticleFlag( false );
24 if ( ! $this->loadText() ) {
25 $wgOut->setPagetitle( wfMsg( "errorpagetitle" ) );
26 $wgOut->addHTML( $mtext );
27 return;
29 $wgOut->supressQuickbar();
30 $wgOut->setSubtitle( wfMsg( "difference" ) );
31 $wgOut->setRobotpolicy( "noindex,follow" );
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 );
39 function showDiff( $otext, $ntext, $otitle, $ntitle )
41 global $wgOut;
43 $ota = explode( "\n", str_replace( "\r\n", "\n",
44 htmlspecialchars( $otext ) ) );
45 $nta = explode( "\n", str_replace( "\r\n", "\n",
46 htmlspecialchars( $ntext ) ) );
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" );
56 $diffs = new Diff( $ota, $nta );
57 $formatter = new TableDiffFormatter();
58 $formatter->format( $diffs );
59 $wgOut->addHTML( "</table>\n" );
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).
67 function loadText()
69 global $wgTitle, $wgOut, $wgLang;
70 $fname = "DifferenceEngine::loadText";
72 if ( 0 == $this->mNewid || 0 == $this->mOldid ) {
73 $wgOut->setArticleFlag( true );
74 $this->mNewtitle = wfMsg( "currentrev" );
75 $id = $wgTitle->getArticleID();
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; }
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}";
87 $res = wfQuery( $sql, DB_READ, $fname );
88 if ( 0 == wfNumRows( $res ) ) { return false; }
90 $s = wfFetchObject( $res );
91 $this->mNewtext = $s->old_text;
93 $t = $wgLang->timeanddate( $s->old_timestamp, true );
94 $this->mNewtitle = wfMsg( "revisionasof", $t );
96 if ( 0 == $this->mOldid ) {
97 $sql = "SELECT old_timestamp,old_text 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 FROM old WHERE " .
104 "old_id={$this->mOldid}";
105 $res = wfQuery( $sql, DB_READ, $fname );
107 if ( 0 == wfNumRows( $res ) ) { return false; }
109 $s = wfFetchObject( $res );
110 $this->mOldtext = $s->old_text;
112 $t = $wgLang->timeanddate( $s->old_timestamp, true );
113 $this->mOldtitle = wfMsg( "revisionasof", $t );
115 return true;
119 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
121 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
122 // You may copy this code freely under the conditions of the GPL.
125 define('USE_ASSERTS', function_exists('assert'));
127 class _DiffOp {
128 var $type;
129 var $orig;
130 var $final;
132 function reverse() {
133 trigger_error("pure virtual", E_USER_ERROR);
136 function norig() {
137 return $this->orig ? sizeof($this->orig) : 0;
140 function nfinal() {
141 return $this->final ? sizeof($this->final) : 0;
145 class _DiffOp_Copy extends _DiffOp {
146 var $type = 'copy';
148 function _DiffOp_Copy ($orig, $final = false) {
149 if (!is_array($final))
150 $final = $orig;
151 $this->orig = $orig;
152 $this->final = $final;
155 function reverse() {
156 return new _DiffOp_Copy($this->final, $this->orig);
160 class _DiffOp_Delete extends _DiffOp {
161 var $type = 'delete';
163 function _DiffOp_Delete ($lines) {
164 $this->orig = $lines;
165 $this->final = false;
168 function reverse() {
169 return new _DiffOp_Add($this->orig);
173 class _DiffOp_Add extends _DiffOp {
174 var $type = 'add';
176 function _DiffOp_Add ($lines) {
177 $this->final = $lines;
178 $this->orig = false;
181 function reverse() {
182 return new _DiffOp_Delete($this->final);
186 class _DiffOp_Change extends _DiffOp {
187 var $type = 'change';
189 function _DiffOp_Change ($orig, $final) {
190 $this->orig = $orig;
191 $this->final = $final;
194 function reverse() {
195 return new _DiffOp_Change($this->final, $this->orig);
201 * Class used internally by Diff to actually compute the diffs.
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
207 * More ideas are taken from:
208 * http://www.ics.uci.edu/~eppstein/161/960229.html
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
214 * Finally, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
215 * are my own.
217 * @author Geoffrey T. Dairiki
218 * @access private
220 class _DiffEngine
222 function diff ($from_lines, $to_lines) {
223 $n_from = sizeof($from_lines);
224 $n_to = sizeof($to_lines);
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);
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;
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;
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;
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;
266 // Find the LCS.
267 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
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);
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]);
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;
287 if ($copy)
288 $edits[] = new _DiffOp_Copy($copy);
290 // Find deletes & adds.
291 $delete = array();
292 while ($xi < $n_from && $this->xchanged[$xi])
293 $delete[] = $from_lines[$xi++];
295 $add = array();
296 while ($yi < $n_to && $this->ychanged[$yi])
297 $add[] = $to_lines[$yi++];
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);
306 return $edits;
310 /* Divide the Largest Common Subsequence (LCS) of the sequences
311 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
312 * sized segments.
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).
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.
326 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
327 $flip = false;
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);
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;
344 $this->lcs = 0;
345 $this->seq[0]= $yoff - 1;
346 $this->in_seq = array();
347 $ymids[0] = array();
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];
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;
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;
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];
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);
395 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
397 return array($this->lcs, $seps);
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;
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;
417 USE_ASSERTS && assert($ypos != $this->seq[$end]);
419 $this->in_seq[$this->seq[$end]] = false;
420 $this->seq[$end] = $ypos;
421 $this->in_seq[$ypos] = 1;
422 return $end;
425 /* Find LCS of two sequences.
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).
431 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
433 * Note that XLIM, YLIM are exclusive bounds.
434 * All line numbers are origin-0 and discarded lines are not counted.
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;
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;
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);
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;
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;
481 /* Adjust inserts/deletes of identical lines to join changes
482 * as much as possible.
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".
491 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
493 function _shift_boundaries ($lines, &$changed, $other_changed) {
494 $i = 0;
495 $j = 0;
497 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
498 $len = sizeof($lines);
499 $other_len = sizeof($other_changed);
501 while (1) {
503 * Scan forwards to find beginning of another run of changes.
504 * Also keep track of the corresponding point in the other file.
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.
513 while ($j < $other_len && $other_changed[$j])
514 $j++;
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++;
523 if ($i == $len)
524 break;
526 $start = $i;
528 // Find the end of this run of changes.
529 while (++$i < $len && $changed[$i])
530 continue;
532 do {
534 * Record the length of this run of changes, so that
535 * we can later determine whether the run has grown.
537 $runlength = $i - $start;
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.
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]');
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.
560 $corresponding = $j < $other_len ? $i : $len;
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.
569 while ($i < $len && $lines[$start] == $lines[$i]) {
570 $changed[$start++] = false;
571 $changed[$i++] = 1;
572 while ($i < $len && $changed[$i])
573 $i++;
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++;
583 } while ($runlength != $i - $start);
586 * If possible, move the fully-merged run of changes
587 * back to a corresponding run in the other file.
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]');
602 * Class representing a 'diff' between two sequences of strings.
604 class Diff
606 var $edits;
609 * Constructor.
610 * Computes diff between sequences of strings.
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.
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);
623 * Compute reversed Diff.
625 * SYNOPSIS:
627 * $diff = new Diff($lines1, $lines2);
628 * $rev = $diff->reverse();
629 * @return object A Diff object representing the inverse of the
630 * original diff.
632 function reverse () {
633 $rev = $this;
634 $rev->edits = array();
635 foreach ($this->edits as $edit) {
636 $rev->edits[] = $edit->reverse();
638 return $rev;
642 * Check for empty diff.
644 * @return bool True iff two sequences were identical.
646 function isEmpty () {
647 foreach ($this->edits as $edit) {
648 if ($edit->type != 'copy')
649 return false;
651 return true;
655 * Compute the length of the Longest Common Subsequence (LCS).
657 * This is mostly for diagnostic purposed.
659 * @return int The length of the LCS.
661 function lcs () {
662 $lcs = 0;
663 foreach ($this->edits as $edit) {
664 if ($edit->type == 'copy')
665 $lcs += sizeof($edit->orig);
667 return $lcs;
671 * Get the original set of lines.
673 * This reconstructs the $from_lines parameter passed to the
674 * constructor.
676 * @return array The original sequence of strings.
678 function orig() {
679 $lines = array();
681 foreach ($this->edits as $edit) {
682 if ($edit->orig)
683 array_splice($lines, sizeof($lines), 0, $edit->orig);
685 return $lines;
689 * Get the final set of lines.
691 * This reconstructs the $to_lines parameter passed to the
692 * constructor.
694 * @return array The sequence of strings.
696 function final() {
697 $lines = array();
699 foreach ($this->edits as $edit) {
700 if ($edit->final)
701 array_splice($lines, sizeof($lines), 0, $edit->final);
703 return $lines;
707 * Check a Diff for validity.
709 * This is here only for debugging purposes.
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->final()))
715 trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
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->final()))
721 trigger_error("Reversed final doesn't match", E_USER_ERROR);
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;
731 $lcs = $this->lcs();
732 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
737 * FIXME: bad name.
739 class MappedDiff
740 extends Diff
743 * Constructor.
745 * Computes diff between sequences of strings.
747 * This can be used to compute things like
748 * case-insensitve diffs, or diffs which ignore
749 * changes in white-space.
751 * @param $from_lines array An array of strings.
752 * (Typically these are lines from a file.)
754 * @param $to_lines array An array of strings.
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.
762 * @param $mapped_to_lines array This array should
763 * have the same number of elements as $to_lines.
765 function MappedDiff($from_lines, $to_lines,
766 $mapped_from_lines, $mapped_to_lines) {
768 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
769 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
771 $this->Diff($mapped_from_lines, $mapped_to_lines);
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);
781 $final = &$this->edits[$i]->final;
782 if (is_array($final)) {
783 $final = array_slice($to_lines, $yi, sizeof($final));
784 $yi += sizeof($final);
791 * A class to format Diffs
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.
797 class DiffFormatter
800 * Number of leading context "lines" to preserve.
802 * This should be left at zero for this class, but subclasses
803 * may want to set this to other values.
805 var $leading_context_lines = 0;
808 * Number of trailing context "lines" to preserve.
810 * This should be left at zero for this class, but subclasses
811 * may want to set this to other values.
813 var $trailing_context_lines = 0;
816 * Format a diff.
818 * @param $diff object A Diff object.
819 * @return string The formatted output.
821 function format($diff) {
823 $xi = $yi = 1;
824 $block = false;
825 $context = array();
827 $nlead = $this->leading_context_lines;
828 $ntrail = $this->trailing_context_lines;
830 $this->_start_diff();
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;
838 else{
839 if ($ntrail) {
840 $context = array_slice($edit->orig, 0, $ntrail);
841 $block[] = new _DiffOp_Copy($context);
843 $this->_block($x0, $ntrail + $xi - $x0,
844 $y0, $ntrail + $yi - $y0,
845 $block);
846 $block = false;
849 $context = $edit->orig;
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);
860 $block[] = $edit;
863 if ($edit->orig)
864 $xi += sizeof($edit->orig);
865 if ($edit->final)
866 $yi += sizeof($edit->final);
869 if (is_array($block))
870 $this->_block($x0, $xi - $x0,
871 $y0, $yi - $y0,
872 $block);
874 return $this->_end_diff();
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->final);
884 elseif ($edit->type == 'delete')
885 $this->_deleted($edit->orig);
886 elseif ($edit->type == 'change')
887 $this->_changed($edit->orig, $edit->final);
888 else
889 trigger_error("Unknown edit type", E_USER_ERROR);
891 $this->_end_block();
894 function _start_diff() {
895 ob_start();
898 function _end_diff() {
899 $val = ob_get_contents();
900 ob_end_clean();
901 return $val;
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);
910 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
913 function _start_block($header) {
914 echo $header;
917 function _end_block() {
920 function _lines($lines, $prefix = ' ') {
921 foreach ($lines as $line)
922 echo "$prefix $line\n";
925 function _context($lines) {
926 $this->_lines($lines);
929 function _added($lines) {
930 $this->_lines($lines, ">");
932 function _deleted($lines) {
933 $this->_lines($lines, "<");
936 function _changed($orig, $final) {
937 $this->_deleted($orig);
938 echo "---\n";
939 $this->_added($final);
945 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
949 define('NBSP', "\xA0"); // iso-8859-x non-breaking space.
951 class _HWLDF_WordAccumulator {
952 function _HWLDF_WordAccumulator () {
953 $this->_lines = array();
954 $this->_line = '';
955 $this->_group = '';
956 $this->_tag = '';
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;
966 $this->_group = '';
967 $this->_tag = $new_tag;
970 function _flushLine ($new_tag) {
971 $this->_flushGroup($new_tag);
972 if ($this->_line != '')
973 $this->_lines[] = $this->_line;
974 $this->_line = '';
977 function addWords ($words, $tag = '') {
978 if ($tag != $this->_tag)
979 $this->_flushGroup($tag);
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);
990 assert(!strstr($word, "\n"));
991 $this->_group .= $word;
995 function getLines() {
996 $this->_flushLine('~done');
997 return $this->_lines;
1001 class WordLevelDiff extends MappedDiff
1003 function WordLevelDiff ($orig_lines, $final_lines) {
1004 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1005 list ($final_words, $final_stripped) = $this->_split($final_lines);
1008 $this->MappedDiff($orig_words, $final_words,
1009 $orig_stripped, $final_stripped);
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(''));
1020 return array($m[0], $m[1]);
1023 function orig () {
1024 $orig = new _HWLDF_WordAccumulator;
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');
1032 return $orig->getLines();
1035 function final () {
1036 $final = new _HWLDF_WordAccumulator;
1038 foreach ($this->edits as $edit) {
1039 if ($edit->type == 'copy')
1040 $final->addWords($edit->final);
1041 elseif ($edit->final)
1042 $final->addWords($edit->final, 'mark');
1044 return $final->getLines();
1049 * Wikipedia Table style diff formatter.
1052 class TableDiffFormatter extends DiffFormatter
1054 function TableDiffFormatter() {
1055 $this->leading_context_lines = 2;
1056 $this->trailing_context_lines = 2;
1059 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1060 $l1 = wfMsg( "lineno", $xbeg );
1061 $l2 = wfMsg( "lineno", $ybeg );
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;
1068 function _start_block( $header ) {
1069 global $wgOut;
1070 $wgOut->addHTML( $header );
1073 function _end_block() {
1076 function _lines( $lines, $prefix=' ', $color="white" ) {
1079 function addedLine( $line ) {
1080 return "<td>+</td><td bgcolor='#ccffcc'>" .
1081 "<small>{$line}</small></td>";
1084 function deletedLine( $line ) {
1085 return "<td>-</td><td bgcolor='#ffffaa'>" .
1086 "<small>{$line}</small></td>";
1089 function emptyLine() {
1090 return "<td colspan=2>&nbsp;</td>";
1093 function contextLine( $line ) {
1094 return "<td> </td><td bgcolor='white'><small>{$line}</small></td>";
1097 function _added($lines) {
1098 global $wgOut;
1099 foreach ($lines as $line) {
1100 $wgOut->addHTML( "<tr>" . $this->emptyLine() .
1101 $this->addedLine( $line ) . "</tr>\n" );
1105 function _deleted($lines) {
1106 global $wgOut;
1107 foreach ($lines as $line) {
1108 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1109 $this->emptyLine() . "</tr>\n" );
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" );
1121 function _changed( $orig, $final ) {
1122 global $wgOut;
1123 $diff = new WordLevelDiff( $orig, $final );
1124 $del = $diff->orig();
1125 $add = $diff->final();
1127 while ( $line = array_shift( $del ) ) {
1128 $aline = array_shift( $add );
1129 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1130 $this->addedLine( $aline ) . "</tr>\n" );
1132 $this->_added( $add ); # If any leftovers