Database::setIgnoreErrors() doesn't seem to exist anymore. Switched to
[mediawiki.git] / includes / DifferenceEngine.php
blob61aec228daa5ce98e7f3b4cb71401c2db1951b6e
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;
9 /* private */ var $mOldComment, $mNewComment;
10 /* private */ var $mOldPage, $mNewPage;
12 function DifferenceEngine( $old, $new )
14 $this->mOldid = $old;
15 $this->mNewid = $new;
18 function showDiffPage()
20 global $wgUser, $wgTitle, $wgOut, $wgLang;
21 $fname = "DifferenceEngine::showDiffPage";
22 wfProfileIn( $fname );
24 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
25 "{$this->mNewid})";
26 $mtext = wfMsg( "missingarticle", $t );
28 $wgOut->setArticleFlag( false );
29 if ( ! $this->loadText() ) {
30 $wgOut->setPagetitle( wfMsg( "errorpagetitle" ) );
31 $wgOut->addHTML( $mtext );
32 wfProfileOut( $fname );
33 return;
35 $wgOut->suppressQuickbar();
37 $oldTitle = $this->mOldPage->getPrefixedText();
38 $newTitle = $this->mNewPage->getPrefixedText();
39 if( $oldTitle == $newTitle ) {
40 $wgOut->setPageTitle( $newTitle );
41 } else {
42 $wgOut->setPageTitle( $oldTitle . ", " . $newTitle );
44 $wgOut->setSubtitle( wfMsg( "difference" ) );
45 $wgOut->setRobotpolicy( "noindex,follow" );
47 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
48 $wgOut->loginToUse();
49 $wgOut->output();
50 wfProfileOut( $fname );
51 exit;
54 $sk = $wgUser->getSkin();
55 $talk = $wgLang->getNsText( NS_TALK );
56 $contribs = wfMsg( "contribslink" );
59 $this->mOldComment = $sk->formatComment($this->mOldComment);
60 $this->mNewComment = $sk->formatComment($this->mNewComment);
63 $oldUserLink = $sk->makeLinkObj( Title::makeTitle( NS_USER, $this->mOldUser ), $this->mOldUser );
64 $newUserLink = $sk->makeLinkObj( Title::makeTitle( NS_USER, $this->mNewUser ), $this->mNewUser );
65 $oldUTLink = $sk->makeLinkObj( Title::makeTitle( NS_USER_TALK, $this->mOldUser ), $talk );
66 $newUTLink = $sk->makeLinkObj( Title::makeTitle( NS_USER_TALK, $this->mNewUser ), $talk );
67 $oldContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, "Contributions" ), $contribs,
68 "target=" . urlencode($this->mOldUser) );
69 $newContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, "Contributions" ), $contribs,
70 "target=" . urlencode($this->mNewUser) );
71 if ( !$this->mNewid && $wgUser->isSysop() ) {
72 $rollback = "&nbsp;&nbsp;&nbsp;<strong>[" . $sk->makeKnownLinkObj( $wgTitle, wfMsg( "rollbacklink" ),
73 "action=rollback&from=" . urlencode($this->mNewUser) ) . "]</strong>";
74 } else {
75 $rollback = "";
78 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink ($oldUTLink | $oldContribs)<br />".
79 $this->mOldComment;
80 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink ($newUTLink | $newContribs) $rollback<br />".
81 $this->mNewComment;
83 DifferenceEngine::showDiff( $this->mOldtext, $this->mNewtext,
84 $oldHeader, $newHeader );
85 $wgOut->addHTML( "<hr /><h2>{$this->mNewtitle}</h2>\n" );
86 $wgOut->addWikiText( $this->mNewtext );
88 wfProfileOut( $fname );
91 function showDiff( $otext, $ntext, $otitle, $ntitle )
93 global $wgOut;
95 $ota = explode( "\n", str_replace( "\r\n", "\n",
96 htmlspecialchars( $otext ) ) );
97 $nta = explode( "\n", str_replace( "\r\n", "\n",
98 htmlspecialchars( $ntext ) ) );
100 $wgOut->addHTML( "<table border='0' width='98%'
101 cellpadding='0' cellspacing='4px' class='diff'><tr>
102 <td colspan='2' width='50%' align='center' class='diff-otitle'>
103 {$otitle}</td>
104 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
105 {$ntitle}</td>
106 </tr>\n" );
108 $diffs = new Diff( $ota, $nta );
109 $formatter = new TableDiffFormatter();
110 $formatter->format( $diffs );
111 $wgOut->addHTML( "</table>\n" );
114 # Load the text of the articles to compare. If newid is 0, then compare
115 # the old article in oldid to the current article; if oldid is 0, then
116 # compare the current article to the immediately previous one (ignoring
117 # the value of newid).
119 function loadText()
121 global $wgTitle, $wgOut, $wgLang;
122 $fname = "DifferenceEngine::loadText";
124 $dbr =& wfGetDB( DB_SLAVE );
125 if ( 0 == $this->mNewid || 0 == $this->mOldid ) {
126 $wgOut->setArticleFlag( true );
127 $this->mNewtitle = wfMsg( "currentrev" );
128 $id = $wgTitle->getArticleID();
130 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
131 array( 'cur_id' => $id ), $fname );
132 if ( $s === false ) {
133 return false;
136 $this->mNewPage = &$wgTitle;
137 $this->mNewtext = $s->cur_text;
138 $this->mNewUser = $s->cur_user_text;
139 $this->mNewComment = $s->cur_comment;
140 } else {
141 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
142 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid ), $fname );
144 if ( $s === false ) {
145 return false;
148 $this->mNewtext = Article::getRevisionText( $s );
150 $t = $wgLang->timeanddate( $s->old_timestamp, true );
151 $this->mNewPage = Title::MakeTitle( $s->old_namespace, $s->old_title );
152 $this->mNewtitle = wfMsg( "revisionasof", $t );
153 $this->mNewUser = $s->old_user_text;
154 $this->mNewComment = $s->old_comment;
156 if ( 0 == $this->mOldid ) {
157 $s = $dbr->getArray( 'old',
158 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
159 array( /* WHERE */
160 'old_namespace' => $this->mNewPage->getNamespace(),
161 'old_title' => $this->mNewPage->getDBkey()
162 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
164 } else {
165 $s = $dbr->getArray( 'old',
166 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
167 array( 'old_id' => $this->mOldid ),
168 $fname
171 if ( $s === false ) {
172 return false;
174 $this->mOldPage = Title::MakeTitle( $s->old_namespace, $s->old_title );
175 $this->mOldtext = Article::getRevisionText( $s );
177 $t = $wgLang->timeanddate( $s->old_timestamp, true );
178 $this->mOldtitle = wfMsg( "revisionasof", $t );
179 $this->mOldUser = $s->old_user_text;
180 $this->mOldComment = $s->old_comment;
182 return true;
186 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
188 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
189 // You may copy this code freely under the conditions of the GPL.
192 define('USE_ASSERTS', function_exists('assert'));
194 class _DiffOp {
195 var $type;
196 var $orig;
197 var $closing;
199 function reverse() {
200 trigger_error("pure virtual", E_USER_ERROR);
203 function norig() {
204 return $this->orig ? sizeof($this->orig) : 0;
207 function nclosing() {
208 return $this->closing ? sizeof($this->closing) : 0;
212 class _DiffOp_Copy extends _DiffOp {
213 var $type = 'copy';
215 function _DiffOp_Copy ($orig, $closing = false) {
216 if (!is_array($closing))
217 $closing = $orig;
218 $this->orig = $orig;
219 $this->closing = $closing;
222 function reverse() {
223 return new _DiffOp_Copy($this->closing, $this->orig);
227 class _DiffOp_Delete extends _DiffOp {
228 var $type = 'delete';
230 function _DiffOp_Delete ($lines) {
231 $this->orig = $lines;
232 $this->closing = false;
235 function reverse() {
236 return new _DiffOp_Add($this->orig);
240 class _DiffOp_Add extends _DiffOp {
241 var $type = 'add';
243 function _DiffOp_Add ($lines) {
244 $this->closing = $lines;
245 $this->orig = false;
248 function reverse() {
249 return new _DiffOp_Delete($this->closing);
253 class _DiffOp_Change extends _DiffOp {
254 var $type = 'change';
256 function _DiffOp_Change ($orig, $closing) {
257 $this->orig = $orig;
258 $this->closing = $closing;
261 function reverse() {
262 return new _DiffOp_Change($this->closing, $this->orig);
268 * Class used internally by Diff to actually compute the diffs.
270 * The algorithm used here is mostly lifted from the perl module
271 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
272 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
274 * More ideas are taken from:
275 * http://www.ics.uci.edu/~eppstein/161/960229.html
277 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
278 * diffutils-2.7, which can be found at:
279 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
281 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
282 * are my own.
284 * @author Geoffrey T. Dairiki
285 * @access private
287 class _DiffEngine
289 function diff ($from_lines, $to_lines) {
290 $n_from = sizeof($from_lines);
291 $n_to = sizeof($to_lines);
293 $this->xchanged = $this->ychanged = array();
294 $this->xv = $this->yv = array();
295 $this->xind = $this->yind = array();
296 unset($this->seq);
297 unset($this->in_seq);
298 unset($this->lcs);
300 // Skip leading common lines.
301 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
302 if ($from_lines[$skip] != $to_lines[$skip])
303 break;
304 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
306 // Skip trailing common lines.
307 $xi = $n_from; $yi = $n_to;
308 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
309 if ($from_lines[$xi] != $to_lines[$yi])
310 break;
311 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
314 // Ignore lines which do not exist in both files.
315 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
316 $xhash[$from_lines[$xi]] = 1;
317 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
318 $line = $to_lines[$yi];
319 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
320 continue;
321 $yhash[$line] = 1;
322 $this->yv[] = $line;
323 $this->yind[] = $yi;
325 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
326 $line = $from_lines[$xi];
327 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
328 continue;
329 $this->xv[] = $line;
330 $this->xind[] = $xi;
333 // Find the LCS.
334 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
336 // Merge edits when possible
337 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
338 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
340 // Compute the edit operations.
341 $edits = array();
342 $xi = $yi = 0;
343 while ($xi < $n_from || $yi < $n_to) {
344 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
345 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
347 // Skip matching "snake".
348 $copy = array();
349 while ( $xi < $n_from && $yi < $n_to
350 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
351 $copy[] = $from_lines[$xi++];
352 ++$yi;
354 if ($copy)
355 $edits[] = new _DiffOp_Copy($copy);
357 // Find deletes & adds.
358 $delete = array();
359 while ($xi < $n_from && $this->xchanged[$xi])
360 $delete[] = $from_lines[$xi++];
362 $add = array();
363 while ($yi < $n_to && $this->ychanged[$yi])
364 $add[] = $to_lines[$yi++];
366 if ($delete && $add)
367 $edits[] = new _DiffOp_Change($delete, $add);
368 elseif ($delete)
369 $edits[] = new _DiffOp_Delete($delete);
370 elseif ($add)
371 $edits[] = new _DiffOp_Add($add);
373 return $edits;
377 /* Divide the Largest Common Subsequence (LCS) of the sequences
378 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
379 * sized segments.
381 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
382 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
383 * sub sequences. The first sub-sequence is contained in [X0, X1),
384 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
385 * that (X0, Y0) == (XOFF, YOFF) and
386 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
388 * This function assumes that the first lines of the specified portions
389 * of the two files do not match, and likewise that the last lines do not
390 * match. The caller must trim matching lines from the beginning and end
391 * of the portions it is going to specify.
393 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
394 $flip = false;
396 if ($xlim - $xoff > $ylim - $yoff) {
397 // Things seems faster (I'm not sure I understand why)
398 // when the shortest sequence in X.
399 $flip = true;
400 list ($xoff, $xlim, $yoff, $ylim)
401 = array( $yoff, $ylim, $xoff, $xlim);
404 if ($flip)
405 for ($i = $ylim - 1; $i >= $yoff; $i--)
406 $ymatches[$this->xv[$i]][] = $i;
407 else
408 for ($i = $ylim - 1; $i >= $yoff; $i--)
409 $ymatches[$this->yv[$i]][] = $i;
411 $this->lcs = 0;
412 $this->seq[0]= $yoff - 1;
413 $this->in_seq = array();
414 $ymids[0] = array();
416 $numer = $xlim - $xoff + $nchunks - 1;
417 $x = $xoff;
418 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
419 if ($chunk > 0)
420 for ($i = 0; $i <= $this->lcs; $i++)
421 $ymids[$i][$chunk-1] = $this->seq[$i];
423 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
424 for ( ; $x < $x1; $x++) {
425 $line = $flip ? $this->yv[$x] : $this->xv[$x];
426 if (empty($ymatches[$line]))
427 continue;
428 $matches = $ymatches[$line];
429 reset($matches);
430 while (list ($junk, $y) = each($matches))
431 if (empty($this->in_seq[$y])) {
432 $k = $this->_lcs_pos($y);
433 USE_ASSERTS && assert($k > 0);
434 $ymids[$k] = $ymids[$k-1];
435 break;
437 while (list ($junk, $y) = each($matches)) {
438 if ($y > $this->seq[$k-1]) {
439 USE_ASSERTS && assert($y < $this->seq[$k]);
440 // Optimization: this is a common case:
441 // next match is just replacing previous match.
442 $this->in_seq[$this->seq[$k]] = false;
443 $this->seq[$k] = $y;
444 $this->in_seq[$y] = 1;
446 else if (empty($this->in_seq[$y])) {
447 $k = $this->_lcs_pos($y);
448 USE_ASSERTS && assert($k > 0);
449 $ymids[$k] = $ymids[$k-1];
455 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
456 $ymid = $ymids[$this->lcs];
457 for ($n = 0; $n < $nchunks - 1; $n++) {
458 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
459 $y1 = $ymid[$n] + 1;
460 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
462 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
464 return array($this->lcs, $seps);
467 function _lcs_pos ($ypos) {
468 $end = $this->lcs;
469 if ($end == 0 || $ypos > $this->seq[$end]) {
470 $this->seq[++$this->lcs] = $ypos;
471 $this->in_seq[$ypos] = 1;
472 return $this->lcs;
475 $beg = 1;
476 while ($beg < $end) {
477 $mid = (int)(($beg + $end) / 2);
478 if ( $ypos > $this->seq[$mid] )
479 $beg = $mid + 1;
480 else
481 $end = $mid;
484 USE_ASSERTS && assert($ypos != $this->seq[$end]);
486 $this->in_seq[$this->seq[$end]] = false;
487 $this->seq[$end] = $ypos;
488 $this->in_seq[$ypos] = 1;
489 return $end;
492 /* Find LCS of two sequences.
494 * The results are recorded in the vectors $this->{x,y}changed[], by
495 * storing a 1 in the element for each line that is an insertion
496 * or deletion (ie. is not in the LCS).
498 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
500 * Note that XLIM, YLIM are exclusive bounds.
501 * All line numbers are origin-0 and discarded lines are not counted.
503 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
504 // Slide down the bottom initial diagonal.
505 while ($xoff < $xlim && $yoff < $ylim
506 && $this->xv[$xoff] == $this->yv[$yoff]) {
507 ++$xoff;
508 ++$yoff;
511 // Slide up the top initial diagonal.
512 while ($xlim > $xoff && $ylim > $yoff
513 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
514 --$xlim;
515 --$ylim;
518 if ($xoff == $xlim || $yoff == $ylim)
519 $lcs = 0;
520 else {
521 // This is ad hoc but seems to work well.
522 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
523 //$nchunks = max(2,min(8,(int)$nchunks));
524 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
525 list ($lcs, $seps)
526 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
529 if ($lcs == 0) {
530 // X and Y sequences have no common subsequence:
531 // mark all changed.
532 while ($yoff < $ylim)
533 $this->ychanged[$this->yind[$yoff++]] = 1;
534 while ($xoff < $xlim)
535 $this->xchanged[$this->xind[$xoff++]] = 1;
537 else {
538 // Use the partitions to split this problem into subproblems.
539 reset($seps);
540 $pt1 = $seps[0];
541 while ($pt2 = next($seps)) {
542 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
543 $pt1 = $pt2;
548 /* Adjust inserts/deletes of identical lines to join changes
549 * as much as possible.
551 * We do something when a run of changed lines include a
552 * line at one end and has an excluded, identical line at the other.
553 * We are free to choose which identical line is included.
554 * `compareseq' usually chooses the one at the beginning,
555 * but usually it is cleaner to consider the following identical line
556 * to be the "change".
558 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
560 function _shift_boundaries ($lines, &$changed, $other_changed) {
561 $i = 0;
562 $j = 0;
564 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
565 $len = sizeof($lines);
566 $other_len = sizeof($other_changed);
568 while (1) {
570 * Scan forwards to find beginning of another run of changes.
571 * Also keep track of the corresponding point in the other file.
573 * Throughout this code, $i and $j are adjusted together so that
574 * the first $i elements of $changed and the first $j elements
575 * of $other_changed both contain the same number of zeros
576 * (unchanged lines).
577 * Furthermore, $j is always kept so that $j == $other_len or
578 * $other_changed[$j] == false.
580 while ($j < $other_len && $other_changed[$j])
581 $j++;
583 while ($i < $len && ! $changed[$i]) {
584 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
585 $i++; $j++;
586 while ($j < $other_len && $other_changed[$j])
587 $j++;
590 if ($i == $len)
591 break;
593 $start = $i;
595 // Find the end of this run of changes.
596 while (++$i < $len && $changed[$i])
597 continue;
599 do {
601 * Record the length of this run of changes, so that
602 * we can later determine whether the run has grown.
604 $runlength = $i - $start;
607 * Move the changed region back, so long as the
608 * previous unchanged line matches the last changed one.
609 * This merges with previous changed regions.
611 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
612 $changed[--$start] = 1;
613 $changed[--$i] = false;
614 while ($start > 0 && $changed[$start - 1])
615 $start--;
616 USE_ASSERTS && assert('$j > 0');
617 while ($other_changed[--$j])
618 continue;
619 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
623 * Set CORRESPONDING to the end of the changed run, at the last
624 * point where it corresponds to a changed run in the other file.
625 * CORRESPONDING == LEN means no such point has been found.
627 $corresponding = $j < $other_len ? $i : $len;
630 * Move the changed region forward, so long as the
631 * first changed line matches the following unchanged one.
632 * This merges with following changed regions.
633 * Do this second, so that if there are no merges,
634 * the changed region is moved forward as far as possible.
636 while ($i < $len && $lines[$start] == $lines[$i]) {
637 $changed[$start++] = false;
638 $changed[$i++] = 1;
639 while ($i < $len && $changed[$i])
640 $i++;
642 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
643 $j++;
644 if ($j < $other_len && $other_changed[$j]) {
645 $corresponding = $i;
646 while ($j < $other_len && $other_changed[$j])
647 $j++;
650 } while ($runlength != $i - $start);
653 * If possible, move the fully-merged run of changes
654 * back to a corresponding run in the other file.
656 while ($corresponding < $i) {
657 $changed[--$start] = 1;
658 $changed[--$i] = 0;
659 USE_ASSERTS && assert('$j > 0');
660 while ($other_changed[--$j])
661 continue;
662 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
669 * Class representing a 'diff' between two sequences of strings.
671 class Diff
673 var $edits;
676 * Constructor.
677 * Computes diff between sequences of strings.
679 * @param $from_lines array An array of strings.
680 * (Typically these are lines from a file.)
681 * @param $to_lines array An array of strings.
683 function Diff($from_lines, $to_lines) {
684 $eng = new _DiffEngine;
685 $this->edits = $eng->diff($from_lines, $to_lines);
686 //$this->_check($from_lines, $to_lines);
690 * Compute reversed Diff.
692 * SYNOPSIS:
694 * $diff = new Diff($lines1, $lines2);
695 * $rev = $diff->reverse();
696 * @return object A Diff object representing the inverse of the
697 * original diff.
699 function reverse () {
700 $rev = $this;
701 $rev->edits = array();
702 foreach ($this->edits as $edit) {
703 $rev->edits[] = $edit->reverse();
705 return $rev;
709 * Check for empty diff.
711 * @return bool True iff two sequences were identical.
713 function isEmpty () {
714 foreach ($this->edits as $edit) {
715 if ($edit->type != 'copy')
716 return false;
718 return true;
722 * Compute the length of the Longest Common Subsequence (LCS).
724 * This is mostly for diagnostic purposed.
726 * @return int The length of the LCS.
728 function lcs () {
729 $lcs = 0;
730 foreach ($this->edits as $edit) {
731 if ($edit->type == 'copy')
732 $lcs += sizeof($edit->orig);
734 return $lcs;
738 * Get the original set of lines.
740 * This reconstructs the $from_lines parameter passed to the
741 * constructor.
743 * @return array The original sequence of strings.
745 function orig() {
746 $lines = array();
748 foreach ($this->edits as $edit) {
749 if ($edit->orig)
750 array_splice($lines, sizeof($lines), 0, $edit->orig);
752 return $lines;
756 * Get the closing set of lines.
758 * This reconstructs the $to_lines parameter passed to the
759 * constructor.
761 * @return array The sequence of strings.
763 function closing() {
764 $lines = array();
766 foreach ($this->edits as $edit) {
767 if ($edit->closing)
768 array_splice($lines, sizeof($lines), 0, $edit->closing);
770 return $lines;
774 * Check a Diff for validity.
776 * This is here only for debugging purposes.
778 function _check ($from_lines, $to_lines) {
779 if (serialize($from_lines) != serialize($this->orig()))
780 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
781 if (serialize($to_lines) != serialize($this->closing()))
782 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
784 $rev = $this->reverse();
785 if (serialize($to_lines) != serialize($rev->orig()))
786 trigger_error("Reversed original doesn't match", E_USER_ERROR);
787 if (serialize($from_lines) != serialize($rev->closing()))
788 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
791 $prevtype = 'none';
792 foreach ($this->edits as $edit) {
793 if ( $prevtype == $edit->type )
794 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
795 $prevtype = $edit->type;
798 $lcs = $this->lcs();
799 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
804 * FIXME: bad name.
806 class MappedDiff
807 extends Diff
810 * Constructor.
812 * Computes diff between sequences of strings.
814 * This can be used to compute things like
815 * case-insensitve diffs, or diffs which ignore
816 * changes in white-space.
818 * @param $from_lines array An array of strings.
819 * (Typically these are lines from a file.)
821 * @param $to_lines array An array of strings.
823 * @param $mapped_from_lines array This array should
824 * have the same size number of elements as $from_lines.
825 * The elements in $mapped_from_lines and
826 * $mapped_to_lines are what is actually compared
827 * when computing the diff.
829 * @param $mapped_to_lines array This array should
830 * have the same number of elements as $to_lines.
832 function MappedDiff($from_lines, $to_lines,
833 $mapped_from_lines, $mapped_to_lines) {
835 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
836 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
838 $this->Diff($mapped_from_lines, $mapped_to_lines);
840 $xi = $yi = 0;
841 for ($i = 0; $i < sizeof($this->edits); $i++) {
842 $orig = &$this->edits[$i]->orig;
843 if (is_array($orig)) {
844 $orig = array_slice($from_lines, $xi, sizeof($orig));
845 $xi += sizeof($orig);
848 $closing = &$this->edits[$i]->closing;
849 if (is_array($closing)) {
850 $closing = array_slice($to_lines, $yi, sizeof($closing));
851 $yi += sizeof($closing);
858 * A class to format Diffs
860 * This class formats the diff in classic diff format.
861 * It is intended that this class be customized via inheritance,
862 * to obtain fancier outputs.
864 class DiffFormatter
867 * Number of leading context "lines" to preserve.
869 * This should be left at zero for this class, but subclasses
870 * may want to set this to other values.
872 var $leading_context_lines = 0;
875 * Number of trailing context "lines" to preserve.
877 * This should be left at zero for this class, but subclasses
878 * may want to set this to other values.
880 var $trailing_context_lines = 0;
883 * Format a diff.
885 * @param $diff object A Diff object.
886 * @return string The formatted output.
888 function format($diff) {
890 $xi = $yi = 1;
891 $block = false;
892 $context = array();
894 $nlead = $this->leading_context_lines;
895 $ntrail = $this->trailing_context_lines;
897 $this->_start_diff();
899 foreach ($diff->edits as $edit) {
900 if ($edit->type == 'copy') {
901 if (is_array($block)) {
902 if (sizeof($edit->orig) <= $nlead + $ntrail) {
903 $block[] = $edit;
905 else{
906 if ($ntrail) {
907 $context = array_slice($edit->orig, 0, $ntrail);
908 $block[] = new _DiffOp_Copy($context);
910 $this->_block($x0, $ntrail + $xi - $x0,
911 $y0, $ntrail + $yi - $y0,
912 $block);
913 $block = false;
916 $context = $edit->orig;
918 else {
919 if (! is_array($block)) {
920 $context = array_slice($context, sizeof($context) - $nlead);
921 $x0 = $xi - sizeof($context);
922 $y0 = $yi - sizeof($context);
923 $block = array();
924 if ($context)
925 $block[] = new _DiffOp_Copy($context);
927 $block[] = $edit;
930 if ($edit->orig)
931 $xi += sizeof($edit->orig);
932 if ($edit->closing)
933 $yi += sizeof($edit->closing);
936 if (is_array($block))
937 $this->_block($x0, $xi - $x0,
938 $y0, $yi - $y0,
939 $block);
941 return $this->_end_diff();
944 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
945 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
946 foreach ($edits as $edit) {
947 if ($edit->type == 'copy')
948 $this->_context($edit->orig);
949 elseif ($edit->type == 'add')
950 $this->_added($edit->closing);
951 elseif ($edit->type == 'delete')
952 $this->_deleted($edit->orig);
953 elseif ($edit->type == 'change')
954 $this->_changed($edit->orig, $edit->closing);
955 else
956 trigger_error("Unknown edit type", E_USER_ERROR);
958 $this->_end_block();
961 function _start_diff() {
962 ob_start();
965 function _end_diff() {
966 $val = ob_get_contents();
967 ob_end_clean();
968 return $val;
971 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
972 if ($xlen > 1)
973 $xbeg .= "," . ($xbeg + $xlen - 1);
974 if ($ylen > 1)
975 $ybeg .= "," . ($ybeg + $ylen - 1);
977 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
980 function _start_block($header) {
981 echo $header;
984 function _end_block() {
987 function _lines($lines, $prefix = ' ') {
988 foreach ($lines as $line)
989 echo "$prefix $line\n";
992 function _context($lines) {
993 $this->_lines($lines);
996 function _added($lines) {
997 $this->_lines($lines, ">");
999 function _deleted($lines) {
1000 $this->_lines($lines, "<");
1003 function _changed($orig, $closing) {
1004 $this->_deleted($orig);
1005 echo "---\n";
1006 $this->_added($closing);
1012 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1016 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1018 class _HWLDF_WordAccumulator {
1019 function _HWLDF_WordAccumulator () {
1020 $this->_lines = array();
1021 $this->_line = '';
1022 $this->_group = '';
1023 $this->_tag = '';
1026 function _flushGroup ($new_tag) {
1027 if ($this->_group !== '') {
1028 if ($this->_tag == 'mark')
1029 $this->_line .= '<span class="diffchange">'.$this->_group.'</span>';
1030 else
1031 $this->_line .= $this->_group;
1033 $this->_group = '';
1034 $this->_tag = $new_tag;
1037 function _flushLine ($new_tag) {
1038 $this->_flushGroup($new_tag);
1039 if ($this->_line != '')
1040 $this->_lines[] = $this->_line;
1041 $this->_line = '';
1044 function addWords ($words, $tag = '') {
1045 if ($tag != $this->_tag)
1046 $this->_flushGroup($tag);
1048 foreach ($words as $word) {
1049 // new-line should only come as first char of word.
1050 if ($word == '')
1051 continue;
1052 if ($word[0] == "\n") {
1053 $this->_group .= NBSP;
1054 $this->_flushLine($tag);
1055 $word = substr($word, 1);
1057 assert(!strstr($word, "\n"));
1058 $this->_group .= $word;
1062 function getLines() {
1063 $this->_flushLine('~done');
1064 return $this->_lines;
1068 class WordLevelDiff extends MappedDiff
1070 function WordLevelDiff ($orig_lines, $closing_lines) {
1071 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1072 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1075 $this->MappedDiff($orig_words, $closing_words,
1076 $orig_stripped, $closing_stripped);
1079 function _split($lines) {
1080 // FIXME: fix POSIX char class.
1081 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1082 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1083 implode("\n", $lines),
1084 $m)) {
1085 return array(array(''), array(''));
1087 return array($m[0], $m[1]);
1090 function orig () {
1091 $orig = new _HWLDF_WordAccumulator;
1093 foreach ($this->edits as $edit) {
1094 if ($edit->type == 'copy')
1095 $orig->addWords($edit->orig);
1096 elseif ($edit->orig)
1097 $orig->addWords($edit->orig, 'mark');
1099 return $orig->getLines();
1102 function closing () {
1103 $closing = new _HWLDF_WordAccumulator;
1105 foreach ($this->edits as $edit) {
1106 if ($edit->type == 'copy')
1107 $closing->addWords($edit->closing);
1108 elseif ($edit->closing)
1109 $closing->addWords($edit->closing, 'mark');
1111 return $closing->getLines();
1116 * Wikipedia Table style diff formatter.
1119 class TableDiffFormatter extends DiffFormatter
1121 function TableDiffFormatter() {
1122 $this->leading_context_lines = 2;
1123 $this->trailing_context_lines = 2;
1126 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1127 $l1 = wfMsg( "lineno", $xbeg );
1128 $l2 = wfMsg( "lineno", $ybeg );
1130 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1131 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1132 return $r;
1135 function _start_block( $header ) {
1136 global $wgOut;
1137 $wgOut->addHTML( $header );
1140 function _end_block() {
1143 function _lines( $lines, $prefix=' ', $color="white" ) {
1146 function addedLine( $line ) {
1147 return '<td>+</td><td class="diff-addedline">' .
1148 $line.'</td>';
1151 function deletedLine( $line ) {
1152 return '<td>-</td><td class="diff-deletedline">' .
1153 $line.'</td>';
1156 function emptyLine() {
1157 return '<td colspan="2">&nbsp;</td>';
1160 function contextLine( $line ) {
1161 return '<td> </td><td class="diff-context">'.$line.'</td>';
1164 function _added($lines) {
1165 global $wgOut;
1166 foreach ($lines as $line) {
1167 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1168 $this->addedLine( $line ) . "</tr>\n" );
1172 function _deleted($lines) {
1173 global $wgOut;
1174 foreach ($lines as $line) {
1175 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1176 $this->emptyLine() . "</tr>\n" );
1180 function _context( $lines ) {
1181 global $wgOut;
1182 foreach ($lines as $line) {
1183 $wgOut->addHTML( '<tr>' . $this->contextLine( $line ) .
1184 $this->contextLine( $line ) . "</tr>\n" );
1188 function _changed( $orig, $closing ) {
1189 global $wgOut;
1190 $diff = new WordLevelDiff( $orig, $closing );
1191 $del = $diff->orig();
1192 $add = $diff->closing();
1194 while ( $line = array_shift( $del ) ) {
1195 $aline = array_shift( $add );
1196 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1197 $this->addedLine( $aline ) . "</tr>\n" );
1199 $this->_added( $add ); # If any leftovers