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;
11 function DifferenceEngine( $old, $new )
17 function showDiffPage()
19 global $wgUser, $wgTitle, $wgOut, $wgLang;
21 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
23 $mtext = wfMsg( "missingarticle", $t );
25 $wgOut->setArticleFlag( false );
26 if ( ! $this->loadText() ) {
27 $wgOut->setPagetitle( wfMsg( "errorpagetitle" ) );
28 $wgOut->addHTML( $mtext );
31 $wgOut->suppressQuickbar();
32 $wgOut->setSubtitle( wfMsg( "difference" ) );
33 $wgOut->setRobotpolicy( "noindex,follow" );
35 $sk = $wgUser->getSkin();
36 $talk = $wgLang->getNsText( NS_TALK
);
37 $contribs = wfMsg( "contribslink" );
40 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
41 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
44 $oldUserLink = $sk->makeLinkObj( Title
::makeTitle( NS_USER
, $this->mOldUser
), $this->mOldUser
);
45 $newUserLink = $sk->makeLinkObj( Title
::makeTitle( NS_USER
, $this->mNewUser
), $this->mNewUser
);
46 $oldUTLink = $sk->makeLinkObj( Title
::makeTitle( NS_USER_TALK
, $this->mOldUser
), $talk );
47 $newUTLink = $sk->makeLinkObj( Title
::makeTitle( NS_USER_TALK
, $this->mNewUser
), $talk );
48 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, "Contributions" ), $contribs,
49 "target=" . urlencode($this->mOldUser
) );
50 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, "Contributions" ), $contribs,
51 "target=" . urlencode($this->mNewUser
) );
52 if ( !$this->mNewid
&& $wgUser->isSysop() ) {
53 $rollback = " <strong>[" . $sk->makeKnownLinkObj( $wgTitle, wfMsg( "rollbacklink" ),
54 "action=rollback&from=" . urlencode($this->mNewUser
) ) . "]</strong>";
59 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink ($oldUTLink | $oldContribs)<br />".
61 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink ($newUTLink | $newContribs) $rollback<br />".
64 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
65 $oldHeader, $newHeader );
66 $wgOut->addHTML( "<hr /><h2>{$this->mNewtitle}</h2>\n" );
67 $wgOut->addWikiText( $this->mNewtext
);
70 function showDiff( $otext, $ntext, $otitle, $ntitle )
74 $ota = explode( "\n", str_replace( "\r\n", "\n",
75 htmlspecialchars( $otext ) ) );
76 $nta = explode( "\n", str_replace( "\r\n", "\n",
77 htmlspecialchars( $ntext ) ) );
79 $wgOut->addHTML( "<table border='0' width='98%'
80 cellpadding='0' cellspacing='4px' class='diff'><tr>
81 <td colspan='2' width='50%' align='center' class='diff-otitle'>
83 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
87 $diffs = new Diff( $ota, $nta );
88 $formatter = new TableDiffFormatter();
89 $formatter->format( $diffs );
90 $wgOut->addHTML( "</table>\n" );
93 # Load the text of the articles to compare. If newid is 0, then compare
94 # the old article in oldid to the current article; if oldid is 0, then
95 # compare the current article to the immediately previous one (ignoring
96 # the value of newid).
100 global $wgTitle, $wgOut, $wgLang;
101 $fname = "DifferenceEngine::loadText";
103 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
104 $wgOut->setArticleFlag( true );
105 $this->mNewtitle
= wfMsg( "currentrev" );
106 $id = $wgTitle->getArticleID();
108 $sql = "SELECT cur_text, cur_user_text, cur_comment FROM cur WHERE cur_id={$id}";
109 $res = wfQuery( $sql, DB_READ
, $fname );
110 if ( 0 == wfNumRows( $res ) ) { return false; }
112 $s = wfFetchObject( $res );
113 $this->mNewtext
= $s->cur_text
;
114 $this->mNewUser
= $s->cur_user_text
;
115 $this->mNewComment
= $s->cur_comment
;
117 $sql = "SELECT old_timestamp,old_text,old_flags,old_user_text,old_comment FROM old WHERE " .
118 "old_id={$this->mNewid}";
120 $res = wfQuery( $sql, DB_READ
, $fname );
121 if ( 0 == wfNumRows( $res ) ) { return false; }
123 $s = wfFetchObject( $res );
124 $this->mNewtext
= Article
::getRevisionText( $s );
126 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
127 $this->mNewtitle
= wfMsg( "revisionasof", $t );
128 $this->mNewUser
= $s->old_user_text
;
129 $this->mNewComment
= $s->old_comment
;
131 if ( 0 == $this->mOldid
) {
132 $sql = "SELECT old_timestamp,old_text,old_flags,old_user_text,old_comment " .
133 "FROM old USE INDEX (name_title_timestamp) WHERE " .
134 "old_namespace=" . $wgTitle->getNamespace() . " AND " .
135 "old_title='" . wfStrencode( $wgTitle->getDBkey() ) .
136 "' ORDER BY inverse_timestamp LIMIT 1";
137 $res = wfQuery( $sql, DB_READ
, $fname );
139 $sql = "SELECT old_timestamp,old_text,old_flags,old_user_text,old_comment FROM old WHERE " .
140 "old_id={$this->mOldid}";
141 $res = wfQuery( $sql, DB_READ
, $fname );
143 if ( 0 == wfNumRows( $res ) ) { return false; }
145 $s = wfFetchObject( $res );
146 $this->mOldtext
= Article
::getRevisionText( $s );
148 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
149 $this->mOldtitle
= wfMsg( "revisionasof", $t );
150 $this->mOldUser
= $s->old_user_text
;
151 $this->mOldComment
= $s->old_comment
;
157 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
159 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
160 // You may copy this code freely under the conditions of the GPL.
163 define('USE_ASSERTS', function_exists('assert'));
171 trigger_error("pure virtual", E_USER_ERROR
);
175 return $this->orig ?
sizeof($this->orig
) : 0;
178 function nclosing() {
179 return $this->closing ?
sizeof($this->closing
) : 0;
183 class _DiffOp_Copy
extends _DiffOp
{
186 function _DiffOp_Copy ($orig, $closing = false) {
187 if (!is_array($closing))
190 $this->closing
= $closing;
194 return new _DiffOp_Copy($this->closing
, $this->orig
);
198 class _DiffOp_Delete
extends _DiffOp
{
199 var $type = 'delete';
201 function _DiffOp_Delete ($lines) {
202 $this->orig
= $lines;
203 $this->closing
= false;
207 return new _DiffOp_Add($this->orig
);
211 class _DiffOp_Add
extends _DiffOp
{
214 function _DiffOp_Add ($lines) {
215 $this->closing
= $lines;
220 return new _DiffOp_Delete($this->closing
);
224 class _DiffOp_Change
extends _DiffOp
{
225 var $type = 'change';
227 function _DiffOp_Change ($orig, $closing) {
229 $this->closing
= $closing;
233 return new _DiffOp_Change($this->closing
, $this->orig
);
239 * Class used internally by Diff to actually compute the diffs.
241 * The algorithm used here is mostly lifted from the perl module
242 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
243 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
245 * More ideas are taken from:
246 * http://www.ics.uci.edu/~eppstein/161/960229.html
248 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
249 * diffutils-2.7, which can be found at:
250 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
252 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
255 * @author Geoffrey T. Dairiki
260 function diff ($from_lines, $to_lines) {
261 $n_from = sizeof($from_lines);
262 $n_to = sizeof($to_lines);
264 $this->xchanged
= $this->ychanged
= array();
265 $this->xv
= $this->yv
= array();
266 $this->xind
= $this->yind
= array();
268 unset($this->in_seq
);
271 // Skip leading common lines.
272 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
273 if ($from_lines[$skip] != $to_lines[$skip])
275 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
277 // Skip trailing common lines.
278 $xi = $n_from; $yi = $n_to;
279 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
280 if ($from_lines[$xi] != $to_lines[$yi])
282 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
285 // Ignore lines which do not exist in both files.
286 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
287 $xhash[$from_lines[$xi]] = 1;
288 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
289 $line = $to_lines[$yi];
290 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
296 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
297 $line = $from_lines[$xi];
298 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
305 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
307 // Merge edits when possible
308 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
309 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
311 // Compute the edit operations.
314 while ($xi < $n_from ||
$yi < $n_to) {
315 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
316 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
318 // Skip matching "snake".
320 while ( $xi < $n_from && $yi < $n_to
321 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
322 $copy[] = $from_lines[$xi++
];
326 $edits[] = new _DiffOp_Copy($copy);
328 // Find deletes & adds.
330 while ($xi < $n_from && $this->xchanged
[$xi])
331 $delete[] = $from_lines[$xi++
];
334 while ($yi < $n_to && $this->ychanged
[$yi])
335 $add[] = $to_lines[$yi++
];
338 $edits[] = new _DiffOp_Change($delete, $add);
340 $edits[] = new _DiffOp_Delete($delete);
342 $edits[] = new _DiffOp_Add($add);
348 /* Divide the Largest Common Subsequence (LCS) of the sequences
349 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
352 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
353 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
354 * sub sequences. The first sub-sequence is contained in [X0, X1),
355 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
356 * that (X0, Y0) == (XOFF, YOFF) and
357 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
359 * This function assumes that the first lines of the specified portions
360 * of the two files do not match, and likewise that the last lines do not
361 * match. The caller must trim matching lines from the beginning and end
362 * of the portions it is going to specify.
364 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
367 if ($xlim - $xoff > $ylim - $yoff) {
368 // Things seems faster (I'm not sure I understand why)
369 // when the shortest sequence in X.
371 list ($xoff, $xlim, $yoff, $ylim)
372 = array( $yoff, $ylim, $xoff, $xlim);
376 for ($i = $ylim - 1; $i >= $yoff; $i--)
377 $ymatches[$this->xv
[$i]][] = $i;
379 for ($i = $ylim - 1; $i >= $yoff; $i--)
380 $ymatches[$this->yv
[$i]][] = $i;
383 $this->seq
[0]= $yoff - 1;
384 $this->in_seq
= array();
387 $numer = $xlim - $xoff +
$nchunks - 1;
389 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
391 for ($i = 0; $i <= $this->lcs
; $i++
)
392 $ymids[$i][$chunk-1] = $this->seq
[$i];
394 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
395 for ( ; $x < $x1; $x++
) {
396 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
397 if (empty($ymatches[$line]))
399 $matches = $ymatches[$line];
401 while (list ($junk, $y) = each($matches))
402 if (empty($this->in_seq
[$y])) {
403 $k = $this->_lcs_pos($y);
404 USE_ASSERTS
&& assert($k > 0);
405 $ymids[$k] = $ymids[$k-1];
408 while (list ($junk, $y) = each($matches)) {
409 if ($y > $this->seq
[$k-1]) {
410 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
411 // Optimization: this is a common case:
412 // next match is just replacing previous match.
413 $this->in_seq
[$this->seq
[$k]] = false;
415 $this->in_seq
[$y] = 1;
417 else if (empty($this->in_seq
[$y])) {
418 $k = $this->_lcs_pos($y);
419 USE_ASSERTS
&& assert($k > 0);
420 $ymids[$k] = $ymids[$k-1];
426 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
427 $ymid = $ymids[$this->lcs
];
428 for ($n = 0; $n < $nchunks - 1; $n++
) {
429 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
431 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
433 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
435 return array($this->lcs
, $seps);
438 function _lcs_pos ($ypos) {
440 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
441 $this->seq
[++
$this->lcs
] = $ypos;
442 $this->in_seq
[$ypos] = 1;
447 while ($beg < $end) {
448 $mid = (int)(($beg +
$end) / 2);
449 if ( $ypos > $this->seq
[$mid] )
455 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
457 $this->in_seq
[$this->seq
[$end]] = false;
458 $this->seq
[$end] = $ypos;
459 $this->in_seq
[$ypos] = 1;
463 /* Find LCS of two sequences.
465 * The results are recorded in the vectors $this->{x,y}changed[], by
466 * storing a 1 in the element for each line that is an insertion
467 * or deletion (ie. is not in the LCS).
469 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
471 * Note that XLIM, YLIM are exclusive bounds.
472 * All line numbers are origin-0 and discarded lines are not counted.
474 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
475 // Slide down the bottom initial diagonal.
476 while ($xoff < $xlim && $yoff < $ylim
477 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
482 // Slide up the top initial diagonal.
483 while ($xlim > $xoff && $ylim > $yoff
484 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
489 if ($xoff == $xlim ||
$yoff == $ylim)
492 // This is ad hoc but seems to work well.
493 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
494 //$nchunks = max(2,min(8,(int)$nchunks));
495 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
497 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
501 // X and Y sequences have no common subsequence:
503 while ($yoff < $ylim)
504 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
505 while ($xoff < $xlim)
506 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
509 // Use the partitions to split this problem into subproblems.
512 while ($pt2 = next($seps)) {
513 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
519 /* Adjust inserts/deletes of identical lines to join changes
520 * as much as possible.
522 * We do something when a run of changed lines include a
523 * line at one end and has an excluded, identical line at the other.
524 * We are free to choose which identical line is included.
525 * `compareseq' usually chooses the one at the beginning,
526 * but usually it is cleaner to consider the following identical line
527 * to be the "change".
529 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
531 function _shift_boundaries ($lines, &$changed, $other_changed) {
535 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
536 $len = sizeof($lines);
537 $other_len = sizeof($other_changed);
541 * Scan forwards to find beginning of another run of changes.
542 * Also keep track of the corresponding point in the other file.
544 * Throughout this code, $i and $j are adjusted together so that
545 * the first $i elements of $changed and the first $j elements
546 * of $other_changed both contain the same number of zeros
548 * Furthermore, $j is always kept so that $j == $other_len or
549 * $other_changed[$j] == false.
551 while ($j < $other_len && $other_changed[$j])
554 while ($i < $len && ! $changed[$i]) {
555 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
557 while ($j < $other_len && $other_changed[$j])
566 // Find the end of this run of changes.
567 while (++
$i < $len && $changed[$i])
572 * Record the length of this run of changes, so that
573 * we can later determine whether the run has grown.
575 $runlength = $i - $start;
578 * Move the changed region back, so long as the
579 * previous unchanged line matches the last changed one.
580 * This merges with previous changed regions.
582 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
583 $changed[--$start] = 1;
584 $changed[--$i] = false;
585 while ($start > 0 && $changed[$start - 1])
587 USE_ASSERTS
&& assert('$j > 0');
588 while ($other_changed[--$j])
590 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
594 * Set CORRESPONDING to the end of the changed run, at the last
595 * point where it corresponds to a changed run in the other file.
596 * CORRESPONDING == LEN means no such point has been found.
598 $corresponding = $j < $other_len ?
$i : $len;
601 * Move the changed region forward, so long as the
602 * first changed line matches the following unchanged one.
603 * This merges with following changed regions.
604 * Do this second, so that if there are no merges,
605 * the changed region is moved forward as far as possible.
607 while ($i < $len && $lines[$start] == $lines[$i]) {
608 $changed[$start++
] = false;
610 while ($i < $len && $changed[$i])
613 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
615 if ($j < $other_len && $other_changed[$j]) {
617 while ($j < $other_len && $other_changed[$j])
621 } while ($runlength != $i - $start);
624 * If possible, move the fully-merged run of changes
625 * back to a corresponding run in the other file.
627 while ($corresponding < $i) {
628 $changed[--$start] = 1;
630 USE_ASSERTS
&& assert('$j > 0');
631 while ($other_changed[--$j])
633 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
640 * Class representing a 'diff' between two sequences of strings.
648 * Computes diff between sequences of strings.
650 * @param $from_lines array An array of strings.
651 * (Typically these are lines from a file.)
652 * @param $to_lines array An array of strings.
654 function Diff($from_lines, $to_lines) {
655 $eng = new _DiffEngine
;
656 $this->edits
= $eng->diff($from_lines, $to_lines);
657 //$this->_check($from_lines, $to_lines);
661 * Compute reversed Diff.
665 * $diff = new Diff($lines1, $lines2);
666 * $rev = $diff->reverse();
667 * @return object A Diff object representing the inverse of the
670 function reverse () {
672 $rev->edits
= array();
673 foreach ($this->edits
as $edit) {
674 $rev->edits
[] = $edit->reverse();
680 * Check for empty diff.
682 * @return bool True iff two sequences were identical.
684 function isEmpty () {
685 foreach ($this->edits
as $edit) {
686 if ($edit->type
!= 'copy')
693 * Compute the length of the Longest Common Subsequence (LCS).
695 * This is mostly for diagnostic purposed.
697 * @return int The length of the LCS.
701 foreach ($this->edits
as $edit) {
702 if ($edit->type
== 'copy')
703 $lcs +
= sizeof($edit->orig
);
709 * Get the original set of lines.
711 * This reconstructs the $from_lines parameter passed to the
714 * @return array The original sequence of strings.
719 foreach ($this->edits
as $edit) {
721 array_splice($lines, sizeof($lines), 0, $edit->orig
);
727 * Get the closing set of lines.
729 * This reconstructs the $to_lines parameter passed to the
732 * @return array The sequence of strings.
737 foreach ($this->edits
as $edit) {
739 array_splice($lines, sizeof($lines), 0, $edit->closing
);
745 * Check a Diff for validity.
747 * This is here only for debugging purposes.
749 function _check ($from_lines, $to_lines) {
750 if (serialize($from_lines) != serialize($this->orig()))
751 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
752 if (serialize($to_lines) != serialize($this->closing()))
753 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
755 $rev = $this->reverse();
756 if (serialize($to_lines) != serialize($rev->orig()))
757 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
758 if (serialize($from_lines) != serialize($rev->closing()))
759 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
763 foreach ($this->edits
as $edit) {
764 if ( $prevtype == $edit->type
)
765 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
766 $prevtype = $edit->type
;
770 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE
);
783 * Computes diff between sequences of strings.
785 * This can be used to compute things like
786 * case-insensitve diffs, or diffs which ignore
787 * changes in white-space.
789 * @param $from_lines array An array of strings.
790 * (Typically these are lines from a file.)
792 * @param $to_lines array An array of strings.
794 * @param $mapped_from_lines array This array should
795 * have the same size number of elements as $from_lines.
796 * The elements in $mapped_from_lines and
797 * $mapped_to_lines are what is actually compared
798 * when computing the diff.
800 * @param $mapped_to_lines array This array should
801 * have the same number of elements as $to_lines.
803 function MappedDiff($from_lines, $to_lines,
804 $mapped_from_lines, $mapped_to_lines) {
806 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
807 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
809 $this->Diff($mapped_from_lines, $mapped_to_lines);
812 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
813 $orig = &$this->edits
[$i]->orig
;
814 if (is_array($orig)) {
815 $orig = array_slice($from_lines, $xi, sizeof($orig));
816 $xi +
= sizeof($orig);
819 $closing = &$this->edits
[$i]->closing
;
820 if (is_array($closing)) {
821 $closing = array_slice($to_lines, $yi, sizeof($closing));
822 $yi +
= sizeof($closing);
829 * A class to format Diffs
831 * This class formats the diff in classic diff format.
832 * It is intended that this class be customized via inheritance,
833 * to obtain fancier outputs.
838 * Number of leading context "lines" to preserve.
840 * This should be left at zero for this class, but subclasses
841 * may want to set this to other values.
843 var $leading_context_lines = 0;
846 * Number of trailing context "lines" to preserve.
848 * This should be left at zero for this class, but subclasses
849 * may want to set this to other values.
851 var $trailing_context_lines = 0;
856 * @param $diff object A Diff object.
857 * @return string The formatted output.
859 function format($diff) {
865 $nlead = $this->leading_context_lines
;
866 $ntrail = $this->trailing_context_lines
;
868 $this->_start_diff();
870 foreach ($diff->edits
as $edit) {
871 if ($edit->type
== 'copy') {
872 if (is_array($block)) {
873 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
878 $context = array_slice($edit->orig
, 0, $ntrail);
879 $block[] = new _DiffOp_Copy($context);
881 $this->_block($x0, $ntrail +
$xi - $x0,
882 $y0, $ntrail +
$yi - $y0,
887 $context = $edit->orig
;
890 if (! is_array($block)) {
891 $context = array_slice($context, sizeof($context) - $nlead);
892 $x0 = $xi - sizeof($context);
893 $y0 = $yi - sizeof($context);
896 $block[] = new _DiffOp_Copy($context);
902 $xi +
= sizeof($edit->orig
);
904 $yi +
= sizeof($edit->closing
);
907 if (is_array($block))
908 $this->_block($x0, $xi - $x0,
912 return $this->_end_diff();
915 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
916 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
917 foreach ($edits as $edit) {
918 if ($edit->type
== 'copy')
919 $this->_context($edit->orig
);
920 elseif ($edit->type
== 'add')
921 $this->_added($edit->closing
);
922 elseif ($edit->type
== 'delete')
923 $this->_deleted($edit->orig
);
924 elseif ($edit->type
== 'change')
925 $this->_changed($edit->orig
, $edit->closing
);
927 trigger_error("Unknown edit type", E_USER_ERROR
);
932 function _start_diff() {
936 function _end_diff() {
937 $val = ob_get_contents();
942 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
944 $xbeg .= "," . ($xbeg +
$xlen - 1);
946 $ybeg .= "," . ($ybeg +
$ylen - 1);
948 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
951 function _start_block($header) {
955 function _end_block() {
958 function _lines($lines, $prefix = ' ') {
959 foreach ($lines as $line)
960 echo "$prefix $line\n";
963 function _context($lines) {
964 $this->_lines($lines);
967 function _added($lines) {
968 $this->_lines($lines, ">");
970 function _deleted($lines) {
971 $this->_lines($lines, "<");
974 function _changed($orig, $closing) {
975 $this->_deleted($orig);
977 $this->_added($closing);
983 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
987 define('NBSP', "\xA0"); // iso-8859-x non-breaking space.
989 class _HWLDF_WordAccumulator
{
990 function _HWLDF_WordAccumulator () {
991 $this->_lines
= array();
997 function _flushGroup ($new_tag) {
998 if ($this->_group
!== '') {
999 if ($this->_tag
== 'mark')
1000 $this->_line
.= "<font color=\"red\">$this->_group</font>";
1002 $this->_line
.= $this->_group
;
1005 $this->_tag
= $new_tag;
1008 function _flushLine ($new_tag) {
1009 $this->_flushGroup($new_tag);
1010 if ($this->_line
!= '')
1011 $this->_lines
[] = $this->_line
;
1015 function addWords ($words, $tag = '') {
1016 if ($tag != $this->_tag
)
1017 $this->_flushGroup($tag);
1019 foreach ($words as $word) {
1020 // new-line should only come as first char of word.
1023 if ($word[0] == "\n") {
1024 $this->_group
.= NBSP
;
1025 $this->_flushLine($tag);
1026 $word = substr($word, 1);
1028 assert(!strstr($word, "\n"));
1029 $this->_group
.= $word;
1033 function getLines() {
1034 $this->_flushLine('~done');
1035 return $this->_lines
;
1039 class WordLevelDiff
extends MappedDiff
1041 function WordLevelDiff ($orig_lines, $closing_lines) {
1042 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1043 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1046 $this->MappedDiff($orig_words, $closing_words,
1047 $orig_stripped, $closing_stripped);
1050 function _split($lines) {
1051 // FIXME: fix POSIX char class.
1052 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1053 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1054 implode("\n", $lines),
1056 return array(array(''), array(''));
1058 return array($m[0], $m[1]);
1062 $orig = new _HWLDF_WordAccumulator
;
1064 foreach ($this->edits
as $edit) {
1065 if ($edit->type
== 'copy')
1066 $orig->addWords($edit->orig
);
1067 elseif ($edit->orig
)
1068 $orig->addWords($edit->orig
, 'mark');
1070 return $orig->getLines();
1073 function closing () {
1074 $closing = new _HWLDF_WordAccumulator
;
1076 foreach ($this->edits
as $edit) {
1077 if ($edit->type
== 'copy')
1078 $closing->addWords($edit->closing
);
1079 elseif ($edit->closing
)
1080 $closing->addWords($edit->closing
, 'mark');
1082 return $closing->getLines();
1087 * Wikipedia Table style diff formatter.
1090 class TableDiffFormatter
extends DiffFormatter
1092 function TableDiffFormatter() {
1093 $this->leading_context_lines
= 2;
1094 $this->trailing_context_lines
= 2;
1097 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1098 $l1 = wfMsg( "lineno", $xbeg );
1099 $l2 = wfMsg( "lineno", $ybeg );
1101 $r = "<tr><td colspan='2' align='left'><strong>{$l1}</strong></td>\n" .
1102 "<td colspan='2' align='left'><strong>{$l2}</strong></td></tr>\n";
1106 function _start_block( $header ) {
1108 $wgOut->addHTML( $header );
1111 function _end_block() {
1114 function _lines( $lines, $prefix=' ', $color="white" ) {
1117 function addedLine( $line ) {
1118 return "<td>+</td><td class='diff-addedline'>" .
1119 "<small>{$line}</small></td>";
1122 function deletedLine( $line ) {
1123 return "<td>-</td><td class='diff-deletedline'>" .
1124 "<small>{$line}</small></td>";
1127 function emptyLine() {
1128 return "<td colspan='2'> </td>";
1131 function contextLine( $line ) {
1132 return "<td> </td><td class='diff-context'><small>{$line}</small></td>";
1135 function _added($lines) {
1137 foreach ($lines as $line) {
1138 $wgOut->addHTML( "<tr>" . $this->emptyLine() .
1139 $this->addedLine( $line ) . "</tr>\n" );
1143 function _deleted($lines) {
1145 foreach ($lines as $line) {
1146 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1147 $this->emptyLine() . "</tr>\n" );
1151 function _context( $lines ) {
1153 foreach ($lines as $line) {
1154 $wgOut->addHTML( "<tr>" . $this->contextLine( $line ) .
1155 $this->contextLine( $line ) . "</tr>\n" );
1159 function _changed( $orig, $closing ) {
1161 $diff = new WordLevelDiff( $orig, $closing );
1162 $del = $diff->orig();
1163 $add = $diff->closing();
1165 while ( $line = array_shift( $del ) ) {
1166 $aline = array_shift( $add );
1167 $wgOut->addHTML( "<tr>" . $this->deletedLine( $line ) .
1168 $this->addedLine( $aline ) . "</tr>\n" );
1170 $this->_added( $add ); # If any leftovers