4 class DifferenceEngine
{
5 /* private */ var $mOldid, $mNewid;
6 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
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
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
64 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
65 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
66 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( 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 && $this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
78 ( $wgUser->isSysop() ||
!$wgOnlySysopsCanPatrol ) )
80 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
81 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
86 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
87 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
;
88 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
89 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
. $patrol;
91 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
92 $oldHeader, $newHeader );
93 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
94 $wgOut->addWikiText( $this->mNewtext
);
96 wfProfileOut( $fname );
99 function showDiff( $otext, $ntext, $otitle, $ntitle )
101 global $wgOut, $wgUseExternalDiffEngine;
103 $otext = str_replace( "\r\n", "\n", htmlspecialchars( $otext ) );
104 $ntext = str_replace( "\r\n", "\n", htmlspecialchars( $ntext ) );
107 $wgOut->addHTML( "<table border='0' width='98%'
108 cellpadding='0' cellspacing='4px' class='diff'><tr>
109 <td colspan='2' width='50%' align='center' class='diff-otitle'>
111 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
114 if ( $wgUseExternalDiffEngine ) {
115 dl('php_wikidiff.so');
116 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
118 $ota = explode( "\n", $otext);
119 $nta = explode( "\n", $ntext);
120 $diffs = new Diff( $ota, $nta );
121 $formatter = new TableDiffFormatter();
122 $formatter->format( $diffs );
124 $wgOut->addHTML( "</table>\n" );
127 # Load the text of the articles to compare. If newid is 0, then compare
128 # the old article in oldid to the current article; if oldid is 0, then
129 # compare the current article to the immediately previous one (ignoring
130 # the value of newid).
134 global $wgTitle, $wgOut, $wgLang;
135 $fname = 'DifferenceEngine::loadText';
137 $dbr =& wfGetDB( DB_SLAVE
);
138 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
139 $wgOut->setArticleFlag( true );
140 $newLink = $wgTitle->getLocalUrl();
141 $this->mPagetitle
= wfMsg( 'currentrev' );
142 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
143 $id = $wgTitle->getArticleID();
145 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
146 array( 'cur_id' => $id ), $fname );
147 if ( $s === false ) {
151 $this->mNewPage
= &$wgTitle;
152 $this->mNewtext
= $s->cur_text
;
153 $this->mNewUser
= $s->cur_user_text
;
154 $this->mNewComment
= $s->cur_comment
;
156 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
157 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid
), $fname );
159 if ( $s === false ) {
163 $this->mNewtext
= Article
::getRevisionText( $s );
165 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
166 $this->mNewPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
167 $newLink = $wgTitle->getLocalUrl ('oldid=' . $this->mNewid
);
168 $this->mPagetitle
= wfMsg( 'revisionasof', $t );
169 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
170 $this->mNewUser
= $s->old_user_text
;
171 $this->mNewComment
= $s->old_comment
;
173 if ( 0 == $this->mOldid
) {
174 $s = $dbr->getArray( 'old',
175 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
177 'old_namespace' => $this->mNewPage
->getNamespace(),
178 'old_title' => $this->mNewPage
->getDBkey()
179 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
182 $s = $dbr->getArray( 'old',
183 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
184 array( 'old_id' => $this->mOldid
),
188 if ( $s === false ) {
191 $this->mOldPage
= Title
::MakeTitle( $s->old_namespace
, $s->old_title
);
192 $this->mOldtext
= Article
::getRevisionText( $s );
194 $t = $wgLang->timeanddate( $s->old_timestamp
, true );
195 $oldLink = $this->mOldPage
->getLocalUrl ('oldid=' . $this->mOldid
);
196 $this->mOldtitle
= "<a href='$oldLink'>" . wfMsg( 'revisionasof', $t ) . '</a>';
197 $this->mOldUser
= $s->old_user_text
;
198 $this->mOldComment
= $s->old_comment
;
204 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
206 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
207 // You may copy this code freely under the conditions of the GPL.
210 define('USE_ASSERTS', function_exists('assert'));
218 trigger_error('pure virtual', E_USER_ERROR
);
222 return $this->orig ?
sizeof($this->orig
) : 0;
225 function nclosing() {
226 return $this->closing ?
sizeof($this->closing
) : 0;
230 class _DiffOp_Copy
extends _DiffOp
{
233 function _DiffOp_Copy ($orig, $closing = false) {
234 if (!is_array($closing))
237 $this->closing
= $closing;
241 return new _DiffOp_Copy($this->closing
, $this->orig
);
245 class _DiffOp_Delete
extends _DiffOp
{
246 var $type = 'delete';
248 function _DiffOp_Delete ($lines) {
249 $this->orig
= $lines;
250 $this->closing
= false;
254 return new _DiffOp_Add($this->orig
);
258 class _DiffOp_Add
extends _DiffOp
{
261 function _DiffOp_Add ($lines) {
262 $this->closing
= $lines;
267 return new _DiffOp_Delete($this->closing
);
271 class _DiffOp_Change
extends _DiffOp
{
272 var $type = 'change';
274 function _DiffOp_Change ($orig, $closing) {
276 $this->closing
= $closing;
280 return new _DiffOp_Change($this->closing
, $this->orig
);
286 * Class used internally by Diff to actually compute the diffs.
288 * The algorithm used here is mostly lifted from the perl module
289 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
290 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
292 * More ideas are taken from:
293 * http://www.ics.uci.edu/~eppstein/161/960229.html
295 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
296 * diffutils-2.7, which can be found at:
297 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
299 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
302 * @author Geoffrey T. Dairiki
307 function diff ($from_lines, $to_lines) {
308 $n_from = sizeof($from_lines);
309 $n_to = sizeof($to_lines);
311 $this->xchanged
= $this->ychanged
= array();
312 $this->xv
= $this->yv
= array();
313 $this->xind
= $this->yind
= array();
315 unset($this->in_seq
);
318 // Skip leading common lines.
319 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
320 if ($from_lines[$skip] != $to_lines[$skip])
322 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
324 // Skip trailing common lines.
325 $xi = $n_from; $yi = $n_to;
326 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
327 if ($from_lines[$xi] != $to_lines[$yi])
329 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
332 // Ignore lines which do not exist in both files.
333 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
334 $xhash[$from_lines[$xi]] = 1;
335 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
336 $line = $to_lines[$yi];
337 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
343 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
344 $line = $from_lines[$xi];
345 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
352 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
354 // Merge edits when possible
355 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
356 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
358 // Compute the edit operations.
361 while ($xi < $n_from ||
$yi < $n_to) {
362 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
363 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
365 // Skip matching "snake".
367 while ( $xi < $n_from && $yi < $n_to
368 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
369 $copy[] = $from_lines[$xi++
];
373 $edits[] = new _DiffOp_Copy($copy);
375 // Find deletes & adds.
377 while ($xi < $n_from && $this->xchanged
[$xi])
378 $delete[] = $from_lines[$xi++
];
381 while ($yi < $n_to && $this->ychanged
[$yi])
382 $add[] = $to_lines[$yi++
];
385 $edits[] = new _DiffOp_Change($delete, $add);
387 $edits[] = new _DiffOp_Delete($delete);
389 $edits[] = new _DiffOp_Add($add);
395 /* Divide the Largest Common Subsequence (LCS) of the sequences
396 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
399 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
400 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
401 * sub sequences. The first sub-sequence is contained in [X0, X1),
402 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
403 * that (X0, Y0) == (XOFF, YOFF) and
404 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
406 * This function assumes that the first lines of the specified portions
407 * of the two files do not match, and likewise that the last lines do not
408 * match. The caller must trim matching lines from the beginning and end
409 * of the portions it is going to specify.
411 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
414 if ($xlim - $xoff > $ylim - $yoff) {
415 // Things seems faster (I'm not sure I understand why)
416 // when the shortest sequence in X.
418 list ($xoff, $xlim, $yoff, $ylim)
419 = array( $yoff, $ylim, $xoff, $xlim);
423 for ($i = $ylim - 1; $i >= $yoff; $i--)
424 $ymatches[$this->xv
[$i]][] = $i;
426 for ($i = $ylim - 1; $i >= $yoff; $i--)
427 $ymatches[$this->yv
[$i]][] = $i;
430 $this->seq
[0]= $yoff - 1;
431 $this->in_seq
= array();
434 $numer = $xlim - $xoff +
$nchunks - 1;
436 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
438 for ($i = 0; $i <= $this->lcs
; $i++
)
439 $ymids[$i][$chunk-1] = $this->seq
[$i];
441 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
442 for ( ; $x < $x1; $x++
) {
443 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
444 if (empty($ymatches[$line]))
446 $matches = $ymatches[$line];
448 while (list ($junk, $y) = each($matches))
449 if (empty($this->in_seq
[$y])) {
450 $k = $this->_lcs_pos($y);
451 USE_ASSERTS
&& assert($k > 0);
452 $ymids[$k] = $ymids[$k-1];
455 while (list ($junk, $y) = each($matches)) {
456 if ($y > $this->seq
[$k-1]) {
457 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
458 // Optimization: this is a common case:
459 // next match is just replacing previous match.
460 $this->in_seq
[$this->seq
[$k]] = false;
462 $this->in_seq
[$y] = 1;
464 else if (empty($this->in_seq
[$y])) {
465 $k = $this->_lcs_pos($y);
466 USE_ASSERTS
&& assert($k > 0);
467 $ymids[$k] = $ymids[$k-1];
473 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
474 $ymid = $ymids[$this->lcs
];
475 for ($n = 0; $n < $nchunks - 1; $n++
) {
476 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
478 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
480 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
482 return array($this->lcs
, $seps);
485 function _lcs_pos ($ypos) {
487 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
488 $this->seq
[++
$this->lcs
] = $ypos;
489 $this->in_seq
[$ypos] = 1;
494 while ($beg < $end) {
495 $mid = (int)(($beg +
$end) / 2);
496 if ( $ypos > $this->seq
[$mid] )
502 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
504 $this->in_seq
[$this->seq
[$end]] = false;
505 $this->seq
[$end] = $ypos;
506 $this->in_seq
[$ypos] = 1;
510 /* Find LCS of two sequences.
512 * The results are recorded in the vectors $this->{x,y}changed[], by
513 * storing a 1 in the element for each line that is an insertion
514 * or deletion (ie. is not in the LCS).
516 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
518 * Note that XLIM, YLIM are exclusive bounds.
519 * All line numbers are origin-0 and discarded lines are not counted.
521 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
522 // Slide down the bottom initial diagonal.
523 while ($xoff < $xlim && $yoff < $ylim
524 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
529 // Slide up the top initial diagonal.
530 while ($xlim > $xoff && $ylim > $yoff
531 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
536 if ($xoff == $xlim ||
$yoff == $ylim)
539 // This is ad hoc but seems to work well.
540 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
541 //$nchunks = max(2,min(8,(int)$nchunks));
542 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
544 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
548 // X and Y sequences have no common subsequence:
550 while ($yoff < $ylim)
551 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
552 while ($xoff < $xlim)
553 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
556 // Use the partitions to split this problem into subproblems.
559 while ($pt2 = next($seps)) {
560 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
566 /* Adjust inserts/deletes of identical lines to join changes
567 * as much as possible.
569 * We do something when a run of changed lines include a
570 * line at one end and has an excluded, identical line at the other.
571 * We are free to choose which identical line is included.
572 * `compareseq' usually chooses the one at the beginning,
573 * but usually it is cleaner to consider the following identical line
574 * to be the "change".
576 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
578 function _shift_boundaries ($lines, &$changed, $other_changed) {
582 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
583 $len = sizeof($lines);
584 $other_len = sizeof($other_changed);
588 * Scan forwards to find beginning of another run of changes.
589 * Also keep track of the corresponding point in the other file.
591 * Throughout this code, $i and $j are adjusted together so that
592 * the first $i elements of $changed and the first $j elements
593 * of $other_changed both contain the same number of zeros
595 * Furthermore, $j is always kept so that $j == $other_len or
596 * $other_changed[$j] == false.
598 while ($j < $other_len && $other_changed[$j])
601 while ($i < $len && ! $changed[$i]) {
602 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
604 while ($j < $other_len && $other_changed[$j])
613 // Find the end of this run of changes.
614 while (++
$i < $len && $changed[$i])
619 * Record the length of this run of changes, so that
620 * we can later determine whether the run has grown.
622 $runlength = $i - $start;
625 * Move the changed region back, so long as the
626 * previous unchanged line matches the last changed one.
627 * This merges with previous changed regions.
629 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
630 $changed[--$start] = 1;
631 $changed[--$i] = false;
632 while ($start > 0 && $changed[$start - 1])
634 USE_ASSERTS
&& assert('$j > 0');
635 while ($other_changed[--$j])
637 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
641 * Set CORRESPONDING to the end of the changed run, at the last
642 * point where it corresponds to a changed run in the other file.
643 * CORRESPONDING == LEN means no such point has been found.
645 $corresponding = $j < $other_len ?
$i : $len;
648 * Move the changed region forward, so long as the
649 * first changed line matches the following unchanged one.
650 * This merges with following changed regions.
651 * Do this second, so that if there are no merges,
652 * the changed region is moved forward as far as possible.
654 while ($i < $len && $lines[$start] == $lines[$i]) {
655 $changed[$start++
] = false;
657 while ($i < $len && $changed[$i])
660 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
662 if ($j < $other_len && $other_changed[$j]) {
664 while ($j < $other_len && $other_changed[$j])
668 } while ($runlength != $i - $start);
671 * If possible, move the fully-merged run of changes
672 * back to a corresponding run in the other file.
674 while ($corresponding < $i) {
675 $changed[--$start] = 1;
677 USE_ASSERTS
&& assert('$j > 0');
678 while ($other_changed[--$j])
680 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
687 * Class representing a 'diff' between two sequences of strings.
695 * Computes diff between sequences of strings.
697 * @param $from_lines array An array of strings.
698 * (Typically these are lines from a file.)
699 * @param $to_lines array An array of strings.
701 function Diff($from_lines, $to_lines) {
702 $eng = new _DiffEngine
;
703 $this->edits
= $eng->diff($from_lines, $to_lines);
704 //$this->_check($from_lines, $to_lines);
708 * Compute reversed Diff.
712 * $diff = new Diff($lines1, $lines2);
713 * $rev = $diff->reverse();
714 * @return object A Diff object representing the inverse of the
717 function reverse () {
719 $rev->edits
= array();
720 foreach ($this->edits
as $edit) {
721 $rev->edits
[] = $edit->reverse();
727 * Check for empty diff.
729 * @return bool True iff two sequences were identical.
731 function isEmpty () {
732 foreach ($this->edits
as $edit) {
733 if ($edit->type
!= 'copy')
740 * Compute the length of the Longest Common Subsequence (LCS).
742 * This is mostly for diagnostic purposed.
744 * @return int The length of the LCS.
748 foreach ($this->edits
as $edit) {
749 if ($edit->type
== 'copy')
750 $lcs +
= sizeof($edit->orig
);
756 * Get the original set of lines.
758 * This reconstructs the $from_lines parameter passed to the
761 * @return array The original sequence of strings.
766 foreach ($this->edits
as $edit) {
768 array_splice($lines, sizeof($lines), 0, $edit->orig
);
774 * Get the closing set of lines.
776 * This reconstructs the $to_lines parameter passed to the
779 * @return array The sequence of strings.
784 foreach ($this->edits
as $edit) {
786 array_splice($lines, sizeof($lines), 0, $edit->closing
);
792 * Check a Diff for validity.
794 * This is here only for debugging purposes.
796 function _check ($from_lines, $to_lines) {
797 if (serialize($from_lines) != serialize($this->orig()))
798 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
799 if (serialize($to_lines) != serialize($this->closing()))
800 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
802 $rev = $this->reverse();
803 if (serialize($to_lines) != serialize($rev->orig()))
804 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
805 if (serialize($from_lines) != serialize($rev->closing()))
806 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
810 foreach ($this->edits
as $edit) {
811 if ( $prevtype == $edit->type
)
812 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
813 $prevtype = $edit->type
;
817 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
830 * Computes diff between sequences of strings.
832 * This can be used to compute things like
833 * case-insensitve diffs, or diffs which ignore
834 * changes in white-space.
836 * @param $from_lines array An array of strings.
837 * (Typically these are lines from a file.)
839 * @param $to_lines array An array of strings.
841 * @param $mapped_from_lines array This array should
842 * have the same size number of elements as $from_lines.
843 * The elements in $mapped_from_lines and
844 * $mapped_to_lines are what is actually compared
845 * when computing the diff.
847 * @param $mapped_to_lines array This array should
848 * have the same number of elements as $to_lines.
850 function MappedDiff($from_lines, $to_lines,
851 $mapped_from_lines, $mapped_to_lines) {
853 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
854 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
856 $this->Diff($mapped_from_lines, $mapped_to_lines);
859 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
860 $orig = &$this->edits
[$i]->orig
;
861 if (is_array($orig)) {
862 $orig = array_slice($from_lines, $xi, sizeof($orig));
863 $xi +
= sizeof($orig);
866 $closing = &$this->edits
[$i]->closing
;
867 if (is_array($closing)) {
868 $closing = array_slice($to_lines, $yi, sizeof($closing));
869 $yi +
= sizeof($closing);
876 * A class to format Diffs
878 * This class formats the diff in classic diff format.
879 * It is intended that this class be customized via inheritance,
880 * to obtain fancier outputs.
885 * Number of leading context "lines" to preserve.
887 * This should be left at zero for this class, but subclasses
888 * may want to set this to other values.
890 var $leading_context_lines = 0;
893 * Number of trailing context "lines" to preserve.
895 * This should be left at zero for this class, but subclasses
896 * may want to set this to other values.
898 var $trailing_context_lines = 0;
903 * @param $diff object A Diff object.
904 * @return string The formatted output.
906 function format($diff) {
912 $nlead = $this->leading_context_lines
;
913 $ntrail = $this->trailing_context_lines
;
915 $this->_start_diff();
917 foreach ($diff->edits
as $edit) {
918 if ($edit->type
== 'copy') {
919 if (is_array($block)) {
920 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
925 $context = array_slice($edit->orig
, 0, $ntrail);
926 $block[] = new _DiffOp_Copy($context);
928 $this->_block($x0, $ntrail +
$xi - $x0,
929 $y0, $ntrail +
$yi - $y0,
934 $context = $edit->orig
;
937 if (! is_array($block)) {
938 $context = array_slice($context, sizeof($context) - $nlead);
939 $x0 = $xi - sizeof($context);
940 $y0 = $yi - sizeof($context);
943 $block[] = new _DiffOp_Copy($context);
949 $xi +
= sizeof($edit->orig
);
951 $yi +
= sizeof($edit->closing
);
954 if (is_array($block))
955 $this->_block($x0, $xi - $x0,
959 return $this->_end_diff();
962 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
963 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
964 foreach ($edits as $edit) {
965 if ($edit->type
== 'copy')
966 $this->_context($edit->orig
);
967 elseif ($edit->type
== 'add')
968 $this->_added($edit->closing
);
969 elseif ($edit->type
== 'delete')
970 $this->_deleted($edit->orig
);
971 elseif ($edit->type
== 'change')
972 $this->_changed($edit->orig
, $edit->closing
);
974 trigger_error('Unknown edit type', E_USER_ERROR
);
979 function _start_diff() {
983 function _end_diff() {
984 $val = ob_get_contents();
989 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
991 $xbeg .= "," . ($xbeg +
$xlen - 1);
993 $ybeg .= "," . ($ybeg +
$ylen - 1);
995 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
998 function _start_block($header) {
1002 function _end_block() {
1005 function _lines($lines, $prefix = ' ') {
1006 foreach ($lines as $line)
1007 echo "$prefix $line\n";
1010 function _context($lines) {
1011 $this->_lines($lines);
1014 function _added($lines) {
1015 $this->_lines($lines, '>');
1017 function _deleted($lines) {
1018 $this->_lines($lines, '<');
1021 function _changed($orig, $closing) {
1022 $this->_deleted($orig);
1024 $this->_added($closing);
1030 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1034 define('NBSP', ' '); // iso-8859-x non-breaking space.
1036 class _HWLDF_WordAccumulator
{
1037 function _HWLDF_WordAccumulator () {
1038 $this->_lines
= array();
1044 function _flushGroup ($new_tag) {
1045 if ($this->_group
!== '') {
1046 if ($this->_tag
== 'mark')
1047 $this->_line
.= '<span class="diffchange">'.$this->_group
.'</span>';
1049 $this->_line
.= $this->_group
;
1052 $this->_tag
= $new_tag;
1055 function _flushLine ($new_tag) {
1056 $this->_flushGroup($new_tag);
1057 if ($this->_line
!= '')
1058 $this->_lines
[] = $this->_line
;
1062 function addWords ($words, $tag = '') {
1063 if ($tag != $this->_tag
)
1064 $this->_flushGroup($tag);
1066 foreach ($words as $word) {
1067 // new-line should only come as first char of word.
1070 if ($word[0] == "\n") {
1071 $this->_group
.= NBSP
;
1072 $this->_flushLine($tag);
1073 $word = substr($word, 1);
1075 assert(!strstr($word, "\n"));
1076 $this->_group
.= $word;
1080 function getLines() {
1081 $this->_flushLine('~done');
1082 return $this->_lines
;
1086 class WordLevelDiff
extends MappedDiff
1088 function WordLevelDiff ($orig_lines, $closing_lines) {
1089 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1090 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1093 $this->MappedDiff($orig_words, $closing_words,
1094 $orig_stripped, $closing_stripped);
1097 function _split($lines) {
1098 // FIXME: fix POSIX char class.
1099 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1100 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1101 implode("\n", $lines),
1103 return array(array(''), array(''));
1105 return array($m[0], $m[1]);
1109 $orig = new _HWLDF_WordAccumulator
;
1111 foreach ($this->edits
as $edit) {
1112 if ($edit->type
== 'copy')
1113 $orig->addWords($edit->orig
);
1114 elseif ($edit->orig
)
1115 $orig->addWords($edit->orig
, 'mark');
1117 return $orig->getLines();
1120 function closing () {
1121 $closing = new _HWLDF_WordAccumulator
;
1123 foreach ($this->edits
as $edit) {
1124 if ($edit->type
== 'copy')
1125 $closing->addWords($edit->closing
);
1126 elseif ($edit->closing
)
1127 $closing->addWords($edit->closing
, 'mark');
1129 return $closing->getLines();
1134 * Wikipedia Table style diff formatter.
1137 class TableDiffFormatter
extends DiffFormatter
1139 function TableDiffFormatter() {
1140 $this->leading_context_lines
= 2;
1141 $this->trailing_context_lines
= 2;
1144 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1145 $l1 = wfMsg( 'lineno', $xbeg );
1146 $l2 = wfMsg( 'lineno', $ybeg );
1148 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1149 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1153 function _start_block( $header ) {
1155 $wgOut->addHTML( $header );
1158 function _end_block() {
1161 function _lines( $lines, $prefix=' ', $color='white' ) {
1164 function addedLine( $line ) {
1165 return '<td>+</td><td class="diff-addedline">' .
1169 function deletedLine( $line ) {
1170 return '<td>-</td><td class="diff-deletedline">' .
1174 function emptyLine() {
1175 return '<td colspan="2"> </td>';
1178 function contextLine( $line ) {
1179 return '<td> </td><td class="diff-context">'.$line.'</td>';
1182 function _added($lines) {
1184 foreach ($lines as $line) {
1185 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1186 $this->addedLine( $line ) . "</tr>\n" );
1190 function _deleted($lines) {
1192 foreach ($lines as $line) {
1193 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1194 $this->emptyLine() . "</tr>\n" );
1198 function _context( $lines ) {
1200 foreach ($lines as $line) {
1201 $wgOut->addHTML( '<tr>' . $this->contextLine( $line ) .
1202 $this->contextLine( $line ) . "</tr>\n" );
1206 function _changed( $orig, $closing ) {
1208 $diff = new WordLevelDiff( $orig, $closing );
1209 $del = $diff->orig();
1210 $add = $diff->closing();
1212 while ( $line = array_shift( $del ) ) {
1213 $aline = array_shift( $add );
1214 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1215 $this->addedLine( $aline ) . "</tr>\n" );
1217 $this->_added( $add ); # If any leftovers