360e5f0170b9f8b0258b80afefa20cbdfa642eb4
5 * @subpackage DifferenceEngine
12 class DifferenceEngine
{
13 /* private */ var $mOldid, $mNewid;
14 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
15 /* private */ var $mOldtext, $mNewtext;
16 /* private */ var $mOldUser, $mNewUser;
17 /* private */ var $mOldComment, $mNewComment;
18 /* private */ var $mOldPage, $mNewPage;
19 /* private */ var $mRcidMarkPatrolled;
21 function DifferenceEngine( $old, $new, $rcid = 0 )
24 if ( 'prev' == $new ) {
25 # Show diff between revision $old and the previous one.
26 # Get previous one from DB.
28 $this->mNewid
= intval($old);
30 $this->mOldid
= $wgTitle->getPreviousRevisionID( $this->mNewid
);
32 } elseif ( 'next' == $new ) {
34 # Show diff between revision $old and the previous one.
35 # Get previous one from DB.
37 $this->mOldid
= intval($old);
38 $this->mNewid
= $wgTitle->getNextRevisionID( $this->mOldid
);
39 if ( false === $this->mNewid
) {
40 # if no result, NewId points to the newest old revision. The only newer
41 # revision is cur, which is "0".
47 $this->mOldid
= intval($old);
48 $this->mNewid
= intval($new);
50 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
53 function showDiffPage()
55 global $wgUser, $wgTitle, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
56 $fname = 'DifferenceEngine::showDiffPage';
57 wfProfileIn( $fname );
59 # mOldid is false if the difference engine is called with a "vague" query for
60 # a diff between a version V and its previous version V' AND the version V
61 # is the first version of that article. In that case, V' does not exist.
62 if ( $this->mOldid
=== false ) {
63 $this->showFirstRevision();
64 wfProfileOut( $fname );
68 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
70 $mtext = wfMsg( 'missingarticle', $t );
72 $wgOut->setArticleFlag( false );
73 if ( ! $this->loadText() ) {
74 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
75 $wgOut->addHTML( $mtext );
76 wfProfileOut( $fname );
79 $wgOut->suppressQuickbar();
81 $oldTitle = $this->mOldPage
->getPrefixedText();
82 $newTitle = $this->mNewPage
->getPrefixedText();
83 if( $oldTitle == $newTitle ) {
84 $wgOut->setPageTitle( $newTitle );
86 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
88 $wgOut->setSubtitle( wfMsg( 'difference' ) );
89 $wgOut->setRobotpolicy( 'noindex,follow' );
91 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
94 wfProfileOut( $fname );
98 $sk = $wgUser->getSkin();
99 $talk = $wgContLang->getNsText( NS_TALK
);
100 $contribs = wfMsg( 'contribslink' );
102 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
103 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
105 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
106 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
107 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
108 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
109 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
110 'target=' . urlencode($this->mOldUser
) );
111 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
112 'target=' . urlencode($this->mNewUser
) );
113 if ( !$this->mNewid
&& $wgUser->isAllowed('rollback') ) {
114 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
115 'action=rollback&from=' . urlencode($this->mNewUser
) ) . ']</strong>';
119 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->getID() != 0 &&
120 ( $wgUser->isAllowed('rollback') ||
!$wgOnlySysopsCanPatrol ) )
122 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
123 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
128 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid
);
129 if ( $this->mNewid
== 0 ) {
132 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
135 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
136 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
137 '<br />' . $prevlink;
138 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
139 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
140 '<br />' . $nextlink . $patrol;
142 DifferenceEngine
::showDiff( $this->mOldtext
, $this->mNewtext
,
143 $oldHeader, $newHeader );
144 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
145 $wgOut->addWikiText( $this->mNewtext
);
147 wfProfileOut( $fname );
150 # Show the first revision of an article. Uses normal diff headers in contrast to normal
151 # "old revision" display style.
153 function showFirstRevision()
155 global $wgOut, $wgTitle, $wgUser, $wgLang;
157 $fname = 'DifferenceEngine::showFirstRevision';
158 wfProfileIn( $fname );
161 $this->mOldid
= $this->mNewid
; # hack to make loadText() work.
163 # Get article text from the DB
165 if ( ! $this->loadText() ) {
166 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
168 $mtext = wfMsg( 'missingarticle', $t );
169 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
170 $wgOut->addHTML( $mtext );
171 wfProfileOut( $fname );
175 # Check if user is allowed to look at this page. If not, bail out.
177 if ( !( $this->mOldPage
->userCanRead() ) ) {
178 $wgOut->loginToUse();
180 wfProfileOut( $fname );
184 # Prepare the header box
186 $sk = $wgUser->getSkin();
188 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
189 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
190 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
191 'target=' . urlencode($this->mOldUser
) );
192 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
);
193 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
194 "($uTLink | $contribs)<br />" . $this->mOldComment
.
195 '<br />' . $nextlink. "</div>\n";
197 $wgOut->addHTML( $header );
199 $wgOut->setSubtitle( wfMsg( 'difference' ) );
200 $wgOut->setRobotpolicy( 'noindex,follow' );
203 # Show current revision
205 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
206 $wgOut->addWikiText( $this->mNewtext
);
208 wfProfileOut( $fname );
211 function showDiff( $otext, $ntext, $otitle, $ntitle )
214 $wgOut->addHTML( DifferenceEngine
::getDiff( $otext, $ntext, $otitle, $ntitle ) );
217 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
218 global $wgUseExternalDiffEngine, $wgContLang;
220 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
222 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
223 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
226 $otext = $wgContLang->segmentForDiff($otext);
227 $ntext = $wgContLang->segmentForDiff($ntext);
229 if ( $wgUseExternalDiffEngine ) {
230 # For historical reasons, external diff engine expects
231 # input text to be HTML-escaped already
232 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
233 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
234 if( !function_exists( 'wikidiff_do_diff' ) ) {
235 dl('php_wikidiff.so');
237 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
239 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
240 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
241 $diffs =& new Diff( $ota, $nta );
242 $formatter =& new TableDiffFormatter();
243 $difftext = $formatter->format( $diffs );
245 $difftext = $wgContLang->unsegmentForDiff($difftext);
246 $out .= $difftext."</table>\n";
250 # Load the text of the articles to compare. If newid is 0, then compare
251 # the old article in oldid to the current article; if oldid is 0, then
252 # compare the current article to the immediately previous one (ignoring
253 # the value of newid).
257 global $wgTitle, $wgOut, $wgLang;
258 $fname = 'DifferenceEngine::loadText';
260 $dbr =& wfGetDB( DB_SLAVE
);
261 if ( 0 == $this->mNewid ||
0 == $this->mOldid
) {
262 /* Fetch current revision */
263 $wgOut->setArticleFlag( true );
264 $newLink = $wgTitle->escapeLocalUrl();
265 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
266 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
267 $id = $wgTitle->getArticleID();
269 $s = $dbr->selectRow( array( 'page', 'revision', 'text' ),
270 array( 'old_flags', 'old_text', 'rev_user_text', 'rev_comment' ),
271 "page_id=$id AND page_id=rev_page AND rev_id=old_id", $fname );
272 if ( $s === false ) {
273 wfDebug( "Unable to load page_id $id\n" );
277 $this->mNewPage
= &$wgTitle;
278 $this->mNewtext
= Article
::getRevisionText( $s );
279 $this->mNewUser
= $s->rev_user_text
;
280 $this->mNewComment
= $s->rev_comment
;
282 $s = $dbr->selectRow( array( 'page', 'revision', 'text' ),
283 array( 'page_namespace','page_title','rev_timestamp', 'old_text',
284 'old_flags','rev_user_text','rev_comment' ),
285 "page_id=rev_page AND rev_id=old_id AND rev_id={$this->mNewid}",
288 if ( $s === false ) {
289 wfDebug( "Unable to load old_id {$this->mNewid}\n" );
293 $this->mNewtext
= Article
::getRevisionText( $s );
295 $t = $wgLang->timeanddate( $s->rev_timestamp
, true );
296 $this->mNewPage
= Title
::MakeTitle( $s->page_namespace
, $s->page_title
);
297 $newLink = $wgTitle->escapeLocalUrl ('oldid=' . $this->mNewid
);
298 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
299 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
300 $this->mNewUser
= $s->rev_user_text
;
301 $this->mNewComment
= $s->rev_comment
;
303 if ( 0 == $this->mOldid
) {
304 $s = $dbr->selectRow( 'old',
305 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
307 'old_namespace' => $this->mNewPage
->getNamespace(),
308 'old_title' => $this->mNewPage
->getDBkey()
309 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
311 if ( $s === false ) {
312 wfDebug( 'Unable to load ' . $this->mNewPage
->getPrefixedDBkey() . " from old\n" );
316 $s = $dbr->selectRow( array( 'page', 'revision', 'text' ),
317 array( 'page_namespace','page_title','rev_timestamp','old_text','old_flags','rev_user_text','rev_comment'),
318 "page_id=rev_page AND rev_id=old_id AND rev_id={$this->mOldid}",
321 if ( $s === false ) {
322 wfDebug( "Unable to load old_id {$this->mOldid}\n" );
326 $this->mOldPage
= Title
::MakeTitle( $s->page_namespace
, $s->page_title
);
327 $this->mOldtext
= Article
::getRevisionText( $s );
329 $t = $wgLang->timeanddate( $s->rev_timestamp
, true );
330 $oldLink = $this->mOldPage
->escapeLocalUrl ('oldid=' . $this->mOldid
);
331 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
332 $this->mOldUser
= $s->rev_user_text
;
333 $this->mOldComment
= $s->rev_comment
;
339 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
341 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
342 // You may copy this code freely under the conditions of the GPL.
345 define('USE_ASSERTS', function_exists('assert'));
357 trigger_error('pure virtual', E_USER_ERROR
);
361 return $this->orig ?
sizeof($this->orig
) : 0;
364 function nclosing() {
365 return $this->closing ?
sizeof($this->closing
) : 0;
373 class _DiffOp_Copy
extends _DiffOp
{
376 function _DiffOp_Copy ($orig, $closing = false) {
377 if (!is_array($closing))
380 $this->closing
= $closing;
384 return new _DiffOp_Copy($this->closing
, $this->orig
);
392 class _DiffOp_Delete
extends _DiffOp
{
393 var $type = 'delete';
395 function _DiffOp_Delete ($lines) {
396 $this->orig
= $lines;
397 $this->closing
= false;
401 return new _DiffOp_Add($this->orig
);
409 class _DiffOp_Add
extends _DiffOp
{
412 function _DiffOp_Add ($lines) {
413 $this->closing
= $lines;
418 return new _DiffOp_Delete($this->closing
);
426 class _DiffOp_Change
extends _DiffOp
{
427 var $type = 'change';
429 function _DiffOp_Change ($orig, $closing) {
431 $this->closing
= $closing;
435 return new _DiffOp_Change($this->closing
, $this->orig
);
441 * Class used internally by Diff to actually compute the diffs.
443 * The algorithm used here is mostly lifted from the perl module
444 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
445 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
447 * More ideas are taken from:
448 * http://www.ics.uci.edu/~eppstein/161/960229.html
450 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
451 * diffutils-2.7, which can be found at:
452 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
454 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
457 * @author Geoffrey T. Dairiki
462 function diff ($from_lines, $to_lines) {
463 $fname = '_DiffEngine::diff';
464 wfProfileIn( $fname );
466 $n_from = sizeof($from_lines);
467 $n_to = sizeof($to_lines);
469 $this->xchanged
= $this->ychanged
= array();
470 $this->xv
= $this->yv
= array();
471 $this->xind
= $this->yind
= array();
473 unset($this->in_seq
);
476 // Skip leading common lines.
477 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
478 if ($from_lines[$skip] != $to_lines[$skip])
480 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
482 // Skip trailing common lines.
483 $xi = $n_from; $yi = $n_to;
484 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
485 if ($from_lines[$xi] != $to_lines[$yi])
487 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
490 // Ignore lines which do not exist in both files.
491 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
)
492 $xhash[$from_lines[$xi]] = 1;
493 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
494 $line = $to_lines[$yi];
495 if ( ($this->ychanged
[$yi] = empty($xhash[$line])) )
501 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
502 $line = $from_lines[$xi];
503 if ( ($this->xchanged
[$xi] = empty($yhash[$line])) )
510 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
512 // Merge edits when possible
513 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
514 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
516 // Compute the edit operations.
519 while ($xi < $n_from ||
$yi < $n_to) {
520 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
521 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
523 // Skip matching "snake".
525 while ( $xi < $n_from && $yi < $n_to
526 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
527 $copy[] = $from_lines[$xi++
];
531 $edits[] = new _DiffOp_Copy($copy);
533 // Find deletes & adds.
535 while ($xi < $n_from && $this->xchanged
[$xi])
536 $delete[] = $from_lines[$xi++
];
539 while ($yi < $n_to && $this->ychanged
[$yi])
540 $add[] = $to_lines[$yi++
];
543 $edits[] = new _DiffOp_Change($delete, $add);
545 $edits[] = new _DiffOp_Delete($delete);
547 $edits[] = new _DiffOp_Add($add);
549 wfProfileOut( $fname );
554 /* Divide the Largest Common Subsequence (LCS) of the sequences
555 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
558 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
559 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
560 * sub sequences. The first sub-sequence is contained in [X0, X1),
561 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
562 * that (X0, Y0) == (XOFF, YOFF) and
563 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
565 * This function assumes that the first lines of the specified portions
566 * of the two files do not match, and likewise that the last lines do not
567 * match. The caller must trim matching lines from the beginning and end
568 * of the portions it is going to specify.
570 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
571 $fname = '_DiffEngine::_diag';
572 wfProfileIn( $fname );
575 if ($xlim - $xoff > $ylim - $yoff) {
576 // Things seems faster (I'm not sure I understand why)
577 // when the shortest sequence in X.
579 list ($xoff, $xlim, $yoff, $ylim)
580 = array( $yoff, $ylim, $xoff, $xlim);
584 for ($i = $ylim - 1; $i >= $yoff; $i--)
585 $ymatches[$this->xv
[$i]][] = $i;
587 for ($i = $ylim - 1; $i >= $yoff; $i--)
588 $ymatches[$this->yv
[$i]][] = $i;
591 $this->seq
[0]= $yoff - 1;
592 $this->in_seq
= array();
595 $numer = $xlim - $xoff +
$nchunks - 1;
597 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
598 wfProfileIn( "$fname-chunk" );
600 for ($i = 0; $i <= $this->lcs
; $i++
)
601 $ymids[$i][$chunk-1] = $this->seq
[$i];
603 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
604 for ( ; $x < $x1; $x++
) {
605 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
606 if (empty($ymatches[$line]))
608 $matches = $ymatches[$line];
610 while (list ($junk, $y) = each($matches))
611 if (empty($this->in_seq
[$y])) {
612 $k = $this->_lcs_pos($y);
613 USE_ASSERTS
&& assert($k > 0);
614 $ymids[$k] = $ymids[$k-1];
617 while (list ($junk, $y) = each($matches)) {
618 if ($y > $this->seq
[$k-1]) {
619 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
620 // Optimization: this is a common case:
621 // next match is just replacing previous match.
622 $this->in_seq
[$this->seq
[$k]] = false;
624 $this->in_seq
[$y] = 1;
625 } else if (empty($this->in_seq
[$y])) {
626 $k = $this->_lcs_pos($y);
627 USE_ASSERTS
&& assert($k > 0);
628 $ymids[$k] = $ymids[$k-1];
632 wfProfileOut( "$fname-chunk" );
635 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
636 $ymid = $ymids[$this->lcs
];
637 for ($n = 0; $n < $nchunks - 1; $n++
) {
638 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
640 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
642 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
644 wfProfileOut( $fname );
645 return array($this->lcs
, $seps);
648 function _lcs_pos ($ypos) {
649 $fname = '_DiffEngine::_lcs_pos';
650 wfProfileIn( $fname );
653 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
654 $this->seq
[++
$this->lcs
] = $ypos;
655 $this->in_seq
[$ypos] = 1;
656 wfProfileOut( $fname );
661 while ($beg < $end) {
662 $mid = (int)(($beg +
$end) / 2);
663 if ( $ypos > $this->seq
[$mid] )
669 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
671 $this->in_seq
[$this->seq
[$end]] = false;
672 $this->seq
[$end] = $ypos;
673 $this->in_seq
[$ypos] = 1;
674 wfProfileOut( $fname );
678 /* Find LCS of two sequences.
680 * The results are recorded in the vectors $this->{x,y}changed[], by
681 * storing a 1 in the element for each line that is an insertion
682 * or deletion (ie. is not in the LCS).
684 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
686 * Note that XLIM, YLIM are exclusive bounds.
687 * All line numbers are origin-0 and discarded lines are not counted.
689 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
690 $fname = '_DiffEngine::_compareseq';
691 wfProfileIn( $fname );
693 // Slide down the bottom initial diagonal.
694 while ($xoff < $xlim && $yoff < $ylim
695 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
700 // Slide up the top initial diagonal.
701 while ($xlim > $xoff && $ylim > $yoff
702 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
707 if ($xoff == $xlim ||
$yoff == $ylim)
710 // This is ad hoc but seems to work well.
711 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
712 //$nchunks = max(2,min(8,(int)$nchunks));
713 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
715 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
719 // X and Y sequences have no common subsequence:
721 while ($yoff < $ylim)
722 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
723 while ($xoff < $xlim)
724 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
726 // Use the partitions to split this problem into subproblems.
729 while ($pt2 = next($seps)) {
730 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
734 wfProfileOut( $fname );
737 /* Adjust inserts/deletes of identical lines to join changes
738 * as much as possible.
740 * We do something when a run of changed lines include a
741 * line at one end and has an excluded, identical line at the other.
742 * We are free to choose which identical line is included.
743 * `compareseq' usually chooses the one at the beginning,
744 * but usually it is cleaner to consider the following identical line
745 * to be the "change".
747 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
749 function _shift_boundaries ($lines, &$changed, $other_changed) {
750 $fname = '_DiffEngine::_shift_boundaries';
751 wfProfileIn( $fname );
755 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
756 $len = sizeof($lines);
757 $other_len = sizeof($other_changed);
761 * Scan forwards to find beginning of another run of changes.
762 * Also keep track of the corresponding point in the other file.
764 * Throughout this code, $i and $j are adjusted together so that
765 * the first $i elements of $changed and the first $j elements
766 * of $other_changed both contain the same number of zeros
768 * Furthermore, $j is always kept so that $j == $other_len or
769 * $other_changed[$j] == false.
771 while ($j < $other_len && $other_changed[$j])
774 while ($i < $len && ! $changed[$i]) {
775 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
777 while ($j < $other_len && $other_changed[$j])
786 // Find the end of this run of changes.
787 while (++
$i < $len && $changed[$i])
792 * Record the length of this run of changes, so that
793 * we can later determine whether the run has grown.
795 $runlength = $i - $start;
798 * Move the changed region back, so long as the
799 * previous unchanged line matches the last changed one.
800 * This merges with previous changed regions.
802 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
803 $changed[--$start] = 1;
804 $changed[--$i] = false;
805 while ($start > 0 && $changed[$start - 1])
807 USE_ASSERTS
&& assert('$j > 0');
808 while ($other_changed[--$j])
810 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
814 * Set CORRESPONDING to the end of the changed run, at the last
815 * point where it corresponds to a changed run in the other file.
816 * CORRESPONDING == LEN means no such point has been found.
818 $corresponding = $j < $other_len ?
$i : $len;
821 * Move the changed region forward, so long as the
822 * first changed line matches the following unchanged one.
823 * This merges with following changed regions.
824 * Do this second, so that if there are no merges,
825 * the changed region is moved forward as far as possible.
827 while ($i < $len && $lines[$start] == $lines[$i]) {
828 $changed[$start++
] = false;
830 while ($i < $len && $changed[$i])
833 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
835 if ($j < $other_len && $other_changed[$j]) {
837 while ($j < $other_len && $other_changed[$j])
841 } while ($runlength != $i - $start);
844 * If possible, move the fully-merged run of changes
845 * back to a corresponding run in the other file.
847 while ($corresponding < $i) {
848 $changed[--$start] = 1;
850 USE_ASSERTS
&& assert('$j > 0');
851 while ($other_changed[--$j])
853 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
856 wfProfileOut( $fname );
861 * Class representing a 'diff' between two sequences of strings.
871 * Computes diff between sequences of strings.
873 * @param $from_lines array An array of strings.
874 * (Typically these are lines from a file.)
875 * @param $to_lines array An array of strings.
877 function Diff($from_lines, $to_lines) {
878 $eng = new _DiffEngine
;
879 $this->edits
= $eng->diff($from_lines, $to_lines);
880 //$this->_check($from_lines, $to_lines);
884 * Compute reversed Diff.
888 * $diff = new Diff($lines1, $lines2);
889 * $rev = $diff->reverse();
890 * @return object A Diff object representing the inverse of the
893 function reverse () {
895 $rev->edits
= array();
896 foreach ($this->edits
as $edit) {
897 $rev->edits
[] = $edit->reverse();
903 * Check for empty diff.
905 * @return bool True iff two sequences were identical.
907 function isEmpty () {
908 foreach ($this->edits
as $edit) {
909 if ($edit->type
!= 'copy')
916 * Compute the length of the Longest Common Subsequence (LCS).
918 * This is mostly for diagnostic purposed.
920 * @return int The length of the LCS.
924 foreach ($this->edits
as $edit) {
925 if ($edit->type
== 'copy')
926 $lcs +
= sizeof($edit->orig
);
932 * Get the original set of lines.
934 * This reconstructs the $from_lines parameter passed to the
937 * @return array The original sequence of strings.
942 foreach ($this->edits
as $edit) {
944 array_splice($lines, sizeof($lines), 0, $edit->orig
);
950 * Get the closing set of lines.
952 * This reconstructs the $to_lines parameter passed to the
955 * @return array The sequence of strings.
960 foreach ($this->edits
as $edit) {
962 array_splice($lines, sizeof($lines), 0, $edit->closing
);
968 * Check a Diff for validity.
970 * This is here only for debugging purposes.
972 function _check ($from_lines, $to_lines) {
973 $fname = 'Diff::_check';
974 wfProfileIn( $fname );
975 if (serialize($from_lines) != serialize($this->orig()))
976 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
977 if (serialize($to_lines) != serialize($this->closing()))
978 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
980 $rev = $this->reverse();
981 if (serialize($to_lines) != serialize($rev->orig()))
982 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
983 if (serialize($from_lines) != serialize($rev->closing()))
984 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
988 foreach ($this->edits
as $edit) {
989 if ( $prevtype == $edit->type
)
990 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
991 $prevtype = $edit->type
;
995 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
996 wfProfileOut( $fname );
1005 class MappedDiff
extends Diff
1010 * Computes diff between sequences of strings.
1012 * This can be used to compute things like
1013 * case-insensitve diffs, or diffs which ignore
1014 * changes in white-space.
1016 * @param $from_lines array An array of strings.
1017 * (Typically these are lines from a file.)
1019 * @param $to_lines array An array of strings.
1021 * @param $mapped_from_lines array This array should
1022 * have the same size number of elements as $from_lines.
1023 * The elements in $mapped_from_lines and
1024 * $mapped_to_lines are what is actually compared
1025 * when computing the diff.
1027 * @param $mapped_to_lines array This array should
1028 * have the same number of elements as $to_lines.
1030 function MappedDiff($from_lines, $to_lines,
1031 $mapped_from_lines, $mapped_to_lines) {
1032 $fname = 'MappedDiff::MappedDiff';
1033 wfProfileIn( $fname );
1035 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1036 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1038 $this->Diff($mapped_from_lines, $mapped_to_lines);
1041 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1042 $orig = &$this->edits
[$i]->orig
;
1043 if (is_array($orig)) {
1044 $orig = array_slice($from_lines, $xi, sizeof($orig));
1045 $xi +
= sizeof($orig);
1048 $closing = &$this->edits
[$i]->closing
;
1049 if (is_array($closing)) {
1050 $closing = array_slice($to_lines, $yi, sizeof($closing));
1051 $yi +
= sizeof($closing);
1054 wfProfileOut( $fname );
1059 * A class to format Diffs
1061 * This class formats the diff in classic diff format.
1062 * It is intended that this class be customized via inheritance,
1063 * to obtain fancier outputs.
1070 * Number of leading context "lines" to preserve.
1072 * This should be left at zero for this class, but subclasses
1073 * may want to set this to other values.
1075 var $leading_context_lines = 0;
1078 * Number of trailing context "lines" to preserve.
1080 * This should be left at zero for this class, but subclasses
1081 * may want to set this to other values.
1083 var $trailing_context_lines = 0;
1088 * @param $diff object A Diff object.
1089 * @return string The formatted output.
1091 function format($diff) {
1092 $fname = 'DiffFormatter::format';
1093 wfProfileIn( $fname );
1099 $nlead = $this->leading_context_lines
;
1100 $ntrail = $this->trailing_context_lines
;
1102 $this->_start_diff();
1104 foreach ($diff->edits
as $edit) {
1105 if ($edit->type
== 'copy') {
1106 if (is_array($block)) {
1107 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1112 $context = array_slice($edit->orig
, 0, $ntrail);
1113 $block[] = new _DiffOp_Copy($context);
1115 $this->_block($x0, $ntrail +
$xi - $x0,
1116 $y0, $ntrail +
$yi - $y0,
1121 $context = $edit->orig
;
1124 if (! is_array($block)) {
1125 $context = array_slice($context, sizeof($context) - $nlead);
1126 $x0 = $xi - sizeof($context);
1127 $y0 = $yi - sizeof($context);
1130 $block[] = new _DiffOp_Copy($context);
1136 $xi +
= sizeof($edit->orig
);
1138 $yi +
= sizeof($edit->closing
);
1141 if (is_array($block))
1142 $this->_block($x0, $xi - $x0,
1146 $end = $this->_end_diff();
1147 wfProfileOut( $fname );
1151 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1152 $fname = 'DiffFormatter::_block';
1153 wfProfileIn( $fname );
1154 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1155 foreach ($edits as $edit) {
1156 if ($edit->type
== 'copy')
1157 $this->_context($edit->orig
);
1158 elseif ($edit->type
== 'add')
1159 $this->_added($edit->closing
);
1160 elseif ($edit->type
== 'delete')
1161 $this->_deleted($edit->orig
);
1162 elseif ($edit->type
== 'change')
1163 $this->_changed($edit->orig
, $edit->closing
);
1165 trigger_error('Unknown edit type', E_USER_ERROR
);
1167 $this->_end_block();
1168 wfProfileOut( $fname );
1171 function _start_diff() {
1175 function _end_diff() {
1176 $val = ob_get_contents();
1181 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1183 $xbeg .= "," . ($xbeg +
$xlen - 1);
1185 $ybeg .= "," . ($ybeg +
$ylen - 1);
1187 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1190 function _start_block($header) {
1194 function _end_block() {
1197 function _lines($lines, $prefix = ' ') {
1198 foreach ($lines as $line)
1199 echo "$prefix $line\n";
1202 function _context($lines) {
1203 $this->_lines($lines);
1206 function _added($lines) {
1207 $this->_lines($lines, '>');
1209 function _deleted($lines) {
1210 $this->_lines($lines, '<');
1213 function _changed($orig, $closing) {
1214 $this->_deleted($orig);
1216 $this->_added($closing);
1222 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1226 define('NBSP', ' '); // iso-8859-x non-breaking space.
1232 class _HWLDF_WordAccumulator
{
1233 function _HWLDF_WordAccumulator () {
1234 $this->_lines
= array();
1240 function _flushGroup ($new_tag) {
1241 if ($this->_group
!== '') {
1242 if ($this->_tag
== 'mark')
1243 $this->_line
.= '<span class="diffchange">' .
1244 htmlspecialchars ( $this->_group
) . '</span>';
1246 $this->_line
.= htmlspecialchars ( $this->_group
);
1249 $this->_tag
= $new_tag;
1252 function _flushLine ($new_tag) {
1253 $this->_flushGroup($new_tag);
1254 if ($this->_line
!= '')
1255 array_push ( $this->_lines
, $this->_line
);
1257 # make empty lines visible by inserting an NBSP
1258 array_push ( $this->_lines
, NBSP
);
1262 function addWords ($words, $tag = '') {
1263 if ($tag != $this->_tag
)
1264 $this->_flushGroup($tag);
1266 foreach ($words as $word) {
1267 // new-line should only come as first char of word.
1270 if ($word[0] == "\n") {
1271 $this->_flushLine($tag);
1272 $word = substr($word, 1);
1274 assert(!strstr($word, "\n"));
1275 $this->_group
.= $word;
1279 function getLines() {
1280 $this->_flushLine('~done');
1281 return $this->_lines
;
1289 class WordLevelDiff
extends MappedDiff
1291 function WordLevelDiff ($orig_lines, $closing_lines) {
1292 $fname = 'WordLevelDiff::WordLevelDiff';
1293 wfProfileIn( $fname );
1295 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1296 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1299 $this->MappedDiff($orig_words, $closing_words,
1300 $orig_stripped, $closing_stripped);
1301 wfProfileOut( $fname );
1304 function _split($lines) {
1305 $fname = 'WordLevelDiff::_split';
1306 wfProfileIn( $fname );
1307 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1308 implode("\n", $lines),
1310 wfProfileOut( $fname );
1311 return array(array(''), array(''));
1313 wfProfileOut( $fname );
1314 return array($m[0], $m[1]);
1318 $fname = 'WordLevelDiff::orig';
1319 wfProfileIn( $fname );
1320 $orig = new _HWLDF_WordAccumulator
;
1322 foreach ($this->edits
as $edit) {
1323 if ($edit->type
== 'copy')
1324 $orig->addWords($edit->orig
);
1325 elseif ($edit->orig
)
1326 $orig->addWords($edit->orig
, 'mark');
1328 $lines = $orig->getLines();
1329 wfProfileOut( $fname );
1333 function closing () {
1334 $fname = 'WordLevelDiff::closing';
1335 wfProfileIn( $fname );
1336 $closing = new _HWLDF_WordAccumulator
;
1338 foreach ($this->edits
as $edit) {
1339 if ($edit->type
== 'copy')
1340 $closing->addWords($edit->closing
);
1341 elseif ($edit->closing
)
1342 $closing->addWords($edit->closing
, 'mark');
1344 $lines = $closing->getLines();
1345 wfProfileOut( $fname );
1351 * Wikipedia Table style diff formatter.
1355 class TableDiffFormatter
extends DiffFormatter
1357 function TableDiffFormatter() {
1358 $this->leading_context_lines
= 2;
1359 $this->trailing_context_lines
= 2;
1362 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1363 $l1 = wfMsg( 'lineno', $xbeg );
1364 $l2 = wfMsg( 'lineno', $ybeg );
1366 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1367 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1371 function _start_block( $header ) {
1376 function _end_block() {
1379 function _lines( $lines, $prefix=' ', $color='white' ) {
1382 # HTML-escape parameter before calling this
1383 function addedLine( $line ) {
1384 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1387 # HTML-escape parameter before calling this
1388 function deletedLine( $line ) {
1389 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1392 # HTML-escape parameter before calling this
1393 function contextLine( $line ) {
1394 return "<td> </td><td class='diff-context'>{$line}</td>";
1397 function emptyLine() {
1398 return '<td colspan="2"> </td>';
1401 function _added( $lines ) {
1402 foreach ($lines as $line) {
1403 echo '<tr>' . $this->emptyLine() .
1404 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1408 function _deleted($lines) {
1409 foreach ($lines as $line) {
1410 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1411 $this->emptyLine() . "</tr>\n";
1415 function _context( $lines ) {
1416 foreach ($lines as $line) {
1418 $this->contextLine( htmlspecialchars ( $line ) ) .
1419 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1423 function _changed( $orig, $closing ) {
1424 $fname = 'TableDiffFormatter::_changed';
1425 wfProfileIn( $fname );
1427 $diff = new WordLevelDiff( $orig, $closing );
1428 $del = $diff->orig();
1429 $add = $diff->closing();
1431 # Notice that WordLevelDiff returns HTML-escaped output.
1432 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1434 while ( $line = array_shift( $del ) ) {
1435 $aline = array_shift( $add );
1436 echo '<tr>' . $this->deletedLine( $line ) .
1437 $this->addedLine( $aline ) . "</tr>\n";
1439 foreach ($add as $line) { # If any leftovers
1440 echo '<tr>' . $this->emptyLine() .
1441 $this->addedLine( $line ) . "</tr>\n";
1443 wfProfileOut( $fname );