removed non-matching wfProfileOut() calls
[mediawiki.git] / includes / DifferenceEngine.php
blob4ba5b7713d8dca3419e67d39c0d6038ad94f82a7
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;
22 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
23 "{$this->mNewid})";
24 $mtext = wfMsg( "missingarticle", $t );
26 $wgOut->setArticleFlag( false );
27 if ( ! $this->loadText() ) {
28 $wgOut->setPagetitle( wfMsg( "errorpagetitle" ) );
29 $wgOut->addHTML( $mtext );
30 return;
32 $wgOut->suppressQuickbar();
34 $oldTitle = $this->mOldPage->getPrefixedText();
35 $newTitle = $this->mNewPage->getPrefixedText();
36 if( $oldTitle == $newTitle ) {
37 $wgOut->setPageTitle( $newTitle );
38 } else {
39 $wgOut->setPageTitle( $oldTitle . ", " . $newTitle );
41 $wgOut->setSubtitle( wfMsg( "difference" ) );
42 $wgOut->setRobotpolicy( "noindex,follow" );
44 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
45 $wgOut->loginToUse();
46 $wgOut->output();
47 exit;
50 $sk = $wgUser->getSkin();
51 $talk = $wgLang->getNsText( NS_TALK );
52 $contribs = wfMsg( "contribslink" );
55 $this->mOldComment = $sk->formatComment($this->mOldComment);
56 $this->mNewComment = $sk->formatComment($this->mNewComment);
59 $oldUserLink = $sk->makeLinkObj( Title::makeTitle( NS_USER, $this->mOldUser ), $this->mOldUser );
60 $newUserLink = $sk->makeLinkObj( Title::makeTitle( NS_USER, $this->mNewUser ), $this->mNewUser );
61 $oldUTLink = $sk->makeLinkObj( Title::makeTitle( NS_USER_TALK, $this->mOldUser ), $talk );
62 $newUTLink = $sk->makeLinkObj( Title::makeTitle( NS_USER_TALK, $this->mNewUser ), $talk );
63 $oldContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, "Contributions" ), $contribs,
64 "target=" . urlencode($this->mOldUser) );
65 $newContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, "Contributions" ), $contribs,
66 "target=" . urlencode($this->mNewUser) );
67 if ( !$this->mNewid && $wgUser->isSysop() ) {
68 $rollback = "&nbsp;&nbsp;&nbsp;<strong>[" . $sk->makeKnownLinkObj( $wgTitle, wfMsg( "rollbacklink" ),
69 "action=rollback&from=" . urlencode($this->mNewUser) ) . "]</strong>";
70 } else {
71 $rollback = "";
74 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink ($oldUTLink | $oldContribs)<br />".
75 $this->mOldComment;
76 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink ($newUTLink | $newContribs) $rollback<br />".
77 $this->mNewComment;
79 DifferenceEngine::showDiff( $this->mOldtext, $this->mNewtext,
80 $oldHeader, $newHeader );
81 $wgOut->addHTML( "<hr /><h2>{$this->mNewtitle}</h2>\n" );
82 $wgOut->addWikiText( $this->mNewtext );
85 function showDiff( $otext, $ntext, $otitle, $ntitle )
87 global $wgOut;
89 $ota = explode( "\n", str_replace( "\r\n", "\n",
90 htmlspecialchars( $otext ) ) );
91 $nta = explode( "\n", str_replace( "\r\n", "\n",
92 htmlspecialchars( $ntext ) ) );
94 $wgOut->addHTML( "<table border='0' width='98%'
95 cellpadding='0' cellspacing='4px' class='diff'><tr>
96 <td colspan='2' width='50%' align='center' class='diff-otitle'>
97 {$otitle}</td>
98 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
99 {$ntitle}</td>
100 </tr>\n" );
102 $diffs = new Diff( $ota, $nta );
103 $formatter = new TableDiffFormatter();
104 $formatter->format( $diffs );
105 $wgOut->addHTML( "</table>\n" );
108 # Load the text of the articles to compare. If newid is 0, then compare
109 # the old article in oldid to the current article; if oldid is 0, then
110 # compare the current article to the immediately previous one (ignoring
111 # the value of newid).
113 function loadText()
115 global $wgTitle, $wgOut, $wgLang;
116 $fname = "DifferenceEngine::loadText";
118 if ( 0 == $this->mNewid || 0 == $this->mOldid ) {
119 $wgOut->setArticleFlag( true );
120 $this->mNewtitle = wfMsg( "currentrev" );
121 $id = $wgTitle->getArticleID();
123 $sql = "SELECT cur_text, cur_user_text, cur_comment FROM cur WHERE cur_id={$id}";
124 $res = wfQuery( $sql, DB_READ, $fname );
125 if ( 0 == wfNumRows( $res ) ) { return false; }
127 $s = wfFetchObject( $res );
128 $this->mNewPage = &$wgTitle;
129 $this->mNewtext = $s->cur_text;
130 $this->mNewUser = $s->cur_user_text;
131 $this->mNewComment = $s->cur_comment;
132 } else {
133 $sql = "SELECT old_namespace,old_title,old_timestamp,old_text,old_flags,old_user_text,old_comment FROM old WHERE " .
134 "old_id={$this->mNewid}";
136 $res = wfQuery( $sql, DB_READ, $fname );
137 if ( 0 == wfNumRows( $res ) ) { return false; }
139 $s = wfFetchObject( $res );
140 $this->mNewtext = Article::getRevisionText( $s );
142 $t = $wgLang->timeanddate( $s->old_timestamp, true );
143 $this->mNewPage = Title::MakeTitle( $s->old_namespace, $s->old_title );
144 $this->mNewtitle = wfMsg( "revisionasof", $t );
145 $this->mNewUser = $s->old_user_text;
146 $this->mNewComment = $s->old_comment;
148 if ( 0 == $this->mOldid ) {
149 $sql = "SELECT old_namespace,old_title,old_timestamp,old_text,old_flags,old_user_text,old_comment " .
150 "FROM old USE INDEX (name_title_timestamp) WHERE " .
151 "old_namespace=" . $this->mNewPage->getNamespace() . " AND " .
152 "old_title='" . wfStrencode( $this->mNewPage->getDBkey() ) .
153 "' ORDER BY inverse_timestamp LIMIT 1";
154 $res = wfQuery( $sql, DB_READ, $fname );
155 } else {
156 $sql = "SELECT old_namespace,old_title,old_timestamp,old_text,old_flags,old_user_text,old_comment FROM old WHERE " .
157 "old_id={$this->mOldid}";
158 $res = wfQuery( $sql, DB_READ, $fname );
160 if ( 0 == wfNumRows( $res ) ) { return false; }
162 $s = wfFetchObject( $res );
163 $this->mOldPage = Title::MakeTitle( $s->old_namespace, $s->old_title );
164 $this->mOldtext = Article::getRevisionText( $s );
166 $t = $wgLang->timeanddate( $s->old_timestamp, true );
167 $this->mOldtitle = wfMsg( "revisionasof", $t );
168 $this->mOldUser = $s->old_user_text;
169 $this->mOldComment = $s->old_comment;
171 return true;
175 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
177 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
178 // You may copy this code freely under the conditions of the GPL.
181 define('USE_ASSERTS', function_exists('assert'));
183 class _DiffOp {
184 var $type;
185 var $orig;
186 var $closing;
188 function reverse() {
189 trigger_error("pure virtual", E_USER_ERROR);
192 function norig() {
193 return $this->orig ? sizeof($this->orig) : 0;
196 function nclosing() {
197 return $this->closing ? sizeof($this->closing) : 0;
201 class _DiffOp_Copy extends _DiffOp {
202 var $type = 'copy';
204 function _DiffOp_Copy ($orig, $closing = false) {
205 if (!is_array($closing))
206 $closing = $orig;
207 $this->orig = $orig;
208 $this->closing = $closing;
211 function reverse() {
212 return new _DiffOp_Copy($this->closing, $this->orig);
216 class _DiffOp_Delete extends _DiffOp {
217 var $type = 'delete';
219 function _DiffOp_Delete ($lines) {
220 $this->orig = $lines;
221 $this->closing = false;
224 function reverse() {
225 return new _DiffOp_Add($this->orig);
229 class _DiffOp_Add extends _DiffOp {
230 var $type = 'add';
232 function _DiffOp_Add ($lines) {
233 $this->closing = $lines;
234 $this->orig = false;
237 function reverse() {
238 return new _DiffOp_Delete($this->closing);
242 class _DiffOp_Change extends _DiffOp {
243 var $type = 'change';
245 function _DiffOp_Change ($orig, $closing) {
246 $this->orig = $orig;
247 $this->closing = $closing;
250 function reverse() {
251 return new _DiffOp_Change($this->closing, $this->orig);
257 * Class used internally by Diff to actually compute the diffs.
259 * The algorithm used here is mostly lifted from the perl module
260 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
261 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
263 * More ideas are taken from:
264 * http://www.ics.uci.edu/~eppstein/161/960229.html
266 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
267 * diffutils-2.7, which can be found at:
268 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
270 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
271 * are my own.
273 * @author Geoffrey T. Dairiki
274 * @access private
276 class _DiffEngine
278 function diff ($from_lines, $to_lines) {
279 $n_from = sizeof($from_lines);
280 $n_to = sizeof($to_lines);
282 $this->xchanged = $this->ychanged = array();
283 $this->xv = $this->yv = array();
284 $this->xind = $this->yind = array();
285 unset($this->seq);
286 unset($this->in_seq);
287 unset($this->lcs);
289 // Skip leading common lines.
290 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
291 if ($from_lines[$skip] != $to_lines[$skip])
292 break;
293 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
295 // Skip trailing common lines.
296 $xi = $n_from; $yi = $n_to;
297 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
298 if ($from_lines[$xi] != $to_lines[$yi])
299 break;
300 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
303 // Ignore lines which do not exist in both files.
304 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
305 $xhash[$from_lines[$xi]] = 1;
306 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
307 $line = $to_lines[$yi];
308 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
309 continue;
310 $yhash[$line] = 1;
311 $this->yv[] = $line;
312 $this->yind[] = $yi;
314 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
315 $line = $from_lines[$xi];
316 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
317 continue;
318 $this->xv[] = $line;
319 $this->xind[] = $xi;
322 // Find the LCS.
323 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
325 // Merge edits when possible
326 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
327 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
329 // Compute the edit operations.
330 $edits = array();
331 $xi = $yi = 0;
332 while ($xi < $n_from || $yi < $n_to) {
333 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
334 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
336 // Skip matching "snake".
337 $copy = array();
338 while ( $xi < $n_from && $yi < $n_to
339 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
340 $copy[] = $from_lines[$xi++];
341 ++$yi;
343 if ($copy)
344 $edits[] = new _DiffOp_Copy($copy);
346 // Find deletes & adds.
347 $delete = array();
348 while ($xi < $n_from && $this->xchanged[$xi])
349 $delete[] = $from_lines[$xi++];
351 $add = array();
352 while ($yi < $n_to && $this->ychanged[$yi])
353 $add[] = $to_lines[$yi++];
355 if ($delete && $add)
356 $edits[] = new _DiffOp_Change($delete, $add);
357 elseif ($delete)
358 $edits[] = new _DiffOp_Delete($delete);
359 elseif ($add)
360 $edits[] = new _DiffOp_Add($add);
362 return $edits;
366 /* Divide the Largest Common Subsequence (LCS) of the sequences
367 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
368 * sized segments.
370 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
371 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
372 * sub sequences. The first sub-sequence is contained in [X0, X1),
373 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
374 * that (X0, Y0) == (XOFF, YOFF) and
375 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
377 * This function assumes that the first lines of the specified portions
378 * of the two files do not match, and likewise that the last lines do not
379 * match. The caller must trim matching lines from the beginning and end
380 * of the portions it is going to specify.
382 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
383 $flip = false;
385 if ($xlim - $xoff > $ylim - $yoff) {
386 // Things seems faster (I'm not sure I understand why)
387 // when the shortest sequence in X.
388 $flip = true;
389 list ($xoff, $xlim, $yoff, $ylim)
390 = array( $yoff, $ylim, $xoff, $xlim);
393 if ($flip)
394 for ($i = $ylim - 1; $i >= $yoff; $i--)
395 $ymatches[$this->xv[$i]][] = $i;
396 else
397 for ($i = $ylim - 1; $i >= $yoff; $i--)
398 $ymatches[$this->yv[$i]][] = $i;
400 $this->lcs = 0;
401 $this->seq[0]= $yoff - 1;
402 $this->in_seq = array();
403 $ymids[0] = array();
405 $numer = $xlim - $xoff + $nchunks - 1;
406 $x = $xoff;
407 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
408 if ($chunk > 0)
409 for ($i = 0; $i <= $this->lcs; $i++)
410 $ymids[$i][$chunk-1] = $this->seq[$i];
412 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
413 for ( ; $x < $x1; $x++) {
414 $line = $flip ? $this->yv[$x] : $this->xv[$x];
415 if (empty($ymatches[$line]))
416 continue;
417 $matches = $ymatches[$line];
418 reset($matches);
419 while (list ($junk, $y) = each($matches))
420 if (empty($this->in_seq[$y])) {
421 $k = $this->_lcs_pos($y);
422 USE_ASSERTS && assert($k > 0);
423 $ymids[$k] = $ymids[$k-1];
424 break;
426 while (list ($junk, $y) = each($matches)) {
427 if ($y > $this->seq[$k-1]) {
428 USE_ASSERTS && assert($y < $this->seq[$k]);
429 // Optimization: this is a common case:
430 // next match is just replacing previous match.
431 $this->in_seq[$this->seq[$k]] = false;
432 $this->seq[$k] = $y;
433 $this->in_seq[$y] = 1;
435 else if (empty($this->in_seq[$y])) {
436 $k = $this->_lcs_pos($y);
437 USE_ASSERTS && assert($k > 0);
438 $ymids[$k] = $ymids[$k-1];
444 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
445 $ymid = $ymids[$this->lcs];
446 for ($n = 0; $n < $nchunks - 1; $n++) {
447 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
448 $y1 = $ymid[$n] + 1;
449 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
451 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
453 return array($this->lcs, $seps);
456 function _lcs_pos ($ypos) {
457 $end = $this->lcs;
458 if ($end == 0 || $ypos > $this->seq[$end]) {
459 $this->seq[++$this->lcs] = $ypos;
460 $this->in_seq[$ypos] = 1;
461 return $this->lcs;
464 $beg = 1;
465 while ($beg < $end) {
466 $mid = (int)(($beg + $end) / 2);
467 if ( $ypos > $this->seq[$mid] )
468 $beg = $mid + 1;
469 else
470 $end = $mid;
473 USE_ASSERTS && assert($ypos != $this->seq[$end]);
475 $this->in_seq[$this->seq[$end]] = false;
476 $this->seq[$end] = $ypos;
477 $this->in_seq[$ypos] = 1;
478 return $end;
481 /* Find LCS of two sequences.
483 * The results are recorded in the vectors $this->{x,y}changed[], by
484 * storing a 1 in the element for each line that is an insertion
485 * or deletion (ie. is not in the LCS).
487 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
489 * Note that XLIM, YLIM are exclusive bounds.
490 * All line numbers are origin-0 and discarded lines are not counted.
492 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
493 // Slide down the bottom initial diagonal.
494 while ($xoff < $xlim && $yoff < $ylim
495 && $this->xv[$xoff] == $this->yv[$yoff]) {
496 ++$xoff;
497 ++$yoff;
500 // Slide up the top initial diagonal.
501 while ($xlim > $xoff && $ylim > $yoff
502 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
503 --$xlim;
504 --$ylim;
507 if ($xoff == $xlim || $yoff == $ylim)
508 $lcs = 0;
509 else {
510 // This is ad hoc but seems to work well.
511 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
512 //$nchunks = max(2,min(8,(int)$nchunks));
513 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
514 list ($lcs, $seps)
515 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
518 if ($lcs == 0) {
519 // X and Y sequences have no common subsequence:
520 // mark all changed.
521 while ($yoff < $ylim)
522 $this->ychanged[$this->yind[$yoff++]] = 1;
523 while ($xoff < $xlim)
524 $this->xchanged[$this->xind[$xoff++]] = 1;
526 else {
527 // Use the partitions to split this problem into subproblems.
528 reset($seps);
529 $pt1 = $seps[0];
530 while ($pt2 = next($seps)) {
531 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
532 $pt1 = $pt2;
537 /* Adjust inserts/deletes of identical lines to join changes
538 * as much as possible.
540 * We do something when a run of changed lines include a
541 * line at one end and has an excluded, identical line at the other.
542 * We are free to choose which identical line is included.
543 * `compareseq' usually chooses the one at the beginning,
544 * but usually it is cleaner to consider the following identical line
545 * to be the "change".
547 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
549 function _shift_boundaries ($lines, &$changed, $other_changed) {
550 $i = 0;
551 $j = 0;
553 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
554 $len = sizeof($lines);
555 $other_len = sizeof($other_changed);
557 while (1) {
559 * Scan forwards to find beginning of another run of changes.
560 * Also keep track of the corresponding point in the other file.
562 * Throughout this code, $i and $j are adjusted together so that
563 * the first $i elements of $changed and the first $j elements
564 * of $other_changed both contain the same number of zeros
565 * (unchanged lines).
566 * Furthermore, $j is always kept so that $j == $other_len or
567 * $other_changed[$j] == false.
569 while ($j < $other_len && $other_changed[$j])
570 $j++;
572 while ($i < $len && ! $changed[$i]) {
573 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
574 $i++; $j++;
575 while ($j < $other_len && $other_changed[$j])
576 $j++;
579 if ($i == $len)
580 break;
582 $start = $i;
584 // Find the end of this run of changes.
585 while (++$i < $len && $changed[$i])
586 continue;
588 do {
590 * Record the length of this run of changes, so that
591 * we can later determine whether the run has grown.
593 $runlength = $i - $start;
596 * Move the changed region back, so long as the
597 * previous unchanged line matches the last changed one.
598 * This merges with previous changed regions.
600 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
601 $changed[--$start] = 1;
602 $changed[--$i] = false;
603 while ($start > 0 && $changed[$start - 1])
604 $start--;
605 USE_ASSERTS && assert('$j > 0');
606 while ($other_changed[--$j])
607 continue;
608 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
612 * Set CORRESPONDING to the end of the changed run, at the last
613 * point where it corresponds to a changed run in the other file.
614 * CORRESPONDING == LEN means no such point has been found.
616 $corresponding = $j < $other_len ? $i : $len;
619 * Move the changed region forward, so long as the
620 * first changed line matches the following unchanged one.
621 * This merges with following changed regions.
622 * Do this second, so that if there are no merges,
623 * the changed region is moved forward as far as possible.
625 while ($i < $len && $lines[$start] == $lines[$i]) {
626 $changed[$start++] = false;
627 $changed[$i++] = 1;
628 while ($i < $len && $changed[$i])
629 $i++;
631 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
632 $j++;
633 if ($j < $other_len && $other_changed[$j]) {
634 $corresponding = $i;
635 while ($j < $other_len && $other_changed[$j])
636 $j++;
639 } while ($runlength != $i - $start);
642 * If possible, move the fully-merged run of changes
643 * back to a corresponding run in the other file.
645 while ($corresponding < $i) {
646 $changed[--$start] = 1;
647 $changed[--$i] = 0;
648 USE_ASSERTS && assert('$j > 0');
649 while ($other_changed[--$j])
650 continue;
651 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
658 * Class representing a 'diff' between two sequences of strings.
660 class Diff
662 var $edits;
665 * Constructor.
666 * Computes diff between sequences of strings.
668 * @param $from_lines array An array of strings.
669 * (Typically these are lines from a file.)
670 * @param $to_lines array An array of strings.
672 function Diff($from_lines, $to_lines) {
673 $eng = new _DiffEngine;
674 $this->edits = $eng->diff($from_lines, $to_lines);
675 //$this->_check($from_lines, $to_lines);
679 * Compute reversed Diff.
681 * SYNOPSIS:
683 * $diff = new Diff($lines1, $lines2);
684 * $rev = $diff->reverse();
685 * @return object A Diff object representing the inverse of the
686 * original diff.
688 function reverse () {
689 $rev = $this;
690 $rev->edits = array();
691 foreach ($this->edits as $edit) {
692 $rev->edits[] = $edit->reverse();
694 return $rev;
698 * Check for empty diff.
700 * @return bool True iff two sequences were identical.
702 function isEmpty () {
703 foreach ($this->edits as $edit) {
704 if ($edit->type != 'copy')
705 return false;
707 return true;
711 * Compute the length of the Longest Common Subsequence (LCS).
713 * This is mostly for diagnostic purposed.
715 * @return int The length of the LCS.
717 function lcs () {
718 $lcs = 0;
719 foreach ($this->edits as $edit) {
720 if ($edit->type == 'copy')
721 $lcs += sizeof($edit->orig);
723 return $lcs;
727 * Get the original set of lines.
729 * This reconstructs the $from_lines parameter passed to the
730 * constructor.
732 * @return array The original sequence of strings.
734 function orig() {
735 $lines = array();
737 foreach ($this->edits as $edit) {
738 if ($edit->orig)
739 array_splice($lines, sizeof($lines), 0, $edit->orig);
741 return $lines;
745 * Get the closing set of lines.
747 * This reconstructs the $to_lines parameter passed to the
748 * constructor.
750 * @return array The sequence of strings.
752 function closing() {
753 $lines = array();
755 foreach ($this->edits as $edit) {
756 if ($edit->closing)
757 array_splice($lines, sizeof($lines), 0, $edit->closing);
759 return $lines;
763 * Check a Diff for validity.
765 * This is here only for debugging purposes.
767 function _check ($from_lines, $to_lines) {
768 if (serialize($from_lines) != serialize($this->orig()))
769 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
770 if (serialize($to_lines) != serialize($this->closing()))
771 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
773 $rev = $this->reverse();
774 if (serialize($to_lines) != serialize($rev->orig()))
775 trigger_error("Reversed original doesn't match", E_USER_ERROR);
776 if (serialize($from_lines) != serialize($rev->closing()))
777 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
780 $prevtype = 'none';
781 foreach ($this->edits as $edit) {
782 if ( $prevtype == $edit->type )
783 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
784 $prevtype = $edit->type;
787 $lcs = $this->lcs();
788 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
793 * FIXME: bad name.
795 class MappedDiff
796 extends Diff
799 * Constructor.
801 * Computes diff between sequences of strings.
803 * This can be used to compute things like
804 * case-insensitve diffs, or diffs which ignore
805 * changes in white-space.
807 * @param $from_lines array An array of strings.
808 * (Typically these are lines from a file.)
810 * @param $to_lines array An array of strings.
812 * @param $mapped_from_lines array This array should
813 * have the same size number of elements as $from_lines.
814 * The elements in $mapped_from_lines and
815 * $mapped_to_lines are what is actually compared
816 * when computing the diff.
818 * @param $mapped_to_lines array This array should
819 * have the same number of elements as $to_lines.
821 function MappedDiff($from_lines, $to_lines,
822 $mapped_from_lines, $mapped_to_lines) {
824 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
825 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
827 $this->Diff($mapped_from_lines, $mapped_to_lines);
829 $xi = $yi = 0;
830 for ($i = 0; $i < sizeof($this->edits); $i++) {
831 $orig = &$this->edits[$i]->orig;
832 if (is_array($orig)) {
833 $orig = array_slice($from_lines, $xi, sizeof($orig));
834 $xi += sizeof($orig);
837 $closing = &$this->edits[$i]->closing;
838 if (is_array($closing)) {
839 $closing = array_slice($to_lines, $yi, sizeof($closing));
840 $yi += sizeof($closing);
847 * A class to format Diffs
849 * This class formats the diff in classic diff format.
850 * It is intended that this class be customized via inheritance,
851 * to obtain fancier outputs.
853 class DiffFormatter
856 * Number of leading context "lines" to preserve.
858 * This should be left at zero for this class, but subclasses
859 * may want to set this to other values.
861 var $leading_context_lines = 0;
864 * Number of trailing context "lines" to preserve.
866 * This should be left at zero for this class, but subclasses
867 * may want to set this to other values.
869 var $trailing_context_lines = 0;
872 * Format a diff.
874 * @param $diff object A Diff object.
875 * @return string The formatted output.
877 function format($diff) {
879 $xi = $yi = 1;
880 $block = false;
881 $context = array();
883 $nlead = $this->leading_context_lines;
884 $ntrail = $this->trailing_context_lines;
886 $this->_start_diff();
888 foreach ($diff->edits as $edit) {
889 if ($edit->type == 'copy') {
890 if (is_array($block)) {
891 if (sizeof($edit->orig) <= $nlead + $ntrail) {
892 $block[] = $edit;
894 else{
895 if ($ntrail) {
896 $context = array_slice($edit->orig, 0, $ntrail);
897 $block[] = new _DiffOp_Copy($context);
899 $this->_block($x0, $ntrail + $xi - $x0,
900 $y0, $ntrail + $yi - $y0,
901 $block);
902 $block = false;
905 $context = $edit->orig;
907 else {
908 if (! is_array($block)) {
909 $context = array_slice($context, sizeof($context) - $nlead);
910 $x0 = $xi - sizeof($context);
911 $y0 = $yi - sizeof($context);
912 $block = array();
913 if ($context)
914 $block[] = new _DiffOp_Copy($context);
916 $block[] = $edit;
919 if ($edit->orig)
920 $xi += sizeof($edit->orig);
921 if ($edit->closing)
922 $yi += sizeof($edit->closing);
925 if (is_array($block))
926 $this->_block($x0, $xi - $x0,
927 $y0, $yi - $y0,
928 $block);
930 return $this->_end_diff();
933 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
934 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
935 foreach ($edits as $edit) {
936 if ($edit->type == 'copy')
937 $this->_context($edit->orig);
938 elseif ($edit->type == 'add')
939 $this->_added($edit->closing);
940 elseif ($edit->type == 'delete')
941 $this->_deleted($edit->orig);
942 elseif ($edit->type == 'change')
943 $this->_changed($edit->orig, $edit->closing);
944 else
945 trigger_error("Unknown edit type", E_USER_ERROR);
947 $this->_end_block();
950 function _start_diff() {
951 ob_start();
954 function _end_diff() {
955 $val = ob_get_contents();
956 ob_end_clean();
957 return $val;
960 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
961 if ($xlen > 1)
962 $xbeg .= "," . ($xbeg + $xlen - 1);
963 if ($ylen > 1)
964 $ybeg .= "," . ($ybeg + $ylen - 1);
966 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
969 function _start_block($header) {
970 echo $header;
973 function _end_block() {
976 function _lines($lines, $prefix = ' ') {
977 foreach ($lines as $line)
978 echo "$prefix $line\n";
981 function _context($lines) {
982 $this->_lines($lines);
985 function _added($lines) {
986 $this->_lines($lines, ">");
988 function _deleted($lines) {
989 $this->_lines($lines, "<");
992 function _changed($orig, $closing) {
993 $this->_deleted($orig);
994 echo "---\n";
995 $this->_added($closing);
1001 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1005 define('NBSP', "\xA0"); // iso-8859-x non-breaking space.
1007 class _HWLDF_WordAccumulator {
1008 function _HWLDF_WordAccumulator () {
1009 $this->_lines = array();
1010 $this->_line = '';
1011 $this->_group = '';
1012 $this->_tag = '';
1015 function _flushGroup ($new_tag) {
1016 if ($this->_group !== '') {
1017 if ($this->_tag == 'mark')
1018 $this->_line .= "<font color=\"red\">$this->_group</font>";
1019 else
1020 $this->_line .= $this->_group;
1022 $this->_group = '';
1023 $this->_tag = $new_tag;
1026 function _flushLine ($new_tag) {
1027 $this->_flushGroup($new_tag);
1028 if ($this->_line != '')
1029 $this->_lines[] = $this->_line;
1030 $this->_line = '';
1033 function addWords ($words, $tag = '') {
1034 if ($tag != $this->_tag)
1035 $this->_flushGroup($tag);
1037 foreach ($words as $word) {
1038 // new-line should only come as first char of word.
1039 if ($word == '')
1040 continue;
1041 if ($word[0] == "\n") {
1042 $this->_group .= NBSP;
1043 $this->_flushLine($tag);
1044 $word = substr($word, 1);
1046 assert(!strstr($word, "\n"));
1047 $this->_group .= $word;
1051 function getLines() {
1052 $this->_flushLine('~done');
1053 return $this->_lines;
1057 class WordLevelDiff extends MappedDiff
1059 function WordLevelDiff ($orig_lines, $closing_lines) {
1060 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1061 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1064 $this->MappedDiff($orig_words, $closing_words,
1065 $orig_stripped, $closing_stripped);
1068 function _split($lines) {
1069 // FIXME: fix POSIX char class.
1070 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1071 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1072 implode("\n", $lines),
1073 $m)) {
1074 return array(array(''), array(''));
1076 return array($m[0], $m[1]);
1079 function orig () {
1080 $orig = new _HWLDF_WordAccumulator;
1082 foreach ($this->edits as $edit) {
1083 if ($edit->type == 'copy')
1084 $orig->addWords($edit->orig);
1085 elseif ($edit->orig)
1086 $orig->addWords($edit->orig, 'mark');
1088 return $orig->getLines();
1091 function closing () {
1092 $closing = new _HWLDF_WordAccumulator;
1094 foreach ($this->edits as $edit) {
1095 if ($edit->type == 'copy')
1096 $closing->addWords($edit->closing);
1097 elseif ($edit->closing)
1098 $closing->addWords($edit->closing, 'mark');
1100 return $closing->getLines();
1105 * Wikipedia Table style diff formatter.
1108 class TableDiffFormatter extends DiffFormatter
1110 function TableDiffFormatter() {
1111 $this->leading_context_lines = 2;
1112 $this->trailing_context_lines = 2;
1115 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1116 $l1 = wfMsg( "lineno", $xbeg );
1117 $l2 = wfMsg( "lineno", $ybeg );
1119 $r = "<tr><td colspan='2' align='left'><strong>{$l1}</strong></td>\n" .
1120 "<td colspan='2' align='left'><strong>{$l2}</strong></td></tr>\n";
1121 return $r;
1124 function _start_block( $header ) {
1125 global $wgOut;
1126 $wgOut->addHTML( $header );
1129 function _end_block() {
1132 function _lines( $lines, $prefix=' ', $color="white" ) {
1135 function addedLine( $line ) {
1136 return "<td>+</td><td class='diff-addedline'>" .
1137 "<small>{$line}</small></td>";
1140 function deletedLine( $line ) {
1141 return "<td>-</td><td class='diff-deletedline'>" .
1142 "<small>{$line}</small></td>";
1145 function emptyLine() {
1146 return "<td colspan='2'>&nbsp;</td>";
1149 function contextLine( $line ) {
1150 return "<td> </td><td class='diff-context'><small>{$line}</small></td>";
1153 function _added($lines) {
1154 global $wgOut;
1155 foreach ($lines as $line) {
1156 $wgOut->addHTML( "<tr>" . $this->emptyLine() .
1157 $this->addedLine( $line ) . "</tr>\n" );
1161 function _deleted($lines) {
1162 global $wgOut;
1163 foreach ($lines as $line) {
1164 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1165 $this->emptyLine() . "</tr>\n" );
1169 function _context( $lines ) {
1170 global $wgOut;
1171 foreach ($lines as $line) {
1172 $wgOut->addHTML( "<tr>" . $this->contextLine( $line ) .
1173 $this->contextLine( $line ) . "</tr>\n" );
1177 function _changed( $orig, $closing ) {
1178 global $wgOut;
1179 $diff = new WordLevelDiff( $orig, $closing );
1180 $del = $diff->orig();
1181 $add = $diff->closing();
1183 while ( $line = array_shift( $del ) ) {
1184 $aline = array_shift( $add );
1185 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1186 $this->addedLine( $aline ) . "</tr>\n" );
1188 $this->_added( $add ); # If any leftovers