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 )
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'>
104 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
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).
121 global $wgTitle, $wgOut, $wgLang;
122 $fname = "DifferenceEngine::loadText";
124 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
125 $wgOut->setArticleFlag( true );
126 $this->mNewtitle
= wfMsg( "currentrev" );
127 $id = $wgTitle->getArticleID();
129 $sql = "SELECT cur_text, cur_user_text, cur_comment FROM cur WHERE cur_id={$id}";
130 $res = wfQuery( $sql, DB_READ
, $fname );
131 if ( 0 == wfNumRows( $res ) ) { return false; }
133 $s = wfFetchObject( $res );
134 $this->mNewPage
= &$wgTitle;
135 $this->mNewtext
= $s->cur_text
;
136 $this->mNewUser
= $s->cur_user_text
;
137 $this->mNewComment
= $s->cur_comment
;
139 $sql = "SELECT old_namespace,old_title,old_timestamp,old_text,old_flags,old_user_text,old_comment FROM old WHERE " .
140 "old_id={$this->mNewid}";
142 $res = wfQuery( $sql, DB_READ
, $fname );
143 if ( 0 == wfNumRows( $res ) ) { return false; }
145 $s = wfFetchObject( $res );
146 $this->mNewtext
= Article
::getRevisionText( $s );
148 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
149 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
150 $this->mNewtitle
= wfMsg( "revisionasof", $t );
151 $this->mNewUser
= $s->old_user_text
;
152 $this->mNewComment
= $s->old_comment
;
154 if ( 0 == $this->mOldid
) {
155 $sql = "SELECT old_namespace,old_title,old_timestamp,old_text,old_flags,old_user_text,old_comment " .
156 "FROM old USE INDEX (name_title_timestamp) WHERE " .
157 "old_namespace=" . $this->mNewPage
->getNamespace() . " AND " .
158 "old_title='" . wfStrencode( $this->mNewPage
->getDBkey() ) .
159 "' ORDER BY inverse_timestamp LIMIT 1";
160 $res = wfQuery( $sql, DB_READ
, $fname );
162 $sql = "SELECT old_namespace,old_title,old_timestamp,old_text,old_flags,old_user_text,old_comment FROM old WHERE " .
163 "old_id={$this->mOldid}";
164 $res = wfQuery( $sql, DB_READ
, $fname );
166 if ( 0 == wfNumRows( $res ) ) { return false; }
168 $s = wfFetchObject( $res );
169 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
170 $this->mOldtext
= Article
::getRevisionText( $s );
172 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
173 $this->mOldtitle
= wfMsg( "revisionasof", $t );
174 $this->mOldUser
= $s->old_user_text
;
175 $this->mOldComment
= $s->old_comment
;
181 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
183 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
184 // You may copy this code freely under the conditions of the GPL.
187 define('USE_ASSERTS', function_exists('assert'));
195 trigger_error("pure virtual", E_USER_ERROR
);
199 return $this->orig ?
sizeof($this->orig
) : 0;
202 function nclosing() {
203 return $this->closing ?
sizeof($this->closing
) : 0;
207 class _DiffOp_Copy
extends _DiffOp
{
210 function _DiffOp_Copy ($orig, $closing = false) {
211 if (!is_array($closing))
214 $this->closing
= $closing;
218 return new _DiffOp_Copy($this->closing
, $this->orig
);
222 class _DiffOp_Delete
extends _DiffOp
{
223 var $type = 'delete';
225 function _DiffOp_Delete ($lines) {
226 $this->orig
= $lines;
227 $this->closing
= false;
231 return new _DiffOp_Add($this->orig
);
235 class _DiffOp_Add
extends _DiffOp
{
238 function _DiffOp_Add ($lines) {
239 $this->closing
= $lines;
244 return new _DiffOp_Delete($this->closing
);
248 class _DiffOp_Change
extends _DiffOp
{
249 var $type = 'change';
251 function _DiffOp_Change ($orig, $closing) {
253 $this->closing
= $closing;
257 return new _DiffOp_Change($this->closing
, $this->orig
);
263 * Class used internally by Diff to actually compute the diffs.
265 * The algorithm used here is mostly lifted from the perl module
266 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
267 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
269 * More ideas are taken from:
270 * http://www.ics.uci.edu/~eppstein/161/960229.html
272 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
273 * diffutils-2.7, which can be found at:
274 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
276 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
279 * @author Geoffrey T. Dairiki
284 function diff ($from_lines, $to_lines) {
285 $n_from = sizeof($from_lines);
286 $n_to = sizeof($to_lines);
288 $this->xchanged
= $this->ychanged
= array();
289 $this->xv
= $this->yv
= array();
290 $this->xind
= $this->yind
= array();
292 unset($this->in_seq
);
295 // Skip leading common lines.
296 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
297 if ($from_lines[$skip] != $to_lines[$skip])
299 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
301 // Skip trailing common lines.
302 $xi = $n_from; $yi = $n_to;
303 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
304 if ($from_lines[$xi] != $to_lines[$yi])
306 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
309 // Ignore lines which do not exist in both files.
310 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
311 $xhash[$from_lines[$xi]] = 1;
312 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
313 $line = $to_lines[$yi];
314 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
320 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
321 $line = $from_lines[$xi];
322 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
329 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
331 // Merge edits when possible
332 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
333 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
335 // Compute the edit operations.
338 while ($xi < $n_from ||
$yi < $n_to) {
339 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
340 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
342 // Skip matching "snake".
344 while ( $xi < $n_from && $yi < $n_to
345 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
346 $copy[] = $from_lines[$xi++
];
350 $edits[] = new _DiffOp_Copy($copy);
352 // Find deletes & adds.
354 while ($xi < $n_from && $this->xchanged
[$xi])
355 $delete[] = $from_lines[$xi++
];
358 while ($yi < $n_to && $this->ychanged
[$yi])
359 $add[] = $to_lines[$yi++
];
362 $edits[] = new _DiffOp_Change($delete, $add);
364 $edits[] = new _DiffOp_Delete($delete);
366 $edits[] = new _DiffOp_Add($add);
372 /* Divide the Largest Common Subsequence (LCS) of the sequences
373 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
376 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
377 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
378 * sub sequences. The first sub-sequence is contained in [X0, X1),
379 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
380 * that (X0, Y0) == (XOFF, YOFF) and
381 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
383 * This function assumes that the first lines of the specified portions
384 * of the two files do not match, and likewise that the last lines do not
385 * match. The caller must trim matching lines from the beginning and end
386 * of the portions it is going to specify.
388 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
391 if ($xlim - $xoff > $ylim - $yoff) {
392 // Things seems faster (I'm not sure I understand why)
393 // when the shortest sequence in X.
395 list ($xoff, $xlim, $yoff, $ylim)
396 = array( $yoff, $ylim, $xoff, $xlim);
400 for ($i = $ylim - 1; $i >= $yoff; $i--)
401 $ymatches[$this->xv
[$i]][] = $i;
403 for ($i = $ylim - 1; $i >= $yoff; $i--)
404 $ymatches[$this->yv
[$i]][] = $i;
407 $this->seq
[0]= $yoff - 1;
408 $this->in_seq
= array();
411 $numer = $xlim - $xoff +
$nchunks - 1;
413 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
415 for ($i = 0; $i <= $this->lcs
; $i++
)
416 $ymids[$i][$chunk-1] = $this->seq
[$i];
418 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
419 for ( ; $x < $x1; $x++
) {
420 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
421 if (empty($ymatches[$line]))
423 $matches = $ymatches[$line];
425 while (list ($junk, $y) = each($matches))
426 if (empty($this->in_seq
[$y])) {
427 $k = $this->_lcs_pos($y);
428 USE_ASSERTS
&& assert($k > 0);
429 $ymids[$k] = $ymids[$k-1];
432 while (list ($junk, $y) = each($matches)) {
433 if ($y > $this->seq
[$k-1]) {
434 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
435 // Optimization: this is a common case:
436 // next match is just replacing previous match.
437 $this->in_seq
[$this->seq
[$k]] = false;
439 $this->in_seq
[$y] = 1;
441 else if (empty($this->in_seq
[$y])) {
442 $k = $this->_lcs_pos($y);
443 USE_ASSERTS
&& assert($k > 0);
444 $ymids[$k] = $ymids[$k-1];
450 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
451 $ymid = $ymids[$this->lcs
];
452 for ($n = 0; $n < $nchunks - 1; $n++
) {
453 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
455 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
457 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
459 return array($this->lcs
, $seps);
462 function _lcs_pos ($ypos) {
464 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
465 $this->seq
[++
$this->lcs
] = $ypos;
466 $this->in_seq
[$ypos] = 1;
471 while ($beg < $end) {
472 $mid = (int)(($beg +
$end) / 2);
473 if ( $ypos > $this->seq
[$mid] )
479 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
481 $this->in_seq
[$this->seq
[$end]] = false;
482 $this->seq
[$end] = $ypos;
483 $this->in_seq
[$ypos] = 1;
487 /* Find LCS of two sequences.
489 * The results are recorded in the vectors $this->{x,y}changed[], by
490 * storing a 1 in the element for each line that is an insertion
491 * or deletion (ie. is not in the LCS).
493 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
495 * Note that XLIM, YLIM are exclusive bounds.
496 * All line numbers are origin-0 and discarded lines are not counted.
498 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
499 // Slide down the bottom initial diagonal.
500 while ($xoff < $xlim && $yoff < $ylim
501 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
506 // Slide up the top initial diagonal.
507 while ($xlim > $xoff && $ylim > $yoff
508 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
513 if ($xoff == $xlim ||
$yoff == $ylim)
516 // This is ad hoc but seems to work well.
517 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
518 //$nchunks = max(2,min(8,(int)$nchunks));
519 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
521 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
525 // X and Y sequences have no common subsequence:
527 while ($yoff < $ylim)
528 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
529 while ($xoff < $xlim)
530 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
533 // Use the partitions to split this problem into subproblems.
536 while ($pt2 = next($seps)) {
537 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
543 /* Adjust inserts/deletes of identical lines to join changes
544 * as much as possible.
546 * We do something when a run of changed lines include a
547 * line at one end and has an excluded, identical line at the other.
548 * We are free to choose which identical line is included.
549 * `compareseq' usually chooses the one at the beginning,
550 * but usually it is cleaner to consider the following identical line
551 * to be the "change".
553 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
555 function _shift_boundaries ($lines, &$changed, $other_changed) {
559 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
560 $len = sizeof($lines);
561 $other_len = sizeof($other_changed);
565 * Scan forwards to find beginning of another run of changes.
566 * Also keep track of the corresponding point in the other file.
568 * Throughout this code, $i and $j are adjusted together so that
569 * the first $i elements of $changed and the first $j elements
570 * of $other_changed both contain the same number of zeros
572 * Furthermore, $j is always kept so that $j == $other_len or
573 * $other_changed[$j] == false.
575 while ($j < $other_len && $other_changed[$j])
578 while ($i < $len && ! $changed[$i]) {
579 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
581 while ($j < $other_len && $other_changed[$j])
590 // Find the end of this run of changes.
591 while (++
$i < $len && $changed[$i])
596 * Record the length of this run of changes, so that
597 * we can later determine whether the run has grown.
599 $runlength = $i - $start;
602 * Move the changed region back, so long as the
603 * previous unchanged line matches the last changed one.
604 * This merges with previous changed regions.
606 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
607 $changed[--$start] = 1;
608 $changed[--$i] = false;
609 while ($start > 0 && $changed[$start - 1])
611 USE_ASSERTS
&& assert('$j > 0');
612 while ($other_changed[--$j])
614 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
618 * Set CORRESPONDING to the end of the changed run, at the last
619 * point where it corresponds to a changed run in the other file.
620 * CORRESPONDING == LEN means no such point has been found.
622 $corresponding = $j < $other_len ?
$i : $len;
625 * Move the changed region forward, so long as the
626 * first changed line matches the following unchanged one.
627 * This merges with following changed regions.
628 * Do this second, so that if there are no merges,
629 * the changed region is moved forward as far as possible.
631 while ($i < $len && $lines[$start] == $lines[$i]) {
632 $changed[$start++
] = false;
634 while ($i < $len && $changed[$i])
637 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
639 if ($j < $other_len && $other_changed[$j]) {
641 while ($j < $other_len && $other_changed[$j])
645 } while ($runlength != $i - $start);
648 * If possible, move the fully-merged run of changes
649 * back to a corresponding run in the other file.
651 while ($corresponding < $i) {
652 $changed[--$start] = 1;
654 USE_ASSERTS
&& assert('$j > 0');
655 while ($other_changed[--$j])
657 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
664 * Class representing a 'diff' between two sequences of strings.
672 * Computes diff between sequences of strings.
674 * @param $from_lines array An array of strings.
675 * (Typically these are lines from a file.)
676 * @param $to_lines array An array of strings.
678 function Diff($from_lines, $to_lines) {
679 $eng = new _DiffEngine
;
680 $this->edits
= $eng->diff($from_lines, $to_lines);
681 //$this->_check($from_lines, $to_lines);
685 * Compute reversed Diff.
689 * $diff = new Diff($lines1, $lines2);
690 * $rev = $diff->reverse();
691 * @return object A Diff object representing the inverse of the
694 function reverse () {
696 $rev->edits
= array();
697 foreach ($this->edits
as $edit) {
698 $rev->edits
[] = $edit->reverse();
704 * Check for empty diff.
706 * @return bool True iff two sequences were identical.
708 function isEmpty () {
709 foreach ($this->edits
as $edit) {
710 if ($edit->type
!= 'copy')
717 * Compute the length of the Longest Common Subsequence (LCS).
719 * This is mostly for diagnostic purposed.
721 * @return int The length of the LCS.
725 foreach ($this->edits
as $edit) {
726 if ($edit->type
== 'copy')
727 $lcs +
= sizeof($edit->orig
);
733 * Get the original set of lines.
735 * This reconstructs the $from_lines parameter passed to the
738 * @return array The original sequence of strings.
743 foreach ($this->edits
as $edit) {
745 array_splice($lines, sizeof($lines), 0, $edit->orig
);
751 * Get the closing set of lines.
753 * This reconstructs the $to_lines parameter passed to the
756 * @return array The sequence of strings.
761 foreach ($this->edits
as $edit) {
763 array_splice($lines, sizeof($lines), 0, $edit->closing
);
769 * Check a Diff for validity.
771 * This is here only for debugging purposes.
773 function _check ($from_lines, $to_lines) {
774 if (serialize($from_lines) != serialize($this->orig()))
775 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
776 if (serialize($to_lines) != serialize($this->closing()))
777 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
779 $rev = $this->reverse();
780 if (serialize($to_lines) != serialize($rev->orig()))
781 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
782 if (serialize($from_lines) != serialize($rev->closing()))
783 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
787 foreach ($this->edits
as $edit) {
788 if ( $prevtype == $edit->type
)
789 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
790 $prevtype = $edit->type
;
794 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE
);
807 * Computes diff between sequences of strings.
809 * This can be used to compute things like
810 * case-insensitve diffs, or diffs which ignore
811 * changes in white-space.
813 * @param $from_lines array An array of strings.
814 * (Typically these are lines from a file.)
816 * @param $to_lines array An array of strings.
818 * @param $mapped_from_lines array This array should
819 * have the same size number of elements as $from_lines.
820 * The elements in $mapped_from_lines and
821 * $mapped_to_lines are what is actually compared
822 * when computing the diff.
824 * @param $mapped_to_lines array This array should
825 * have the same number of elements as $to_lines.
827 function MappedDiff($from_lines, $to_lines,
828 $mapped_from_lines, $mapped_to_lines) {
830 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
831 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
833 $this->Diff($mapped_from_lines, $mapped_to_lines);
836 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
837 $orig = &$this->edits
[$i]->orig
;
838 if (is_array($orig)) {
839 $orig = array_slice($from_lines, $xi, sizeof($orig));
840 $xi +
= sizeof($orig);
843 $closing = &$this->edits
[$i]->closing
;
844 if (is_array($closing)) {
845 $closing = array_slice($to_lines, $yi, sizeof($closing));
846 $yi +
= sizeof($closing);
853 * A class to format Diffs
855 * This class formats the diff in classic diff format.
856 * It is intended that this class be customized via inheritance,
857 * to obtain fancier outputs.
862 * Number of leading context "lines" to preserve.
864 * This should be left at zero for this class, but subclasses
865 * may want to set this to other values.
867 var $leading_context_lines = 0;
870 * Number of trailing context "lines" to preserve.
872 * This should be left at zero for this class, but subclasses
873 * may want to set this to other values.
875 var $trailing_context_lines = 0;
880 * @param $diff object A Diff object.
881 * @return string The formatted output.
883 function format($diff) {
889 $nlead = $this->leading_context_lines
;
890 $ntrail = $this->trailing_context_lines
;
892 $this->_start_diff();
894 foreach ($diff->edits
as $edit) {
895 if ($edit->type
== 'copy') {
896 if (is_array($block)) {
897 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
902 $context = array_slice($edit->orig
, 0, $ntrail);
903 $block[] = new _DiffOp_Copy($context);
905 $this->_block($x0, $ntrail +
$xi - $x0,
906 $y0, $ntrail +
$yi - $y0,
911 $context = $edit->orig
;
914 if (! is_array($block)) {
915 $context = array_slice($context, sizeof($context) - $nlead);
916 $x0 = $xi - sizeof($context);
917 $y0 = $yi - sizeof($context);
920 $block[] = new _DiffOp_Copy($context);
926 $xi +
= sizeof($edit->orig
);
928 $yi +
= sizeof($edit->closing
);
931 if (is_array($block))
932 $this->_block($x0, $xi - $x0,
936 return $this->_end_diff();
939 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
940 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
941 foreach ($edits as $edit) {
942 if ($edit->type
== 'copy')
943 $this->_context($edit->orig
);
944 elseif ($edit->type
== 'add')
945 $this->_added($edit->closing
);
946 elseif ($edit->type
== 'delete')
947 $this->_deleted($edit->orig
);
948 elseif ($edit->type
== 'change')
949 $this->_changed($edit->orig
, $edit->closing
);
951 trigger_error("Unknown edit type", E_USER_ERROR
);
956 function _start_diff() {
960 function _end_diff() {
961 $val = ob_get_contents();
966 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
968 $xbeg .= "," . ($xbeg +
$xlen - 1);
970 $ybeg .= "," . ($ybeg +
$ylen - 1);
972 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
975 function _start_block($header) {
979 function _end_block() {
982 function _lines($lines, $prefix = ' ') {
983 foreach ($lines as $line)
984 echo "$prefix $line\n";
987 function _context($lines) {
988 $this->_lines($lines);
991 function _added($lines) {
992 $this->_lines($lines, ">");
994 function _deleted($lines) {
995 $this->_lines($lines, "<");
998 function _changed($orig, $closing) {
999 $this->_deleted($orig);
1001 $this->_added($closing);
1007 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1011 define('NBSP', "\xA0"); // iso-8859-x non-breaking space.
1013 class _HWLDF_WordAccumulator
{
1014 function _HWLDF_WordAccumulator () {
1015 $this->_lines
= array();
1021 function _flushGroup ($new_tag) {
1022 if ($this->_group
!== '') {
1023 if ($this->_tag
== 'mark')
1024 $this->_line
.= "<font color=\"red\">$this->_group</font>";
1026 $this->_line
.= $this->_group
;
1029 $this->_tag
= $new_tag;
1032 function _flushLine ($new_tag) {
1033 $this->_flushGroup($new_tag);
1034 if ($this->_line
!= '')
1035 $this->_lines
[] = $this->_line
;
1039 function addWords ($words, $tag = '') {
1040 if ($tag != $this->_tag
)
1041 $this->_flushGroup($tag);
1043 foreach ($words as $word) {
1044 // new-line should only come as first char of word.
1047 if ($word[0] == "\n") {
1048 $this->_group
.= NBSP
;
1049 $this->_flushLine($tag);
1050 $word = substr($word, 1);
1052 assert(!strstr($word, "\n"));
1053 $this->_group
.= $word;
1057 function getLines() {
1058 $this->_flushLine('~done');
1059 return $this->_lines
;
1063 class WordLevelDiff
extends MappedDiff
1065 function WordLevelDiff ($orig_lines, $closing_lines) {
1066 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1067 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1070 $this->MappedDiff($orig_words, $closing_words,
1071 $orig_stripped, $closing_stripped);
1074 function _split($lines) {
1075 // FIXME: fix POSIX char class.
1076 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1077 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1078 implode("\n", $lines),
1080 return array(array(''), array(''));
1082 return array($m[0], $m[1]);
1086 $orig = new _HWLDF_WordAccumulator
;
1088 foreach ($this->edits
as $edit) {
1089 if ($edit->type
== 'copy')
1090 $orig->addWords($edit->orig
);
1091 elseif ($edit->orig
)
1092 $orig->addWords($edit->orig
, 'mark');
1094 return $orig->getLines();
1097 function closing () {
1098 $closing = new _HWLDF_WordAccumulator
;
1100 foreach ($this->edits
as $edit) {
1101 if ($edit->type
== 'copy')
1102 $closing->addWords($edit->closing
);
1103 elseif ($edit->closing
)
1104 $closing->addWords($edit->closing
, 'mark');
1106 return $closing->getLines();
1111 * Wikipedia Table style diff formatter.
1114 class TableDiffFormatter
extends DiffFormatter
1116 function TableDiffFormatter() {
1117 $this->leading_context_lines
= 2;
1118 $this->trailing_context_lines
= 2;
1121 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1122 $l1 = wfMsg( "lineno", $xbeg );
1123 $l2 = wfMsg( "lineno", $ybeg );
1125 $r = "<tr><td colspan='2' align='left'><strong>{$l1}</strong></td>\n" .
1126 "<td colspan='2' align='left'><strong>{$l2}</strong></td></tr>\n";
1130 function _start_block( $header ) {
1132 $wgOut->addHTML( $header );
1135 function _end_block() {
1138 function _lines( $lines, $prefix=' ', $color="white" ) {
1141 function addedLine( $line ) {
1142 return "<td>+</td><td class='diff-addedline'>" .
1143 "<small>{$line}</small></td>";
1146 function deletedLine( $line ) {
1147 return "<td>-</td><td class='diff-deletedline'>" .
1148 "<small>{$line}</small></td>";
1151 function emptyLine() {
1152 return "<td colspan='2'> </td>";
1155 function contextLine( $line ) {
1156 return "<td> </td><td class='diff-context'><small>{$line}</small></td>";
1159 function _added($lines) {
1161 foreach ($lines as $line) {
1162 $wgOut->addHTML( "<tr>" . $this->emptyLine() .
1163 $this->addedLine( $line ) . "</tr>\n" );
1167 function _deleted($lines) {
1169 foreach ($lines as $line) {
1170 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1171 $this->emptyLine() . "</tr>\n" );
1175 function _context( $lines ) {
1177 foreach ($lines as $line) {
1178 $wgOut->addHTML( "<tr>" . $this->contextLine( $line ) .
1179 $this->contextLine( $line ) . "</tr>\n" );
1183 function _changed( $orig, $closing ) {
1185 $diff = new WordLevelDiff( $orig, $closing );
1186 $del = $diff->orig();
1187 $add = $diff->closing();
1189 while ( $line = array_shift( $del ) ) {
1190 $aline = array_shift( $add );
1191 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1192 $this->addedLine( $aline ) . "</tr>\n" );
1194 $this->_added( $add ); # If any leftovers