template arguments, various improvements to handling of recursive inclusion
[mediawiki.git] / includes / DifferenceEngine.php
blob28e95f11d3de6853779b4c1747148b595bf589a7
1 <?php
2 # See diff.doc
4 class DifferenceEngine {
5 /* private */ var $mOldid, $mNewid;
6 /* private */ var $mOldtitle, $mNewtitle;
7 /* private */ var $mOldtext, $mNewtext;
8 /* private */ var $mOldUser, $mNewUser;
10 function DifferenceEngine( $old, $new )
12 $this->mOldid = $old;
13 $this->mNewid = $new;
16 function showDiffPage()
18 global $wgUser, $wgTitle, $wgOut, $wgLang;
20 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
21 "{$this->mNewid})";
22 $mtext = wfMsg( "missingarticle", $t );
24 $wgOut->setArticleFlag( false );
25 if ( ! $this->loadText() ) {
26 $wgOut->setPagetitle( wfMsg( "errorpagetitle" ) );
27 $wgOut->addHTML( $mtext );
28 return;
30 $wgOut->suppressQuickbar();
31 $wgOut->setSubtitle( wfMsg( "difference" ) );
32 $wgOut->setRobotpolicy( "noindex,follow" );
34 $sk = $wgUser->getSkin();
35 $talk = $wgLang->getNsText( NS_TALK );
36 $contribs = wfMsg( "contribslink" );
38 $oldUserLink = $sk->makeLinkObj( Title::makeTitle( NS_USER, $this->mOldUser ), $this->mOldUser );
39 $newUserLink = $sk->makeLinkObj( Title::makeTitle( NS_USER, $this->mNewUser ), $this->mNewUser );
40 $oldUTLink = $sk->makeLinkObj( Title::makeTitle( NS_USER_TALK, $this->mOldUser ), $talk );
41 $newUTLink = $sk->makeLinkObj( Title::makeTitle( NS_USER_TALK, $this->mNewUser ), $talk );
42 $oldContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, "Contributions" ), $contribs,
43 "target=" . urlencode($this->mOldUser) );
44 $newContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, "Contributions" ), $contribs,
45 "target=" . urlencode($this->mNewUser) );
46 if ( !$this->mNewid && $wgUser->isSysop() ) {
47 $rollback = "&nbsp;&nbsp;&nbsp;<strong>[" . $sk->makeKnownLinkObj( $wgTitle, wfMsg( "rollbacklink" ),
48 "action=rollback&from=" . urlencode($this->mNewUser) ) . "]</strong>";
49 } else {
50 $rollback = "";
53 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink ($oldUTLink | $oldContribs)";
54 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink ($newUTLink | $newContribs) $rollback";
56 DifferenceEngine::showDiff( $this->mOldtext, $this->mNewtext,
57 $oldHeader, $newHeader );
58 $wgOut->addHTML( "<hr /><h2>{$this->mNewtitle}</h2>\n" );
59 $wgOut->addWikiText( $this->mNewtext );
62 function showDiff( $otext, $ntext, $otitle, $ntitle )
64 global $wgOut;
66 $ota = explode( "\n", str_replace( "\r\n", "\n",
67 htmlspecialchars( $otext ) ) );
68 $nta = explode( "\n", str_replace( "\r\n", "\n",
69 htmlspecialchars( $ntext ) ) );
71 $wgOut->addHTML( "<table border='0' width='98%'
72 cellpadding='0' cellspacing='4px' class='special'><tr>
73 <td colspan='2' width='50%' align='center' bgcolor='#cccccc'>
74 {$otitle}</td>
75 <td colspan='2' width='50%' align='center' bgcolor='#cccccc'>
76 {$ntitle}</td>
77 </tr>\n" );
79 $diffs = new Diff( $ota, $nta );
80 $formatter = new TableDiffFormatter();
81 $formatter->format( $diffs );
82 $wgOut->addHTML( "</table>\n" );
85 # Load the text of the articles to compare. If newid is 0, then compare
86 # the old article in oldid to the current article; if oldid is 0, then
87 # compare the current article to the immediately previous one (ignoring
88 # the value of newid).
90 function loadText()
92 global $wgTitle, $wgOut, $wgLang;
93 $fname = "DifferenceEngine::loadText";
95 if ( 0 == $this->mNewid || 0 == $this->mOldid ) {
96 $wgOut->setArticleFlag( true );
97 $this->mNewtitle = wfMsg( "currentrev" );
98 $id = $wgTitle->getArticleID();
100 $sql = "SELECT cur_text, cur_user_text FROM cur WHERE cur_id={$id}";
101 $res = wfQuery( $sql, DB_READ, $fname );
102 if ( 0 == wfNumRows( $res ) ) { return false; }
104 $s = wfFetchObject( $res );
105 $this->mNewtext = $s->cur_text;
106 $this->mNewUser = $s->cur_user_text;
107 } else {
108 $sql = "SELECT old_timestamp,old_text,old_flags,old_user_text FROM old WHERE " .
109 "old_id={$this->mNewid}";
111 $res = wfQuery( $sql, DB_READ, $fname );
112 if ( 0 == wfNumRows( $res ) ) { return false; }
114 $s = wfFetchObject( $res );
115 $this->mNewtext = Article::getRevisionText( $s );
117 $t = $wgLang->timeanddate( $s->old_timestamp, true );
118 $this->mNewtitle = wfMsg( "revisionasof", $t );
119 $this->mNewUser = $s->old_user_text;
121 if ( 0 == $this->mOldid ) {
122 $sql = "SELECT old_timestamp,old_text,old_flags,old_user_text " .
123 "FROM old USE INDEX (name_title_timestamp) WHERE " .
124 "old_namespace=" . $wgTitle->getNamespace() . " AND " .
125 "old_title='" . wfStrencode( $wgTitle->getDBkey() ) .
126 "' ORDER BY inverse_timestamp LIMIT 1";
127 $res = wfQuery( $sql, DB_READ, $fname );
128 } else {
129 $sql = "SELECT old_timestamp,old_text,old_flags,old_user_text FROM old WHERE " .
130 "old_id={$this->mOldid}";
131 $res = wfQuery( $sql, DB_READ, $fname );
133 if ( 0 == wfNumRows( $res ) ) { return false; }
135 $s = wfFetchObject( $res );
136 $this->mOldtext = Article::getRevisionText( $s );
138 $t = $wgLang->timeanddate( $s->old_timestamp, true );
139 $this->mOldtitle = wfMsg( "revisionasof", $t );
140 $this->mOldUser = $s->old_user_text;
142 return true;
146 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
148 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
149 // You may copy this code freely under the conditions of the GPL.
152 define('USE_ASSERTS', function_exists('assert'));
154 class _DiffOp {
155 var $type;
156 var $orig;
157 var $closing;
159 function reverse() {
160 trigger_error("pure virtual", E_USER_ERROR);
163 function norig() {
164 return $this->orig ? sizeof($this->orig) : 0;
167 function nclosing() {
168 return $this->closing ? sizeof($this->closing) : 0;
172 class _DiffOp_Copy extends _DiffOp {
173 var $type = 'copy';
175 function _DiffOp_Copy ($orig, $closing = false) {
176 if (!is_array($closing))
177 $closing = $orig;
178 $this->orig = $orig;
179 $this->closing = $closing;
182 function reverse() {
183 return new _DiffOp_Copy($this->closing, $this->orig);
187 class _DiffOp_Delete extends _DiffOp {
188 var $type = 'delete';
190 function _DiffOp_Delete ($lines) {
191 $this->orig = $lines;
192 $this->closing = false;
195 function reverse() {
196 return new _DiffOp_Add($this->orig);
200 class _DiffOp_Add extends _DiffOp {
201 var $type = 'add';
203 function _DiffOp_Add ($lines) {
204 $this->closing = $lines;
205 $this->orig = false;
208 function reverse() {
209 return new _DiffOp_Delete($this->closing);
213 class _DiffOp_Change extends _DiffOp {
214 var $type = 'change';
216 function _DiffOp_Change ($orig, $closing) {
217 $this->orig = $orig;
218 $this->closing = $closing;
221 function reverse() {
222 return new _DiffOp_Change($this->closing, $this->orig);
228 * Class used internally by Diff to actually compute the diffs.
230 * The algorithm used here is mostly lifted from the perl module
231 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
232 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
234 * More ideas are taken from:
235 * http://www.ics.uci.edu/~eppstein/161/960229.html
237 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
238 * diffutils-2.7, which can be found at:
239 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
241 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
242 * are my own.
244 * @author Geoffrey T. Dairiki
245 * @access private
247 class _DiffEngine
249 function diff ($from_lines, $to_lines) {
250 $n_from = sizeof($from_lines);
251 $n_to = sizeof($to_lines);
253 $this->xchanged = $this->ychanged = array();
254 $this->xv = $this->yv = array();
255 $this->xind = $this->yind = array();
256 unset($this->seq);
257 unset($this->in_seq);
258 unset($this->lcs);
260 // Skip leading common lines.
261 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
262 if ($from_lines[$skip] != $to_lines[$skip])
263 break;
264 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
266 // Skip trailing common lines.
267 $xi = $n_from; $yi = $n_to;
268 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
269 if ($from_lines[$xi] != $to_lines[$yi])
270 break;
271 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
274 // Ignore lines which do not exist in both files.
275 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
276 $xhash[$from_lines[$xi]] = 1;
277 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
278 $line = $to_lines[$yi];
279 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
280 continue;
281 $yhash[$line] = 1;
282 $this->yv[] = $line;
283 $this->yind[] = $yi;
285 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
286 $line = $from_lines[$xi];
287 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
288 continue;
289 $this->xv[] = $line;
290 $this->xind[] = $xi;
293 // Find the LCS.
294 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
296 // Merge edits when possible
297 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
298 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
300 // Compute the edit operations.
301 $edits = array();
302 $xi = $yi = 0;
303 while ($xi < $n_from || $yi < $n_to) {
304 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
305 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
307 // Skip matching "snake".
308 $copy = array();
309 while ( $xi < $n_from && $yi < $n_to
310 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
311 $copy[] = $from_lines[$xi++];
312 ++$yi;
314 if ($copy)
315 $edits[] = new _DiffOp_Copy($copy);
317 // Find deletes & adds.
318 $delete = array();
319 while ($xi < $n_from && $this->xchanged[$xi])
320 $delete[] = $from_lines[$xi++];
322 $add = array();
323 while ($yi < $n_to && $this->ychanged[$yi])
324 $add[] = $to_lines[$yi++];
326 if ($delete && $add)
327 $edits[] = new _DiffOp_Change($delete, $add);
328 elseif ($delete)
329 $edits[] = new _DiffOp_Delete($delete);
330 elseif ($add)
331 $edits[] = new _DiffOp_Add($add);
333 return $edits;
337 /* Divide the Largest Common Subsequence (LCS) of the sequences
338 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
339 * sized segments.
341 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
342 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
343 * sub sequences. The first sub-sequence is contained in [X0, X1),
344 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
345 * that (X0, Y0) == (XOFF, YOFF) and
346 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
348 * This function assumes that the first lines of the specified portions
349 * of the two files do not match, and likewise that the last lines do not
350 * match. The caller must trim matching lines from the beginning and end
351 * of the portions it is going to specify.
353 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
354 $flip = false;
356 if ($xlim - $xoff > $ylim - $yoff) {
357 // Things seems faster (I'm not sure I understand why)
358 // when the shortest sequence in X.
359 $flip = true;
360 list ($xoff, $xlim, $yoff, $ylim)
361 = array( $yoff, $ylim, $xoff, $xlim);
364 if ($flip)
365 for ($i = $ylim - 1; $i >= $yoff; $i--)
366 $ymatches[$this->xv[$i]][] = $i;
367 else
368 for ($i = $ylim - 1; $i >= $yoff; $i--)
369 $ymatches[$this->yv[$i]][] = $i;
371 $this->lcs = 0;
372 $this->seq[0]= $yoff - 1;
373 $this->in_seq = array();
374 $ymids[0] = array();
376 $numer = $xlim - $xoff + $nchunks - 1;
377 $x = $xoff;
378 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
379 if ($chunk > 0)
380 for ($i = 0; $i <= $this->lcs; $i++)
381 $ymids[$i][$chunk-1] = $this->seq[$i];
383 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
384 for ( ; $x < $x1; $x++) {
385 $line = $flip ? $this->yv[$x] : $this->xv[$x];
386 if (empty($ymatches[$line]))
387 continue;
388 $matches = $ymatches[$line];
389 reset($matches);
390 while (list ($junk, $y) = each($matches))
391 if (empty($this->in_seq[$y])) {
392 $k = $this->_lcs_pos($y);
393 USE_ASSERTS && assert($k > 0);
394 $ymids[$k] = $ymids[$k-1];
395 break;
397 while (list ($junk, $y) = each($matches)) {
398 if ($y > $this->seq[$k-1]) {
399 USE_ASSERTS && assert($y < $this->seq[$k]);
400 // Optimization: this is a common case:
401 // next match is just replacing previous match.
402 $this->in_seq[$this->seq[$k]] = false;
403 $this->seq[$k] = $y;
404 $this->in_seq[$y] = 1;
406 else if (empty($this->in_seq[$y])) {
407 $k = $this->_lcs_pos($y);
408 USE_ASSERTS && assert($k > 0);
409 $ymids[$k] = $ymids[$k-1];
415 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
416 $ymid = $ymids[$this->lcs];
417 for ($n = 0; $n < $nchunks - 1; $n++) {
418 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
419 $y1 = $ymid[$n] + 1;
420 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
422 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
424 return array($this->lcs, $seps);
427 function _lcs_pos ($ypos) {
428 $end = $this->lcs;
429 if ($end == 0 || $ypos > $this->seq[$end]) {
430 $this->seq[++$this->lcs] = $ypos;
431 $this->in_seq[$ypos] = 1;
432 return $this->lcs;
435 $beg = 1;
436 while ($beg < $end) {
437 $mid = (int)(($beg + $end) / 2);
438 if ( $ypos > $this->seq[$mid] )
439 $beg = $mid + 1;
440 else
441 $end = $mid;
444 USE_ASSERTS && assert($ypos != $this->seq[$end]);
446 $this->in_seq[$this->seq[$end]] = false;
447 $this->seq[$end] = $ypos;
448 $this->in_seq[$ypos] = 1;
449 return $end;
452 /* Find LCS of two sequences.
454 * The results are recorded in the vectors $this->{x,y}changed[], by
455 * storing a 1 in the element for each line that is an insertion
456 * or deletion (ie. is not in the LCS).
458 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
460 * Note that XLIM, YLIM are exclusive bounds.
461 * All line numbers are origin-0 and discarded lines are not counted.
463 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
464 // Slide down the bottom initial diagonal.
465 while ($xoff < $xlim && $yoff < $ylim
466 && $this->xv[$xoff] == $this->yv[$yoff]) {
467 ++$xoff;
468 ++$yoff;
471 // Slide up the top initial diagonal.
472 while ($xlim > $xoff && $ylim > $yoff
473 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
474 --$xlim;
475 --$ylim;
478 if ($xoff == $xlim || $yoff == $ylim)
479 $lcs = 0;
480 else {
481 // This is ad hoc but seems to work well.
482 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
483 //$nchunks = max(2,min(8,(int)$nchunks));
484 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
485 list ($lcs, $seps)
486 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
489 if ($lcs == 0) {
490 // X and Y sequences have no common subsequence:
491 // mark all changed.
492 while ($yoff < $ylim)
493 $this->ychanged[$this->yind[$yoff++]] = 1;
494 while ($xoff < $xlim)
495 $this->xchanged[$this->xind[$xoff++]] = 1;
497 else {
498 // Use the partitions to split this problem into subproblems.
499 reset($seps);
500 $pt1 = $seps[0];
501 while ($pt2 = next($seps)) {
502 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
503 $pt1 = $pt2;
508 /* Adjust inserts/deletes of identical lines to join changes
509 * as much as possible.
511 * We do something when a run of changed lines include a
512 * line at one end and has an excluded, identical line at the other.
513 * We are free to choose which identical line is included.
514 * `compareseq' usually chooses the one at the beginning,
515 * but usually it is cleaner to consider the following identical line
516 * to be the "change".
518 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
520 function _shift_boundaries ($lines, &$changed, $other_changed) {
521 $i = 0;
522 $j = 0;
524 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
525 $len = sizeof($lines);
526 $other_len = sizeof($other_changed);
528 while (1) {
530 * Scan forwards to find beginning of another run of changes.
531 * Also keep track of the corresponding point in the other file.
533 * Throughout this code, $i and $j are adjusted together so that
534 * the first $i elements of $changed and the first $j elements
535 * of $other_changed both contain the same number of zeros
536 * (unchanged lines).
537 * Furthermore, $j is always kept so that $j == $other_len or
538 * $other_changed[$j] == false.
540 while ($j < $other_len && $other_changed[$j])
541 $j++;
543 while ($i < $len && ! $changed[$i]) {
544 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
545 $i++; $j++;
546 while ($j < $other_len && $other_changed[$j])
547 $j++;
550 if ($i == $len)
551 break;
553 $start = $i;
555 // Find the end of this run of changes.
556 while (++$i < $len && $changed[$i])
557 continue;
559 do {
561 * Record the length of this run of changes, so that
562 * we can later determine whether the run has grown.
564 $runlength = $i - $start;
567 * Move the changed region back, so long as the
568 * previous unchanged line matches the last changed one.
569 * This merges with previous changed regions.
571 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
572 $changed[--$start] = 1;
573 $changed[--$i] = false;
574 while ($start > 0 && $changed[$start - 1])
575 $start--;
576 USE_ASSERTS && assert('$j > 0');
577 while ($other_changed[--$j])
578 continue;
579 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
583 * Set CORRESPONDING to the end of the changed run, at the last
584 * point where it corresponds to a changed run in the other file.
585 * CORRESPONDING == LEN means no such point has been found.
587 $corresponding = $j < $other_len ? $i : $len;
590 * Move the changed region forward, so long as the
591 * first changed line matches the following unchanged one.
592 * This merges with following changed regions.
593 * Do this second, so that if there are no merges,
594 * the changed region is moved forward as far as possible.
596 while ($i < $len && $lines[$start] == $lines[$i]) {
597 $changed[$start++] = false;
598 $changed[$i++] = 1;
599 while ($i < $len && $changed[$i])
600 $i++;
602 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
603 $j++;
604 if ($j < $other_len && $other_changed[$j]) {
605 $corresponding = $i;
606 while ($j < $other_len && $other_changed[$j])
607 $j++;
610 } while ($runlength != $i - $start);
613 * If possible, move the fully-merged run of changes
614 * back to a corresponding run in the other file.
616 while ($corresponding < $i) {
617 $changed[--$start] = 1;
618 $changed[--$i] = 0;
619 USE_ASSERTS && assert('$j > 0');
620 while ($other_changed[--$j])
621 continue;
622 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
629 * Class representing a 'diff' between two sequences of strings.
631 class Diff
633 var $edits;
636 * Constructor.
637 * Computes diff between sequences of strings.
639 * @param $from_lines array An array of strings.
640 * (Typically these are lines from a file.)
641 * @param $to_lines array An array of strings.
643 function Diff($from_lines, $to_lines) {
644 $eng = new _DiffEngine;
645 $this->edits = $eng->diff($from_lines, $to_lines);
646 //$this->_check($from_lines, $to_lines);
650 * Compute reversed Diff.
652 * SYNOPSIS:
654 * $diff = new Diff($lines1, $lines2);
655 * $rev = $diff->reverse();
656 * @return object A Diff object representing the inverse of the
657 * original diff.
659 function reverse () {
660 $rev = $this;
661 $rev->edits = array();
662 foreach ($this->edits as $edit) {
663 $rev->edits[] = $edit->reverse();
665 return $rev;
669 * Check for empty diff.
671 * @return bool True iff two sequences were identical.
673 function isEmpty () {
674 foreach ($this->edits as $edit) {
675 if ($edit->type != 'copy')
676 return false;
678 return true;
682 * Compute the length of the Longest Common Subsequence (LCS).
684 * This is mostly for diagnostic purposed.
686 * @return int The length of the LCS.
688 function lcs () {
689 $lcs = 0;
690 foreach ($this->edits as $edit) {
691 if ($edit->type == 'copy')
692 $lcs += sizeof($edit->orig);
694 return $lcs;
698 * Get the original set of lines.
700 * This reconstructs the $from_lines parameter passed to the
701 * constructor.
703 * @return array The original sequence of strings.
705 function orig() {
706 $lines = array();
708 foreach ($this->edits as $edit) {
709 if ($edit->orig)
710 array_splice($lines, sizeof($lines), 0, $edit->orig);
712 return $lines;
716 * Get the closing set of lines.
718 * This reconstructs the $to_lines parameter passed to the
719 * constructor.
721 * @return array The sequence of strings.
723 function closing() {
724 $lines = array();
726 foreach ($this->edits as $edit) {
727 if ($edit->closing)
728 array_splice($lines, sizeof($lines), 0, $edit->closing);
730 return $lines;
734 * Check a Diff for validity.
736 * This is here only for debugging purposes.
738 function _check ($from_lines, $to_lines) {
739 if (serialize($from_lines) != serialize($this->orig()))
740 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
741 if (serialize($to_lines) != serialize($this->closing()))
742 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
744 $rev = $this->reverse();
745 if (serialize($to_lines) != serialize($rev->orig()))
746 trigger_error("Reversed original doesn't match", E_USER_ERROR);
747 if (serialize($from_lines) != serialize($rev->closing()))
748 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
751 $prevtype = 'none';
752 foreach ($this->edits as $edit) {
753 if ( $prevtype == $edit->type )
754 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
755 $prevtype = $edit->type;
758 $lcs = $this->lcs();
759 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
764 * FIXME: bad name.
766 class MappedDiff
767 extends Diff
770 * Constructor.
772 * Computes diff between sequences of strings.
774 * This can be used to compute things like
775 * case-insensitve diffs, or diffs which ignore
776 * changes in white-space.
778 * @param $from_lines array An array of strings.
779 * (Typically these are lines from a file.)
781 * @param $to_lines array An array of strings.
783 * @param $mapped_from_lines array This array should
784 * have the same size number of elements as $from_lines.
785 * The elements in $mapped_from_lines and
786 * $mapped_to_lines are what is actually compared
787 * when computing the diff.
789 * @param $mapped_to_lines array This array should
790 * have the same number of elements as $to_lines.
792 function MappedDiff($from_lines, $to_lines,
793 $mapped_from_lines, $mapped_to_lines) {
795 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
796 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
798 $this->Diff($mapped_from_lines, $mapped_to_lines);
800 $xi = $yi = 0;
801 for ($i = 0; $i < sizeof($this->edits); $i++) {
802 $orig = &$this->edits[$i]->orig;
803 if (is_array($orig)) {
804 $orig = array_slice($from_lines, $xi, sizeof($orig));
805 $xi += sizeof($orig);
808 $closing = &$this->edits[$i]->closing;
809 if (is_array($closing)) {
810 $closing = array_slice($to_lines, $yi, sizeof($closing));
811 $yi += sizeof($closing);
818 * A class to format Diffs
820 * This class formats the diff in classic diff format.
821 * It is intended that this class be customized via inheritance,
822 * to obtain fancier outputs.
824 class DiffFormatter
827 * Number of leading context "lines" to preserve.
829 * This should be left at zero for this class, but subclasses
830 * may want to set this to other values.
832 var $leading_context_lines = 0;
835 * Number of trailing context "lines" to preserve.
837 * This should be left at zero for this class, but subclasses
838 * may want to set this to other values.
840 var $trailing_context_lines = 0;
843 * Format a diff.
845 * @param $diff object A Diff object.
846 * @return string The formatted output.
848 function format($diff) {
850 $xi = $yi = 1;
851 $block = false;
852 $context = array();
854 $nlead = $this->leading_context_lines;
855 $ntrail = $this->trailing_context_lines;
857 $this->_start_diff();
859 foreach ($diff->edits as $edit) {
860 if ($edit->type == 'copy') {
861 if (is_array($block)) {
862 if (sizeof($edit->orig) <= $nlead + $ntrail) {
863 $block[] = $edit;
865 else{
866 if ($ntrail) {
867 $context = array_slice($edit->orig, 0, $ntrail);
868 $block[] = new _DiffOp_Copy($context);
870 $this->_block($x0, $ntrail + $xi - $x0,
871 $y0, $ntrail + $yi - $y0,
872 $block);
873 $block = false;
876 $context = $edit->orig;
878 else {
879 if (! is_array($block)) {
880 $context = array_slice($context, sizeof($context) - $nlead);
881 $x0 = $xi - sizeof($context);
882 $y0 = $yi - sizeof($context);
883 $block = array();
884 if ($context)
885 $block[] = new _DiffOp_Copy($context);
887 $block[] = $edit;
890 if ($edit->orig)
891 $xi += sizeof($edit->orig);
892 if ($edit->closing)
893 $yi += sizeof($edit->closing);
896 if (is_array($block))
897 $this->_block($x0, $xi - $x0,
898 $y0, $yi - $y0,
899 $block);
901 return $this->_end_diff();
904 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
905 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
906 foreach ($edits as $edit) {
907 if ($edit->type == 'copy')
908 $this->_context($edit->orig);
909 elseif ($edit->type == 'add')
910 $this->_added($edit->closing);
911 elseif ($edit->type == 'delete')
912 $this->_deleted($edit->orig);
913 elseif ($edit->type == 'change')
914 $this->_changed($edit->orig, $edit->closing);
915 else
916 trigger_error("Unknown edit type", E_USER_ERROR);
918 $this->_end_block();
921 function _start_diff() {
922 ob_start();
925 function _end_diff() {
926 $val = ob_get_contents();
927 ob_end_clean();
928 return $val;
931 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
932 if ($xlen > 1)
933 $xbeg .= "," . ($xbeg + $xlen - 1);
934 if ($ylen > 1)
935 $ybeg .= "," . ($ybeg + $ylen - 1);
937 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
940 function _start_block($header) {
941 echo $header;
944 function _end_block() {
947 function _lines($lines, $prefix = ' ') {
948 foreach ($lines as $line)
949 echo "$prefix $line\n";
952 function _context($lines) {
953 $this->_lines($lines);
956 function _added($lines) {
957 $this->_lines($lines, ">");
959 function _deleted($lines) {
960 $this->_lines($lines, "<");
963 function _changed($orig, $closing) {
964 $this->_deleted($orig);
965 echo "---\n";
966 $this->_added($closing);
972 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
976 define('NBSP', "\xA0"); // iso-8859-x non-breaking space.
978 class _HWLDF_WordAccumulator {
979 function _HWLDF_WordAccumulator () {
980 $this->_lines = array();
981 $this->_line = '';
982 $this->_group = '';
983 $this->_tag = '';
986 function _flushGroup ($new_tag) {
987 if ($this->_group !== '') {
988 if ($this->_tag == 'mark')
989 $this->_line .= "<font color=\"red\">$this->_group</font>";
990 else
991 $this->_line .= $this->_group;
993 $this->_group = '';
994 $this->_tag = $new_tag;
997 function _flushLine ($new_tag) {
998 $this->_flushGroup($new_tag);
999 if ($this->_line != '')
1000 $this->_lines[] = $this->_line;
1001 $this->_line = '';
1004 function addWords ($words, $tag = '') {
1005 if ($tag != $this->_tag)
1006 $this->_flushGroup($tag);
1008 foreach ($words as $word) {
1009 // new-line should only come as first char of word.
1010 if ($word == '')
1011 continue;
1012 if ($word[0] == "\n") {
1013 $this->_group .= NBSP;
1014 $this->_flushLine($tag);
1015 $word = substr($word, 1);
1017 assert(!strstr($word, "\n"));
1018 $this->_group .= $word;
1022 function getLines() {
1023 $this->_flushLine('~done');
1024 return $this->_lines;
1028 class WordLevelDiff extends MappedDiff
1030 function WordLevelDiff ($orig_lines, $closing_lines) {
1031 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1032 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1035 $this->MappedDiff($orig_words, $closing_words,
1036 $orig_stripped, $closing_stripped);
1039 function _split($lines) {
1040 // FIXME: fix POSIX char class.
1041 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1042 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1043 implode("\n", $lines),
1044 $m)) {
1045 return array(array(''), array(''));
1047 return array($m[0], $m[1]);
1050 function orig () {
1051 $orig = new _HWLDF_WordAccumulator;
1053 foreach ($this->edits as $edit) {
1054 if ($edit->type == 'copy')
1055 $orig->addWords($edit->orig);
1056 elseif ($edit->orig)
1057 $orig->addWords($edit->orig, 'mark');
1059 return $orig->getLines();
1062 function closing () {
1063 $closing = new _HWLDF_WordAccumulator;
1065 foreach ($this->edits as $edit) {
1066 if ($edit->type == 'copy')
1067 $closing->addWords($edit->closing);
1068 elseif ($edit->closing)
1069 $closing->addWords($edit->closing, 'mark');
1071 return $closing->getLines();
1076 * Wikipedia Table style diff formatter.
1079 class TableDiffFormatter extends DiffFormatter
1081 function TableDiffFormatter() {
1082 $this->leading_context_lines = 2;
1083 $this->trailing_context_lines = 2;
1086 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1087 $l1 = wfMsg( "lineno", $xbeg );
1088 $l2 = wfMsg( "lineno", $ybeg );
1090 $r = "<tr><td colspan='2' align='left'><strong>{$l1}</strong></td>\n" .
1091 "<td colspan='2' align='left'><strong>{$l2}</strong></td></tr>\n";
1092 return $r;
1095 function _start_block( $header ) {
1096 global $wgOut;
1097 $wgOut->addHTML( $header );
1100 function _end_block() {
1103 function _lines( $lines, $prefix=' ', $color="white" ) {
1106 function addedLine( $line ) {
1107 return "<td>+</td><td bgcolor='#ccffcc'>" .
1108 "<small>{$line}</small></td>";
1111 function deletedLine( $line ) {
1112 return "<td>-</td><td bgcolor='#ffffaa'>" .
1113 "<small>{$line}</small></td>";
1116 function emptyLine() {
1117 return "<td colspan='2'>&nbsp;</td>";
1120 function contextLine( $line ) {
1121 return "<td> </td><td bgcolor='white'><small>{$line}</small></td>";
1124 function _added($lines) {
1125 global $wgOut;
1126 foreach ($lines as $line) {
1127 $wgOut->addHTML( "<tr>" . $this->emptyLine() .
1128 $this->addedLine( $line ) . "</tr>\n" );
1132 function _deleted($lines) {
1133 global $wgOut;
1134 foreach ($lines as $line) {
1135 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1136 $this->emptyLine() . "</tr>\n" );
1140 function _context( $lines ) {
1141 global $wgOut;
1142 foreach ($lines as $line) {
1143 $wgOut->addHTML( "<tr>" . $this->contextLine( $line ) .
1144 $this->contextLine( $line ) . "</tr>\n" );
1148 function _changed( $orig, $closing ) {
1149 global $wgOut;
1150 $diff = new WordLevelDiff( $orig, $closing );
1151 $del = $diff->orig();
1152 $add = $diff->closing();
1154 while ( $line = array_shift( $del ) ) {
1155 $aline = array_shift( $add );
1156 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1157 $this->addedLine( $aline ) . "</tr>\n" );
1159 $this->_added( $add ); # If any leftovers