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;
11 /* private */ var $mRcidMarkPatrolled;
13 function DifferenceEngine( $old, $new, $rcid = 0 )
17 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
20 function showDiffPage()
22 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
23 $fname = "DifferenceEngine::showDiffPage";
24 wfProfileIn( $fname );
26 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
28 $mtext = wfMsg( "missingarticle", $t );
30 $wgOut->setArticleFlag( false );
31 if ( ! $this->loadText() ) {
32 $wgOut->setPagetitle( wfMsg( "errorpagetitle" ) );
33 $wgOut->addHTML( $mtext );
34 wfProfileOut( $fname );
37 $wgOut->suppressQuickbar();
39 $oldTitle = $this->mOldPage
->getPrefixedText();
40 $newTitle = $this->mNewPage
->getPrefixedText();
41 if( $oldTitle == $newTitle ) {
42 $wgOut->setPageTitle( $newTitle );
44 $wgOut->setPageTitle( $oldTitle . ", " . $newTitle );
46 $wgOut->setSubtitle( wfMsg( "difference" ) );
47 $wgOut->setRobotpolicy( "noindex,follow" );
49 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
52 wfProfileOut( $fname );
56 $sk = $wgUser->getSkin();
57 $talk = $wgLang->getNsText( NS_TALK
);
58 $contribs = wfMsg( "contribslink" );
60 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
61 $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>";
77 if ( $wgUseRCPatrol &&
78 ($this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
79 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) ) )
81 $patrol = " [" . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
82 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . "]";
87 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
88 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
;
89 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
90 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
. $patrol;
92 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
93 $oldHeader, $newHeader );
94 $wgOut->addHTML( "<hr /><h2>{$this->mNewtitle}</h2>\n" );
95 $wgOut->addWikiText( $this->mNewtext
);
97 wfProfileOut( $fname );
100 function showDiff( $otext, $ntext, $otitle, $ntitle )
102 global $wgOut, $wgUseExternalDiffEngine;
104 $otext = str_replace( "\r\n", "\n", htmlspecialchars( $otext ) );
105 $ntext = str_replace( "\r\n", "\n", htmlspecialchars( $ntext ) );
108 $wgOut->addHTML( "<table border='0' width='98%'
109 cellpadding='0' cellspacing='4px' class='diff'><tr>
110 <td colspan='2' width='50%' align='center' class='diff-otitle'>
112 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
115 if ( $wgUseExternalDiffEngine ) {
116 dl("php_wikidiff.so");
117 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
119 $ota = explode( "\n", $otext);
120 $nta = explode( "\n", $ntext);
121 $diffs = new Diff( $ota, $nta );
122 $formatter = new TableDiffFormatter();
123 $formatter->format( $diffs );
125 $wgOut->addHTML( "</table>\n" );
128 # Load the text of the articles to compare. If newid is 0, then compare
129 # the old article in oldid to the current article; if oldid is 0, then
130 # compare the current article to the immediately previous one (ignoring
131 # the value of newid).
135 global $wgTitle, $wgOut, $wgLang;
136 $fname = "DifferenceEngine::loadText";
138 $dbr =& wfGetDB( DB_SLAVE
);
139 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
140 $wgOut->setArticleFlag( true );
141 $this->mNewtitle
= wfMsg( "currentrev" );
142 $id = $wgTitle->getArticleID();
144 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
145 array( 'cur_id' => $id ), $fname );
146 if ( $s === false ) {
150 $this->mNewPage
= &$wgTitle;
151 $this->mNewtext
= $s->cur_text
;
152 $this->mNewUser
= $s->cur_user_text
;
153 $this->mNewComment
= $s->cur_comment
;
155 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
156 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
158 if ( $s === false ) {
162 $this->mNewtext
= Article
::getRevisionText( $s );
164 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
165 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
166 $this->mNewtitle
= wfMsg( "revisionasof", $t );
167 $this->mNewUser
= $s->old_user_text
;
168 $this->mNewComment
= $s->old_comment
;
170 if ( 0 == $this->mOldid
) {
171 $s = $dbr->getArray( 'old',
172 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
174 'old_namespace' => $this->mNewPage
->getNamespace(),
175 'old_title' => $this->mNewPage
->getDBkey()
176 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
179 $s = $dbr->getArray( 'old',
180 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
181 array( 'old_id' => $this->mOldid
),
185 if ( $s === false ) {
188 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
189 $this->mOldtext
= Article
::getRevisionText( $s );
191 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
192 $this->mOldtitle
= wfMsg( "revisionasof", $t );
193 $this->mOldUser
= $s->old_user_text
;
194 $this->mOldComment
= $s->old_comment
;
200 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
202 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
203 // You may copy this code freely under the conditions of the GPL.
206 define('USE_ASSERTS', function_exists('assert'));
214 trigger_error("pure virtual", E_USER_ERROR
);
218 return $this->orig ?
sizeof($this->orig
) : 0;
221 function nclosing() {
222 return $this->closing ?
sizeof($this->closing
) : 0;
226 class _DiffOp_Copy
extends _DiffOp
{
229 function _DiffOp_Copy ($orig, $closing = false) {
230 if (!is_array($closing))
233 $this->closing
= $closing;
237 return new _DiffOp_Copy($this->closing
, $this->orig
);
241 class _DiffOp_Delete
extends _DiffOp
{
242 var $type = 'delete';
244 function _DiffOp_Delete ($lines) {
245 $this->orig
= $lines;
246 $this->closing
= false;
250 return new _DiffOp_Add($this->orig
);
254 class _DiffOp_Add
extends _DiffOp
{
257 function _DiffOp_Add ($lines) {
258 $this->closing
= $lines;
263 return new _DiffOp_Delete($this->closing
);
267 class _DiffOp_Change
extends _DiffOp
{
268 var $type = 'change';
270 function _DiffOp_Change ($orig, $closing) {
272 $this->closing
= $closing;
276 return new _DiffOp_Change($this->closing
, $this->orig
);
282 * Class used internally by Diff to actually compute the diffs.
284 * The algorithm used here is mostly lifted from the perl module
285 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
286 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
288 * More ideas are taken from:
289 * http://www.ics.uci.edu/~eppstein/161/960229.html
291 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
292 * diffutils-2.7, which can be found at:
293 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
295 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
298 * @author Geoffrey T. Dairiki
303 function diff ($from_lines, $to_lines) {
304 $n_from = sizeof($from_lines);
305 $n_to = sizeof($to_lines);
307 $this->xchanged
= $this->ychanged
= array();
308 $this->xv
= $this->yv
= array();
309 $this->xind
= $this->yind
= array();
311 unset($this->in_seq
);
314 // Skip leading common lines.
315 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
316 if ($from_lines[$skip] != $to_lines[$skip])
318 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
320 // Skip trailing common lines.
321 $xi = $n_from; $yi = $n_to;
322 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
323 if ($from_lines[$xi] != $to_lines[$yi])
325 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
328 // Ignore lines which do not exist in both files.
329 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
330 $xhash[$from_lines[$xi]] = 1;
331 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
332 $line = $to_lines[$yi];
333 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
339 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
340 $line = $from_lines[$xi];
341 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
348 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
350 // Merge edits when possible
351 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
352 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
354 // Compute the edit operations.
357 while ($xi < $n_from ||
$yi < $n_to) {
358 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
359 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
361 // Skip matching "snake".
363 while ( $xi < $n_from && $yi < $n_to
364 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
365 $copy[] = $from_lines[$xi++
];
369 $edits[] = new _DiffOp_Copy($copy);
371 // Find deletes & adds.
373 while ($xi < $n_from && $this->xchanged
[$xi])
374 $delete[] = $from_lines[$xi++
];
377 while ($yi < $n_to && $this->ychanged
[$yi])
378 $add[] = $to_lines[$yi++
];
381 $edits[] = new _DiffOp_Change($delete, $add);
383 $edits[] = new _DiffOp_Delete($delete);
385 $edits[] = new _DiffOp_Add($add);
391 /* Divide the Largest Common Subsequence (LCS) of the sequences
392 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
395 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
396 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
397 * sub sequences. The first sub-sequence is contained in [X0, X1),
398 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
399 * that (X0, Y0) == (XOFF, YOFF) and
400 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
402 * This function assumes that the first lines of the specified portions
403 * of the two files do not match, and likewise that the last lines do not
404 * match. The caller must trim matching lines from the beginning and end
405 * of the portions it is going to specify.
407 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
410 if ($xlim - $xoff > $ylim - $yoff) {
411 // Things seems faster (I'm not sure I understand why)
412 // when the shortest sequence in X.
414 list ($xoff, $xlim, $yoff, $ylim)
415 = array( $yoff, $ylim, $xoff, $xlim);
419 for ($i = $ylim - 1; $i >= $yoff; $i--)
420 $ymatches[$this->xv
[$i]][] = $i;
422 for ($i = $ylim - 1; $i >= $yoff; $i--)
423 $ymatches[$this->yv
[$i]][] = $i;
426 $this->seq
[0]= $yoff - 1;
427 $this->in_seq
= array();
430 $numer = $xlim - $xoff +
$nchunks - 1;
432 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
434 for ($i = 0; $i <= $this->lcs
; $i++
)
435 $ymids[$i][$chunk-1] = $this->seq
[$i];
437 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
438 for ( ; $x < $x1; $x++
) {
439 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
440 if (empty($ymatches[$line]))
442 $matches = $ymatches[$line];
444 while (list ($junk, $y) = each($matches))
445 if (empty($this->in_seq
[$y])) {
446 $k = $this->_lcs_pos($y);
447 USE_ASSERTS
&& assert($k > 0);
448 $ymids[$k] = $ymids[$k-1];
451 while (list ($junk, $y) = each($matches)) {
452 if ($y > $this->seq
[$k-1]) {
453 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
454 // Optimization: this is a common case:
455 // next match is just replacing previous match.
456 $this->in_seq
[$this->seq
[$k]] = false;
458 $this->in_seq
[$y] = 1;
460 else if (empty($this->in_seq
[$y])) {
461 $k = $this->_lcs_pos($y);
462 USE_ASSERTS
&& assert($k > 0);
463 $ymids[$k] = $ymids[$k-1];
469 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
470 $ymid = $ymids[$this->lcs
];
471 for ($n = 0; $n < $nchunks - 1; $n++
) {
472 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
474 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
476 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
478 return array($this->lcs
, $seps);
481 function _lcs_pos ($ypos) {
483 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
484 $this->seq
[++
$this->lcs
] = $ypos;
485 $this->in_seq
[$ypos] = 1;
490 while ($beg < $end) {
491 $mid = (int)(($beg +
$end) / 2);
492 if ( $ypos > $this->seq
[$mid] )
498 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
500 $this->in_seq
[$this->seq
[$end]] = false;
501 $this->seq
[$end] = $ypos;
502 $this->in_seq
[$ypos] = 1;
506 /* Find LCS of two sequences.
508 * The results are recorded in the vectors $this->{x,y}changed[], by
509 * storing a 1 in the element for each line that is an insertion
510 * or deletion (ie. is not in the LCS).
512 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
514 * Note that XLIM, YLIM are exclusive bounds.
515 * All line numbers are origin-0 and discarded lines are not counted.
517 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
518 // Slide down the bottom initial diagonal.
519 while ($xoff < $xlim && $yoff < $ylim
520 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
525 // Slide up the top initial diagonal.
526 while ($xlim > $xoff && $ylim > $yoff
527 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
532 if ($xoff == $xlim ||
$yoff == $ylim)
535 // This is ad hoc but seems to work well.
536 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
537 //$nchunks = max(2,min(8,(int)$nchunks));
538 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
540 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
544 // X and Y sequences have no common subsequence:
546 while ($yoff < $ylim)
547 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
548 while ($xoff < $xlim)
549 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
552 // Use the partitions to split this problem into subproblems.
555 while ($pt2 = next($seps)) {
556 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
562 /* Adjust inserts/deletes of identical lines to join changes
563 * as much as possible.
565 * We do something when a run of changed lines include a
566 * line at one end and has an excluded, identical line at the other.
567 * We are free to choose which identical line is included.
568 * `compareseq' usually chooses the one at the beginning,
569 * but usually it is cleaner to consider the following identical line
570 * to be the "change".
572 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
574 function _shift_boundaries ($lines, &$changed, $other_changed) {
578 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
579 $len = sizeof($lines);
580 $other_len = sizeof($other_changed);
584 * Scan forwards to find beginning of another run of changes.
585 * Also keep track of the corresponding point in the other file.
587 * Throughout this code, $i and $j are adjusted together so that
588 * the first $i elements of $changed and the first $j elements
589 * of $other_changed both contain the same number of zeros
591 * Furthermore, $j is always kept so that $j == $other_len or
592 * $other_changed[$j] == false.
594 while ($j < $other_len && $other_changed[$j])
597 while ($i < $len && ! $changed[$i]) {
598 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
600 while ($j < $other_len && $other_changed[$j])
609 // Find the end of this run of changes.
610 while (++
$i < $len && $changed[$i])
615 * Record the length of this run of changes, so that
616 * we can later determine whether the run has grown.
618 $runlength = $i - $start;
621 * Move the changed region back, so long as the
622 * previous unchanged line matches the last changed one.
623 * This merges with previous changed regions.
625 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
626 $changed[--$start] = 1;
627 $changed[--$i] = false;
628 while ($start > 0 && $changed[$start - 1])
630 USE_ASSERTS
&& assert('$j > 0');
631 while ($other_changed[--$j])
633 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
637 * Set CORRESPONDING to the end of the changed run, at the last
638 * point where it corresponds to a changed run in the other file.
639 * CORRESPONDING == LEN means no such point has been found.
641 $corresponding = $j < $other_len ?
$i : $len;
644 * Move the changed region forward, so long as the
645 * first changed line matches the following unchanged one.
646 * This merges with following changed regions.
647 * Do this second, so that if there are no merges,
648 * the changed region is moved forward as far as possible.
650 while ($i < $len && $lines[$start] == $lines[$i]) {
651 $changed[$start++
] = false;
653 while ($i < $len && $changed[$i])
656 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
658 if ($j < $other_len && $other_changed[$j]) {
660 while ($j < $other_len && $other_changed[$j])
664 } while ($runlength != $i - $start);
667 * If possible, move the fully-merged run of changes
668 * back to a corresponding run in the other file.
670 while ($corresponding < $i) {
671 $changed[--$start] = 1;
673 USE_ASSERTS
&& assert('$j > 0');
674 while ($other_changed[--$j])
676 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
683 * Class representing a 'diff' between two sequences of strings.
691 * Computes diff between sequences of strings.
693 * @param $from_lines array An array of strings.
694 * (Typically these are lines from a file.)
695 * @param $to_lines array An array of strings.
697 function Diff($from_lines, $to_lines) {
698 $eng = new _DiffEngine
;
699 $this->edits
= $eng->diff($from_lines, $to_lines);
700 //$this->_check($from_lines, $to_lines);
704 * Compute reversed Diff.
708 * $diff = new Diff($lines1, $lines2);
709 * $rev = $diff->reverse();
710 * @return object A Diff object representing the inverse of the
713 function reverse () {
715 $rev->edits
= array();
716 foreach ($this->edits
as $edit) {
717 $rev->edits
[] = $edit->reverse();
723 * Check for empty diff.
725 * @return bool True iff two sequences were identical.
727 function isEmpty () {
728 foreach ($this->edits
as $edit) {
729 if ($edit->type
!= 'copy')
736 * Compute the length of the Longest Common Subsequence (LCS).
738 * This is mostly for diagnostic purposed.
740 * @return int The length of the LCS.
744 foreach ($this->edits
as $edit) {
745 if ($edit->type
== 'copy')
746 $lcs +
= sizeof($edit->orig
);
752 * Get the original set of lines.
754 * This reconstructs the $from_lines parameter passed to the
757 * @return array The original sequence of strings.
762 foreach ($this->edits
as $edit) {
764 array_splice($lines, sizeof($lines), 0, $edit->orig
);
770 * Get the closing set of lines.
772 * This reconstructs the $to_lines parameter passed to the
775 * @return array The sequence of strings.
780 foreach ($this->edits
as $edit) {
782 array_splice($lines, sizeof($lines), 0, $edit->closing
);
788 * Check a Diff for validity.
790 * This is here only for debugging purposes.
792 function _check ($from_lines, $to_lines) {
793 if (serialize($from_lines) != serialize($this->orig()))
794 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
795 if (serialize($to_lines) != serialize($this->closing()))
796 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
798 $rev = $this->reverse();
799 if (serialize($to_lines) != serialize($rev->orig()))
800 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
801 if (serialize($from_lines) != serialize($rev->closing()))
802 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
806 foreach ($this->edits
as $edit) {
807 if ( $prevtype == $edit->type
)
808 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
809 $prevtype = $edit->type
;
813 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE
);
826 * Computes diff between sequences of strings.
828 * This can be used to compute things like
829 * case-insensitve diffs, or diffs which ignore
830 * changes in white-space.
832 * @param $from_lines array An array of strings.
833 * (Typically these are lines from a file.)
835 * @param $to_lines array An array of strings.
837 * @param $mapped_from_lines array This array should
838 * have the same size number of elements as $from_lines.
839 * The elements in $mapped_from_lines and
840 * $mapped_to_lines are what is actually compared
841 * when computing the diff.
843 * @param $mapped_to_lines array This array should
844 * have the same number of elements as $to_lines.
846 function MappedDiff($from_lines, $to_lines,
847 $mapped_from_lines, $mapped_to_lines) {
849 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
850 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
852 $this->Diff($mapped_from_lines, $mapped_to_lines);
855 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
856 $orig = &$this->edits
[$i]->orig
;
857 if (is_array($orig)) {
858 $orig = array_slice($from_lines, $xi, sizeof($orig));
859 $xi +
= sizeof($orig);
862 $closing = &$this->edits
[$i]->closing
;
863 if (is_array($closing)) {
864 $closing = array_slice($to_lines, $yi, sizeof($closing));
865 $yi +
= sizeof($closing);
872 * A class to format Diffs
874 * This class formats the diff in classic diff format.
875 * It is intended that this class be customized via inheritance,
876 * to obtain fancier outputs.
881 * Number of leading context "lines" to preserve.
883 * This should be left at zero for this class, but subclasses
884 * may want to set this to other values.
886 var $leading_context_lines = 0;
889 * Number of trailing context "lines" to preserve.
891 * This should be left at zero for this class, but subclasses
892 * may want to set this to other values.
894 var $trailing_context_lines = 0;
899 * @param $diff object A Diff object.
900 * @return string The formatted output.
902 function format($diff) {
908 $nlead = $this->leading_context_lines
;
909 $ntrail = $this->trailing_context_lines
;
911 $this->_start_diff();
913 foreach ($diff->edits
as $edit) {
914 if ($edit->type
== 'copy') {
915 if (is_array($block)) {
916 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
921 $context = array_slice($edit->orig
, 0, $ntrail);
922 $block[] = new _DiffOp_Copy($context);
924 $this->_block($x0, $ntrail +
$xi - $x0,
925 $y0, $ntrail +
$yi - $y0,
930 $context = $edit->orig
;
933 if (! is_array($block)) {
934 $context = array_slice($context, sizeof($context) - $nlead);
935 $x0 = $xi - sizeof($context);
936 $y0 = $yi - sizeof($context);
939 $block[] = new _DiffOp_Copy($context);
945 $xi +
= sizeof($edit->orig
);
947 $yi +
= sizeof($edit->closing
);
950 if (is_array($block))
951 $this->_block($x0, $xi - $x0,
955 return $this->_end_diff();
958 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
959 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
960 foreach ($edits as $edit) {
961 if ($edit->type
== 'copy')
962 $this->_context($edit->orig
);
963 elseif ($edit->type
== 'add')
964 $this->_added($edit->closing
);
965 elseif ($edit->type
== 'delete')
966 $this->_deleted($edit->orig
);
967 elseif ($edit->type
== 'change')
968 $this->_changed($edit->orig
, $edit->closing
);
970 trigger_error("Unknown edit type", E_USER_ERROR
);
975 function _start_diff() {
979 function _end_diff() {
980 $val = ob_get_contents();
985 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
987 $xbeg .= "," . ($xbeg +
$xlen - 1);
989 $ybeg .= "," . ($ybeg +
$ylen - 1);
991 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
994 function _start_block($header) {
998 function _end_block() {
1001 function _lines($lines, $prefix = ' ') {
1002 foreach ($lines as $line)
1003 echo "$prefix $line\n";
1006 function _context($lines) {
1007 $this->_lines($lines);
1010 function _added($lines) {
1011 $this->_lines($lines, ">");
1013 function _deleted($lines) {
1014 $this->_lines($lines, "<");
1017 function _changed($orig, $closing) {
1018 $this->_deleted($orig);
1020 $this->_added($closing);
1026 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1030 define('NBSP', ' '); // iso-8859-x non-breaking space.
1032 class _HWLDF_WordAccumulator
{
1033 function _HWLDF_WordAccumulator () {
1034 $this->_lines
= array();
1040 function _flushGroup ($new_tag) {
1041 if ($this->_group
!== '') {
1042 if ($this->_tag
== 'mark')
1043 $this->_line
.= '<span class="diffchange">'.$this->_group
.'</span>';
1045 $this->_line
.= $this->_group
;
1048 $this->_tag
= $new_tag;
1051 function _flushLine ($new_tag) {
1052 $this->_flushGroup($new_tag);
1053 if ($this->_line
!= '')
1054 $this->_lines
[] = $this->_line
;
1058 function addWords ($words, $tag = '') {
1059 if ($tag != $this->_tag
)
1060 $this->_flushGroup($tag);
1062 foreach ($words as $word) {
1063 // new-line should only come as first char of word.
1066 if ($word[0] == "\n") {
1067 $this->_group
.= NBSP
;
1068 $this->_flushLine($tag);
1069 $word = substr($word, 1);
1071 assert(!strstr($word, "\n"));
1072 $this->_group
.= $word;
1076 function getLines() {
1077 $this->_flushLine('~done');
1078 return $this->_lines
;
1082 class WordLevelDiff
extends MappedDiff
1084 function WordLevelDiff ($orig_lines, $closing_lines) {
1085 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1086 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1089 $this->MappedDiff($orig_words, $closing_words,
1090 $orig_stripped, $closing_stripped);
1093 function _split($lines) {
1094 // FIXME: fix POSIX char class.
1095 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1096 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1097 implode("\n", $lines),
1099 return array(array(''), array(''));
1101 return array($m[0], $m[1]);
1105 $orig = new _HWLDF_WordAccumulator
;
1107 foreach ($this->edits
as $edit) {
1108 if ($edit->type
== 'copy')
1109 $orig->addWords($edit->orig
);
1110 elseif ($edit->orig
)
1111 $orig->addWords($edit->orig
, 'mark');
1113 return $orig->getLines();
1116 function closing () {
1117 $closing = new _HWLDF_WordAccumulator
;
1119 foreach ($this->edits
as $edit) {
1120 if ($edit->type
== 'copy')
1121 $closing->addWords($edit->closing
);
1122 elseif ($edit->closing
)
1123 $closing->addWords($edit->closing
, 'mark');
1125 return $closing->getLines();
1130 * Wikipedia Table style diff formatter.
1133 class TableDiffFormatter
extends DiffFormatter
1135 function TableDiffFormatter() {
1136 $this->leading_context_lines
= 2;
1137 $this->trailing_context_lines
= 2;
1140 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1141 $l1 = wfMsg( "lineno", $xbeg );
1142 $l2 = wfMsg( "lineno", $ybeg );
1144 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1145 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1149 function _start_block( $header ) {
1151 $wgOut->addHTML( $header );
1154 function _end_block() {
1157 function _lines( $lines, $prefix=' ', $color="white" ) {
1160 function addedLine( $line ) {
1161 return '<td>+</td><td class="diff-addedline">' .
1165 function deletedLine( $line ) {
1166 return '<td>-</td><td class="diff-deletedline">' .
1170 function emptyLine() {
1171 return '<td colspan="2"> </td>';
1174 function contextLine( $line ) {
1175 return '<td> </td><td class="diff-context">'.$line.'</td>';
1178 function _added($lines) {
1180 foreach ($lines as $line) {
1181 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1182 $this->addedLine( $line ) . "</tr>\n" );
1186 function _deleted($lines) {
1188 foreach ($lines as $line) {
1189 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1190 $this->emptyLine() . "</tr>\n" );
1194 function _context( $lines ) {
1196 foreach ($lines as $line) {
1197 $wgOut->addHTML( '<tr>' . $this->contextLine( $line ) .
1198 $this->contextLine( $line ) . "</tr>\n" );
1202 function _changed( $orig, $closing ) {
1204 $diff = new WordLevelDiff( $orig, $closing );
1205 $del = $diff->orig();
1206 $add = $diff->closing();
1208 while ( $line = array_shift( $del ) ) {
1209 $aline = array_shift( $add );
1210 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1211 $this->addedLine( $aline ) . "</tr>\n" );
1213 $this->_added( $add ); # If any leftovers