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 )
18 function showDiffPage()
20 global $wgUser, $wgTitle, $wgOut, $wgLang;
21 $fname = "DifferenceEngine::showDiffPage";
22 wfProfileIn( $fname );
24 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
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 );
35 $wgOut->suppressQuickbar();
37 $oldTitle = $this->mOldPage
->getPrefixedText();
38 $newTitle = $this->mNewPage
->getPrefixedText();
39 if( $oldTitle == $newTitle ) {
40 $wgOut->setPageTitle( $newTitle );
42 $wgOut->setPageTitle( $oldTitle . ", " . $newTitle );
44 $wgOut->setSubtitle( wfMsg( "difference" ) );
45 $wgOut->setRobotpolicy( "noindex,follow" );
47 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
50 wfProfileOut( $fname );
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 = " <strong>[" . $sk->makeKnownLinkObj( $wgTitle, wfMsg( "rollbacklink" ),
73 "action=rollback&from=" . urlencode($this->mNewUser
) ) . "]</strong>";
78 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink ($oldUTLink | $oldContribs)<br />".
80 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink ($newUTLink | $newContribs) $rollback<br />".
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, $wgUseExternalDiffEngine;
95 $otext = str_replace( "\r\n", "\n", htmlspecialchars( $otext ) );
96 $ntext = str_replace( "\r\n", "\n", htmlspecialchars( $ntext ) );
99 $wgOut->addHTML( "<table border='0' width='98%'
100 cellpadding='0' cellspacing='4px' class='diff'><tr>
101 <td colspan='2' width='50%' align='center' class='diff-otitle'>
103 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
106 if ( $wgUseExternalDiffEngine ) {
107 dl("php_wikidiff.so");
108 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
110 $ota = explode( "\n", $otext);
111 $nta = explode( "\n", $ntext);
112 $diffs = new Diff( $ota, $nta );
113 $formatter = new TableDiffFormatter();
114 $formatter->format( $diffs );
116 $wgOut->addHTML( "</table>\n" );
119 # Load the text of the articles to compare. If newid is 0, then compare
120 # the old article in oldid to the current article; if oldid is 0, then
121 # compare the current article to the immediately previous one (ignoring
122 # the value of newid).
126 global $wgTitle, $wgOut, $wgLang;
127 $fname = "DifferenceEngine::loadText";
129 $dbr =& wfGetDB( DB_SLAVE
);
130 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
131 $wgOut->setArticleFlag( true );
132 $this->mNewtitle
= wfMsg( "currentrev" );
133 $id = $wgTitle->getArticleID();
135 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
136 array( 'cur_id' => $id ), $fname );
137 if ( $s === false ) {
141 $this->mNewPage
= &$wgTitle;
142 $this->mNewtext
= $s->cur_text
;
143 $this->mNewUser
= $s->cur_user_text
;
144 $this->mNewComment
= $s->cur_comment
;
146 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
147 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
149 if ( $s === false ) {
153 $this->mNewtext
= Article
::getRevisionText( $s );
155 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
156 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
157 $this->mNewtitle
= wfMsg( "revisionasof", $t );
158 $this->mNewUser
= $s->old_user_text
;
159 $this->mNewComment
= $s->old_comment
;
161 if ( 0 == $this->mOldid
) {
162 $s = $dbr->getArray( 'old',
163 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
165 'old_namespace' => $this->mNewPage
->getNamespace(),
166 'old_title' => $this->mNewPage
->getDBkey()
167 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
170 $s = $dbr->getArray( 'old',
171 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
172 array( 'old_id' => $this->mOldid
),
176 if ( $s === false ) {
179 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
180 $this->mOldtext
= Article
::getRevisionText( $s );
182 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
183 $this->mOldtitle
= wfMsg( "revisionasof", $t );
184 $this->mOldUser
= $s->old_user_text
;
185 $this->mOldComment
= $s->old_comment
;
191 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
193 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
194 // You may copy this code freely under the conditions of the GPL.
197 define('USE_ASSERTS', function_exists('assert'));
205 trigger_error("pure virtual", E_USER_ERROR
);
209 return $this->orig ?
sizeof($this->orig
) : 0;
212 function nclosing() {
213 return $this->closing ?
sizeof($this->closing
) : 0;
217 class _DiffOp_Copy
extends _DiffOp
{
220 function _DiffOp_Copy ($orig, $closing = false) {
221 if (!is_array($closing))
224 $this->closing
= $closing;
228 return new _DiffOp_Copy($this->closing
, $this->orig
);
232 class _DiffOp_Delete
extends _DiffOp
{
233 var $type = 'delete';
235 function _DiffOp_Delete ($lines) {
236 $this->orig
= $lines;
237 $this->closing
= false;
241 return new _DiffOp_Add($this->orig
);
245 class _DiffOp_Add
extends _DiffOp
{
248 function _DiffOp_Add ($lines) {
249 $this->closing
= $lines;
254 return new _DiffOp_Delete($this->closing
);
258 class _DiffOp_Change
extends _DiffOp
{
259 var $type = 'change';
261 function _DiffOp_Change ($orig, $closing) {
263 $this->closing
= $closing;
267 return new _DiffOp_Change($this->closing
, $this->orig
);
273 * Class used internally by Diff to actually compute the diffs.
275 * The algorithm used here is mostly lifted from the perl module
276 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
277 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
279 * More ideas are taken from:
280 * http://www.ics.uci.edu/~eppstein/161/960229.html
282 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
283 * diffutils-2.7, which can be found at:
284 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
286 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
289 * @author Geoffrey T. Dairiki
294 function diff ($from_lines, $to_lines) {
295 $n_from = sizeof($from_lines);
296 $n_to = sizeof($to_lines);
298 $this->xchanged
= $this->ychanged
= array();
299 $this->xv
= $this->yv
= array();
300 $this->xind
= $this->yind
= array();
302 unset($this->in_seq
);
305 // Skip leading common lines.
306 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
307 if ($from_lines[$skip] != $to_lines[$skip])
309 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
311 // Skip trailing common lines.
312 $xi = $n_from; $yi = $n_to;
313 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
314 if ($from_lines[$xi] != $to_lines[$yi])
316 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
319 // Ignore lines which do not exist in both files.
320 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
321 $xhash[$from_lines[$xi]] = 1;
322 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
323 $line = $to_lines[$yi];
324 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
330 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
331 $line = $from_lines[$xi];
332 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
339 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
341 // Merge edits when possible
342 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
343 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
345 // Compute the edit operations.
348 while ($xi < $n_from ||
$yi < $n_to) {
349 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
350 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
352 // Skip matching "snake".
354 while ( $xi < $n_from && $yi < $n_to
355 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
356 $copy[] = $from_lines[$xi++
];
360 $edits[] = new _DiffOp_Copy($copy);
362 // Find deletes & adds.
364 while ($xi < $n_from && $this->xchanged
[$xi])
365 $delete[] = $from_lines[$xi++
];
368 while ($yi < $n_to && $this->ychanged
[$yi])
369 $add[] = $to_lines[$yi++
];
372 $edits[] = new _DiffOp_Change($delete, $add);
374 $edits[] = new _DiffOp_Delete($delete);
376 $edits[] = new _DiffOp_Add($add);
382 /* Divide the Largest Common Subsequence (LCS) of the sequences
383 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
386 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
387 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
388 * sub sequences. The first sub-sequence is contained in [X0, X1),
389 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
390 * that (X0, Y0) == (XOFF, YOFF) and
391 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
393 * This function assumes that the first lines of the specified portions
394 * of the two files do not match, and likewise that the last lines do not
395 * match. The caller must trim matching lines from the beginning and end
396 * of the portions it is going to specify.
398 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
401 if ($xlim - $xoff > $ylim - $yoff) {
402 // Things seems faster (I'm not sure I understand why)
403 // when the shortest sequence in X.
405 list ($xoff, $xlim, $yoff, $ylim)
406 = array( $yoff, $ylim, $xoff, $xlim);
410 for ($i = $ylim - 1; $i >= $yoff; $i--)
411 $ymatches[$this->xv
[$i]][] = $i;
413 for ($i = $ylim - 1; $i >= $yoff; $i--)
414 $ymatches[$this->yv
[$i]][] = $i;
417 $this->seq
[0]= $yoff - 1;
418 $this->in_seq
= array();
421 $numer = $xlim - $xoff +
$nchunks - 1;
423 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
425 for ($i = 0; $i <= $this->lcs
; $i++
)
426 $ymids[$i][$chunk-1] = $this->seq
[$i];
428 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
429 for ( ; $x < $x1; $x++
) {
430 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
431 if (empty($ymatches[$line]))
433 $matches = $ymatches[$line];
435 while (list ($junk, $y) = each($matches))
436 if (empty($this->in_seq
[$y])) {
437 $k = $this->_lcs_pos($y);
438 USE_ASSERTS
&& assert($k > 0);
439 $ymids[$k] = $ymids[$k-1];
442 while (list ($junk, $y) = each($matches)) {
443 if ($y > $this->seq
[$k-1]) {
444 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
445 // Optimization: this is a common case:
446 // next match is just replacing previous match.
447 $this->in_seq
[$this->seq
[$k]] = false;
449 $this->in_seq
[$y] = 1;
451 else if (empty($this->in_seq
[$y])) {
452 $k = $this->_lcs_pos($y);
453 USE_ASSERTS
&& assert($k > 0);
454 $ymids[$k] = $ymids[$k-1];
460 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
461 $ymid = $ymids[$this->lcs
];
462 for ($n = 0; $n < $nchunks - 1; $n++
) {
463 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
465 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
467 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
469 return array($this->lcs
, $seps);
472 function _lcs_pos ($ypos) {
474 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
475 $this->seq
[++
$this->lcs
] = $ypos;
476 $this->in_seq
[$ypos] = 1;
481 while ($beg < $end) {
482 $mid = (int)(($beg +
$end) / 2);
483 if ( $ypos > $this->seq
[$mid] )
489 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
491 $this->in_seq
[$this->seq
[$end]] = false;
492 $this->seq
[$end] = $ypos;
493 $this->in_seq
[$ypos] = 1;
497 /* Find LCS of two sequences.
499 * The results are recorded in the vectors $this->{x,y}changed[], by
500 * storing a 1 in the element for each line that is an insertion
501 * or deletion (ie. is not in the LCS).
503 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
505 * Note that XLIM, YLIM are exclusive bounds.
506 * All line numbers are origin-0 and discarded lines are not counted.
508 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
509 // Slide down the bottom initial diagonal.
510 while ($xoff < $xlim && $yoff < $ylim
511 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
516 // Slide up the top initial diagonal.
517 while ($xlim > $xoff && $ylim > $yoff
518 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
523 if ($xoff == $xlim ||
$yoff == $ylim)
526 // This is ad hoc but seems to work well.
527 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
528 //$nchunks = max(2,min(8,(int)$nchunks));
529 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
531 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
535 // X and Y sequences have no common subsequence:
537 while ($yoff < $ylim)
538 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
539 while ($xoff < $xlim)
540 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
543 // Use the partitions to split this problem into subproblems.
546 while ($pt2 = next($seps)) {
547 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
553 /* Adjust inserts/deletes of identical lines to join changes
554 * as much as possible.
556 * We do something when a run of changed lines include a
557 * line at one end and has an excluded, identical line at the other.
558 * We are free to choose which identical line is included.
559 * `compareseq' usually chooses the one at the beginning,
560 * but usually it is cleaner to consider the following identical line
561 * to be the "change".
563 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
565 function _shift_boundaries ($lines, &$changed, $other_changed) {
569 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
570 $len = sizeof($lines);
571 $other_len = sizeof($other_changed);
575 * Scan forwards to find beginning of another run of changes.
576 * Also keep track of the corresponding point in the other file.
578 * Throughout this code, $i and $j are adjusted together so that
579 * the first $i elements of $changed and the first $j elements
580 * of $other_changed both contain the same number of zeros
582 * Furthermore, $j is always kept so that $j == $other_len or
583 * $other_changed[$j] == false.
585 while ($j < $other_len && $other_changed[$j])
588 while ($i < $len && ! $changed[$i]) {
589 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
591 while ($j < $other_len && $other_changed[$j])
600 // Find the end of this run of changes.
601 while (++
$i < $len && $changed[$i])
606 * Record the length of this run of changes, so that
607 * we can later determine whether the run has grown.
609 $runlength = $i - $start;
612 * Move the changed region back, so long as the
613 * previous unchanged line matches the last changed one.
614 * This merges with previous changed regions.
616 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
617 $changed[--$start] = 1;
618 $changed[--$i] = false;
619 while ($start > 0 && $changed[$start - 1])
621 USE_ASSERTS
&& assert('$j > 0');
622 while ($other_changed[--$j])
624 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
628 * Set CORRESPONDING to the end of the changed run, at the last
629 * point where it corresponds to a changed run in the other file.
630 * CORRESPONDING == LEN means no such point has been found.
632 $corresponding = $j < $other_len ?
$i : $len;
635 * Move the changed region forward, so long as the
636 * first changed line matches the following unchanged one.
637 * This merges with following changed regions.
638 * Do this second, so that if there are no merges,
639 * the changed region is moved forward as far as possible.
641 while ($i < $len && $lines[$start] == $lines[$i]) {
642 $changed[$start++
] = false;
644 while ($i < $len && $changed[$i])
647 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
649 if ($j < $other_len && $other_changed[$j]) {
651 while ($j < $other_len && $other_changed[$j])
655 } while ($runlength != $i - $start);
658 * If possible, move the fully-merged run of changes
659 * back to a corresponding run in the other file.
661 while ($corresponding < $i) {
662 $changed[--$start] = 1;
664 USE_ASSERTS
&& assert('$j > 0');
665 while ($other_changed[--$j])
667 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
674 * Class representing a 'diff' between two sequences of strings.
682 * Computes diff between sequences of strings.
684 * @param $from_lines array An array of strings.
685 * (Typically these are lines from a file.)
686 * @param $to_lines array An array of strings.
688 function Diff($from_lines, $to_lines) {
689 $eng = new _DiffEngine
;
690 $this->edits
= $eng->diff($from_lines, $to_lines);
691 //$this->_check($from_lines, $to_lines);
695 * Compute reversed Diff.
699 * $diff = new Diff($lines1, $lines2);
700 * $rev = $diff->reverse();
701 * @return object A Diff object representing the inverse of the
704 function reverse () {
706 $rev->edits
= array();
707 foreach ($this->edits
as $edit) {
708 $rev->edits
[] = $edit->reverse();
714 * Check for empty diff.
716 * @return bool True iff two sequences were identical.
718 function isEmpty () {
719 foreach ($this->edits
as $edit) {
720 if ($edit->type
!= 'copy')
727 * Compute the length of the Longest Common Subsequence (LCS).
729 * This is mostly for diagnostic purposed.
731 * @return int The length of the LCS.
735 foreach ($this->edits
as $edit) {
736 if ($edit->type
== 'copy')
737 $lcs +
= sizeof($edit->orig
);
743 * Get the original set of lines.
745 * This reconstructs the $from_lines parameter passed to the
748 * @return array The original sequence of strings.
753 foreach ($this->edits
as $edit) {
755 array_splice($lines, sizeof($lines), 0, $edit->orig
);
761 * Get the closing set of lines.
763 * This reconstructs the $to_lines parameter passed to the
766 * @return array The sequence of strings.
771 foreach ($this->edits
as $edit) {
773 array_splice($lines, sizeof($lines), 0, $edit->closing
);
779 * Check a Diff for validity.
781 * This is here only for debugging purposes.
783 function _check ($from_lines, $to_lines) {
784 if (serialize($from_lines) != serialize($this->orig()))
785 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
786 if (serialize($to_lines) != serialize($this->closing()))
787 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
789 $rev = $this->reverse();
790 if (serialize($to_lines) != serialize($rev->orig()))
791 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
792 if (serialize($from_lines) != serialize($rev->closing()))
793 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
797 foreach ($this->edits
as $edit) {
798 if ( $prevtype == $edit->type
)
799 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
800 $prevtype = $edit->type
;
804 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE
);
817 * Computes diff between sequences of strings.
819 * This can be used to compute things like
820 * case-insensitve diffs, or diffs which ignore
821 * changes in white-space.
823 * @param $from_lines array An array of strings.
824 * (Typically these are lines from a file.)
826 * @param $to_lines array An array of strings.
828 * @param $mapped_from_lines array This array should
829 * have the same size number of elements as $from_lines.
830 * The elements in $mapped_from_lines and
831 * $mapped_to_lines are what is actually compared
832 * when computing the diff.
834 * @param $mapped_to_lines array This array should
835 * have the same number of elements as $to_lines.
837 function MappedDiff($from_lines, $to_lines,
838 $mapped_from_lines, $mapped_to_lines) {
840 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
841 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
843 $this->Diff($mapped_from_lines, $mapped_to_lines);
846 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
847 $orig = &$this->edits
[$i]->orig
;
848 if (is_array($orig)) {
849 $orig = array_slice($from_lines, $xi, sizeof($orig));
850 $xi +
= sizeof($orig);
853 $closing = &$this->edits
[$i]->closing
;
854 if (is_array($closing)) {
855 $closing = array_slice($to_lines, $yi, sizeof($closing));
856 $yi +
= sizeof($closing);
863 * A class to format Diffs
865 * This class formats the diff in classic diff format.
866 * It is intended that this class be customized via inheritance,
867 * to obtain fancier outputs.
872 * Number of leading context "lines" to preserve.
874 * This should be left at zero for this class, but subclasses
875 * may want to set this to other values.
877 var $leading_context_lines = 0;
880 * Number of trailing context "lines" to preserve.
882 * This should be left at zero for this class, but subclasses
883 * may want to set this to other values.
885 var $trailing_context_lines = 0;
890 * @param $diff object A Diff object.
891 * @return string The formatted output.
893 function format($diff) {
899 $nlead = $this->leading_context_lines
;
900 $ntrail = $this->trailing_context_lines
;
902 $this->_start_diff();
904 foreach ($diff->edits
as $edit) {
905 if ($edit->type
== 'copy') {
906 if (is_array($block)) {
907 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
912 $context = array_slice($edit->orig
, 0, $ntrail);
913 $block[] = new _DiffOp_Copy($context);
915 $this->_block($x0, $ntrail +
$xi - $x0,
916 $y0, $ntrail +
$yi - $y0,
921 $context = $edit->orig
;
924 if (! is_array($block)) {
925 $context = array_slice($context, sizeof($context) - $nlead);
926 $x0 = $xi - sizeof($context);
927 $y0 = $yi - sizeof($context);
930 $block[] = new _DiffOp_Copy($context);
936 $xi +
= sizeof($edit->orig
);
938 $yi +
= sizeof($edit->closing
);
941 if (is_array($block))
942 $this->_block($x0, $xi - $x0,
946 return $this->_end_diff();
949 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
950 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
951 foreach ($edits as $edit) {
952 if ($edit->type
== 'copy')
953 $this->_context($edit->orig
);
954 elseif ($edit->type
== 'add')
955 $this->_added($edit->closing
);
956 elseif ($edit->type
== 'delete')
957 $this->_deleted($edit->orig
);
958 elseif ($edit->type
== 'change')
959 $this->_changed($edit->orig
, $edit->closing
);
961 trigger_error("Unknown edit type", E_USER_ERROR
);
966 function _start_diff() {
970 function _end_diff() {
971 $val = ob_get_contents();
976 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
978 $xbeg .= "," . ($xbeg +
$xlen - 1);
980 $ybeg .= "," . ($ybeg +
$ylen - 1);
982 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
985 function _start_block($header) {
989 function _end_block() {
992 function _lines($lines, $prefix = ' ') {
993 foreach ($lines as $line)
994 echo "$prefix $line\n";
997 function _context($lines) {
998 $this->_lines($lines);
1001 function _added($lines) {
1002 $this->_lines($lines, ">");
1004 function _deleted($lines) {
1005 $this->_lines($lines, "<");
1008 function _changed($orig, $closing) {
1009 $this->_deleted($orig);
1011 $this->_added($closing);
1017 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1021 define('NBSP', ' '); // iso-8859-x non-breaking space.
1023 class _HWLDF_WordAccumulator
{
1024 function _HWLDF_WordAccumulator () {
1025 $this->_lines
= array();
1031 function _flushGroup ($new_tag) {
1032 if ($this->_group
!== '') {
1033 if ($this->_tag
== 'mark')
1034 $this->_line
.= '<span class="diffchange">'.$this->_group
.'</span>';
1036 $this->_line
.= $this->_group
;
1039 $this->_tag
= $new_tag;
1042 function _flushLine ($new_tag) {
1043 $this->_flushGroup($new_tag);
1044 if ($this->_line
!= '')
1045 $this->_lines
[] = $this->_line
;
1049 function addWords ($words, $tag = '') {
1050 if ($tag != $this->_tag
)
1051 $this->_flushGroup($tag);
1053 foreach ($words as $word) {
1054 // new-line should only come as first char of word.
1057 if ($word[0] == "\n") {
1058 $this->_group
.= NBSP
;
1059 $this->_flushLine($tag);
1060 $word = substr($word, 1);
1062 assert(!strstr($word, "\n"));
1063 $this->_group
.= $word;
1067 function getLines() {
1068 $this->_flushLine('~done');
1069 return $this->_lines
;
1073 class WordLevelDiff
extends MappedDiff
1075 function WordLevelDiff ($orig_lines, $closing_lines) {
1076 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1077 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1080 $this->MappedDiff($orig_words, $closing_words,
1081 $orig_stripped, $closing_stripped);
1084 function _split($lines) {
1085 // FIXME: fix POSIX char class.
1086 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1087 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1088 implode("\n", $lines),
1090 return array(array(''), array(''));
1092 return array($m[0], $m[1]);
1096 $orig = new _HWLDF_WordAccumulator
;
1098 foreach ($this->edits
as $edit) {
1099 if ($edit->type
== 'copy')
1100 $orig->addWords($edit->orig
);
1101 elseif ($edit->orig
)
1102 $orig->addWords($edit->orig
, 'mark');
1104 return $orig->getLines();
1107 function closing () {
1108 $closing = new _HWLDF_WordAccumulator
;
1110 foreach ($this->edits
as $edit) {
1111 if ($edit->type
== 'copy')
1112 $closing->addWords($edit->closing
);
1113 elseif ($edit->closing
)
1114 $closing->addWords($edit->closing
, 'mark');
1116 return $closing->getLines();
1121 * Wikipedia Table style diff formatter.
1124 class TableDiffFormatter
extends DiffFormatter
1126 function TableDiffFormatter() {
1127 $this->leading_context_lines
= 2;
1128 $this->trailing_context_lines
= 2;
1131 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1132 $l1 = wfMsg( "lineno", $xbeg );
1133 $l2 = wfMsg( "lineno", $ybeg );
1135 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1136 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1140 function _start_block( $header ) {
1142 $wgOut->addHTML( $header );
1145 function _end_block() {
1148 function _lines( $lines, $prefix=' ', $color="white" ) {
1151 function addedLine( $line ) {
1152 return '<td>+</td><td class="diff-addedline">' .
1156 function deletedLine( $line ) {
1157 return '<td>-</td><td class="diff-deletedline">' .
1161 function emptyLine() {
1162 return '<td colspan="2"> </td>';
1165 function contextLine( $line ) {
1166 return '<td> </td><td class="diff-context">'.$line.'</td>';
1169 function _added($lines) {
1171 foreach ($lines as $line) {
1172 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1173 $this->addedLine( $line ) . "</tr>\n" );
1177 function _deleted($lines) {
1179 foreach ($lines as $line) {
1180 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1181 $this->emptyLine() . "</tr>\n" );
1185 function _context( $lines ) {
1187 foreach ($lines as $line) {
1188 $wgOut->addHTML( '<tr>' . $this->contextLine( $line ) .
1189 $this->contextLine( $line ) . "</tr>\n" );
1193 function _changed( $orig, $closing ) {
1195 $diff = new WordLevelDiff( $orig, $closing );
1196 $del = $diff->orig();
1197 $add = $diff->closing();
1199 while ( $line = array_shift( $del ) ) {
1200 $aline = array_shift( $add );
1201 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1202 $this->addedLine( $aline ) . "</tr>\n" );
1204 $this->_added( $add ); # If any leftovers