5 * @subpackage DifferenceEngine
9 require_once( 'Revision.php' );
11 define( 'MAX_DIFF_LINE', 10000 );
12 define( 'MAX_DIFF_XREF_LENGTH', 10000 );
18 * @subpackage DifferenceEngine
20 class DifferenceEngine
{
24 var $mOldid, $mNewid, $mTitle;
25 var $mOldtitle, $mNewtitle, $mPagetitle;
26 var $mOldtext, $mNewtext;
27 var $mOldUser, $mNewUser;
28 var $mOldComment, $mNewComment;
29 var $mOldPage, $mNewPage;
30 var $mRcidMarkPatrolled;
31 var $mOldRev, $mNewRev;
32 var $mRevisionsLoaded = false; // Have the revisions been loaded
33 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
38 * @param Title $titleObj Title object that the diff is associated with
39 * @param integer $old Old ID we want to show and diff with.
40 * @param string $new Either 'prev' or 'next'.
41 * @param integer $rcid ??? (default 0)
43 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
44 $this->mTitle
= $titleObj;
46 if ( 'prev' == $new ) {
47 # Show diff between revision $old and the previous one.
48 # Get previous one from DB.
50 $this->mNewid
= intval($old);
52 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
54 } elseif ( 'next' == $new ) {
55 # Show diff between revision $old and the previous one.
56 # Get previous one from DB.
58 $this->mOldid
= intval($old);
59 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
60 if ( false === $this->mNewid
) {
61 # if no result, NewId points to the newest old revision. The only newer
62 # revision is cur, which is "0".
67 $this->mOldid
= intval($old);
68 $this->mNewid
= intval($new);
70 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
73 function showDiffPage() {
74 global $wgUser, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol,
75 $wgUseExternalEditor, $wgUseRCPatrol;
76 $fname = 'DifferenceEngine::showDiffPage';
77 wfProfileIn( $fname );
79 # If external diffs are enabled both globally and for the user,
80 # we'll use the application/x-external-editor interface to call
81 # an external diff tool like kompare, kdiff3, etc.
82 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
83 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
85 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
86 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
87 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
88 $special=$wgLang->getNsText(NS_SPECIAL
);
93 Script={$wgServer}{$wgScript}
94 Special namespace={$special}
108 # mOldid is false if the difference engine is called with a "vague" query for
109 # a diff between a version V and its previous version V' AND the version V
110 # is the first version of that article. In that case, V' does not exist.
111 if ( $this->mOldid
=== false ) {
112 $this->showFirstRevision();
113 wfProfileOut( $fname );
117 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
119 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
121 $wgOut->setArticleFlag( false );
122 if ( ! $this->loadRevisionData() ) {
123 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
124 $wgOut->addWikitext( $mtext );
125 wfProfileOut( $fname );
128 if ( $this->mNewRev
->isCurrent() ) {
129 $wgOut->setArticleFlag( true );
132 $wgOut->suppressQuickbar();
134 $oldTitle = $this->mOldPage
->getPrefixedText();
135 $newTitle = $this->mNewPage
->getPrefixedText();
136 if( $oldTitle == $newTitle ) {
137 $wgOut->setPageTitle( $newTitle );
139 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
141 $wgOut->setSubtitle( wfMsg( 'difference' ) );
142 $wgOut->setRobotpolicy( 'noindex,follow' );
144 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
145 $wgOut->loginToUse();
147 wfProfileOut( $fname );
151 $sk = $wgUser->getSkin();
152 $talk = $wgContLang->getNsText( NS_TALK
);
153 $contribs = wfMsg( 'contribslink' );
155 $this->mOldComment
= $sk->formatComment($this->mOldComment
);
156 $this->mNewComment
= $sk->formatComment($this->mNewComment
);
158 $oldUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
159 $newUserLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mNewUser
), $this->mNewUser
);
160 $oldUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $talk );
161 $newUTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mNewUser
), $talk );
162 $oldContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
163 'target=' . urlencode($this->mOldUser
) );
164 $newContribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), $contribs,
165 'target=' . urlencode($this->mNewUser
) );
166 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
167 $rollback = ' <strong>[' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'rollbacklink' ),
168 'action=rollback&from=' . urlencode($this->mNewUser
) .
169 '&token=' . urlencode( $wgUser->editToken( array( $this->mTitle
->getPrefixedText(), $this->mNewUser
) ) ) ) .
174 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isLoggedIn() &&
175 ( $wgUser->isAllowed('rollback') ||
!$wgOnlySysopsCanPatrol ) )
177 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'markaspatrolleddiff' ),
178 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
183 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
184 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
185 if ( $this->mNewRev
->isCurrent() ) {
188 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
189 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
192 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
193 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment
.
194 '<br />' . $prevlink;
195 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
196 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment
.
197 '<br />' . $nextlink . $patrol;
199 $this->showDiff( $oldHeader, $newHeader );
200 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
202 if( !$this->mNewRev
->isCurrent() ) {
203 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
206 $this->loadNewText();
207 if( is_object( $this->mNewRev
) ) {
208 $wgOut->setRevisionId( $this->mNewRev
->getId() );
210 $wgOut->addWikiText( $this->mNewtext
);
212 if( !$this->mNewRev
->isCurrent() ) {
213 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
216 wfProfileOut( $fname );
220 * Show the first revision of an article. Uses normal diff headers in
221 * contrast to normal "old revision" display style.
223 function showFirstRevision() {
224 global $wgOut, $wgUser, $wgLang;
226 $fname = 'DifferenceEngine::showFirstRevision';
227 wfProfileIn( $fname );
229 # Get article text from the DB
231 if ( ! $this->loadNewText() ) {
232 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
234 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
235 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
236 $wgOut->addWikitext( $mtext );
237 wfProfileOut( $fname );
240 if ( $this->mNewRev
->isCurrent() ) {
241 $wgOut->setArticleFlag( true );
244 # Check if user is allowed to look at this page. If not, bail out.
246 if ( !( $this->mTitle
->userCanRead() ) ) {
247 $wgOut->loginToUse();
249 wfProfileOut( $fname );
253 # Prepare the header box
255 $sk = $wgUser->getSkin();
257 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
258 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
259 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
260 'target=' . urlencode($this->mOldUser
) );
261 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
262 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
263 "($uTLink | $contribs)<br />" . $this->mOldComment
.
264 '<br />' . $nextlink. "</div>\n";
266 $wgOut->addHTML( $header );
268 $wgOut->setSubtitle( wfMsg( 'difference' ) );
269 $wgOut->setRobotpolicy( 'noindex,follow' );
272 # Show current revision
274 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
275 if( is_object( $this->mNewRev
) ) {
276 $wgOut->setRevisionId( $this->mNewRev
->getId() );
278 $wgOut->addWikiText( $this->mNewtext
);
280 wfProfileOut( $fname );
284 * Get the diff text, send it to $wgOut
285 * Returns false if the diff could not be generated, otherwise returns true
287 function showDiff( $otitle, $ntitle ) {
289 $diff = $this->getDiff( $otitle, $ntitle );
290 if ( $diff === false ) {
291 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" ) );
294 $wgOut->addHTML( $diff );
300 * Get diff table, including header
301 * Note that the interface has changed, it's no longer static.
302 * Returns false on error
304 function getDiff( $otitle, $ntitle ) {
305 $body = $this->getDiffBody();
306 if ( $body === false ) {
309 return $this->addHeader( $body, $otitle, $ntitle );
314 * Get the diff table body, without header
315 * Returns false on error
317 function getDiffBody() {
318 global $wgUseExternalDiffEngine, $wgContLang, $wgMemc, $wgDBname;
322 if ( $this->mOldid
&& $this->mNewid
) {
324 $key = "$wgDBname:diff:oldid:{$this->mOldid}:newid:{$this->mNewid}";
325 $difftext = $wgMemc->get( $key );
327 wfIncrStats( 'diff_cache_hit' );
332 if ( !$this->loadText() ) {
336 $otext = $wgContLang->segmentForDiff($this->mOldtext
);
337 $ntext = $wgContLang->segmentForDiff($this->mNewtext
);
338 if ( $wgUseExternalDiffEngine ) {
339 # For historical reasons, external diff engine expects
340 # input text to be HTML-escaped already
341 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
342 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
343 if( !function_exists( 'wikidiff_do_diff' ) ) {
344 dl('php_wikidiff.so');
346 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
348 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
349 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
350 $diffs =& new Diff( $ota, $nta );
351 $formatter =& new TableDiffFormatter();
352 $difftext = $formatter->format( $diffs );
354 $difftext = $wgContLang->unsegmentForDiff($difftext);
356 // Save to cache for 7 days
357 if ( $key !== false ) {
358 wfIncrStats( 'diff_cache_miss' );
359 $wgMemc->set( $key, $difftext, 7*86400 );
361 wfIncrStats( 'diff_uncacheable' );
367 * Add the header to a diff body
369 function addHeader( $diff, $otitle, $ntitle ) {
371 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
373 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
374 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
383 * Use specified text instead of loading from the database
385 function setText( $oldText, $newText ) {
386 $this->mOldtext
= $oldText;
387 $this->mNewtext
= $newText;
388 $this->mTextLoaded
= 2;
392 * Load revision metadata for the specified articles. If newid is 0, then compare
393 * the old article in oldid to the current article; if oldid is 0, then
394 * compare the current article to the immediately previous one (ignoring the
397 * If oldid is false, leave the corresponding revision object set
398 * to false. This is impossible via ordinary user input, and is provided for
401 function loadRevisionData() {
403 if ( $this->mRevisionsLoaded
) {
406 // Whether it succeeds or fails, we don't want to try again
407 $this->mRevisionsLoaded
= true;
410 // Load the new revision object
411 if( $this->mNewid
) {
412 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
414 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
417 if( is_null( $this->mNewRev
) ) {
421 // Set assorted variables
422 if( $this->mNewRev
->isCurrent() ) {
423 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
424 $this->mNewPage
= $this->mTitle
;
425 $newLink = $this->mNewPage
->escapeLocalUrl();
426 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
428 $this->mNewPage
= $this->mNewRev
->getTitle();
429 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
430 $t = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
431 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
432 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
435 $this->mNewUser
= $this->mNewRev
->getUserText();
436 $this->mNewComment
= $this->mNewRev
->getComment();
438 // Load the old revision object
439 $this->mOldRev
= false;
440 if( $this->mOldid
) {
441 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
442 } elseif ( $this->mOldid
=== 0 ) {
443 $this->mOldRev
= $this->mNewRev
->getPrevious();
444 $this->mOldid
= $this->mOldRev
->getId();
445 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
447 if( is_null( $this->mOldRev
) ) {
451 if ( $this->mOldRev
) {
452 $this->mOldPage
= $this->mOldRev
->getTitle();
454 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
455 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
456 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
459 $this->mOldUser
= $this->mOldRev
->getUserText();
460 $this->mOldComment
= $this->mOldRev
->getComment();
467 * Load the text of the revisions, as well as revision data.
469 function loadText() {
470 if ( $this->mTextLoaded
== 2 ) {
473 // Whether it succeeds or fails, we don't want to try again
474 $this->mTextLoaded
= 2;
477 if ( !$this->loadRevisionData() ) {
480 if ( $this->mOldRev
) {
481 $this->mOldtext
= $this->mOldRev
->getText();
483 if ( $this->mNewRev
) {
484 $this->mNewtext
= $this->mNewRev
->getText();
490 * Load the text of the new revision, not the old one
492 function loadNewText() {
493 if ( $this->mTextLoaded
>= 1 ) {
496 $this->mTextLoaded
= 1;
498 if ( !$this->loadRevisionData() ) {
501 $this->mNewtext
= $this->mNewRev
->getText();
508 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
510 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
511 // You may copy this code freely under the conditions of the GPL.
514 define('USE_ASSERTS', function_exists('assert'));
520 * @subpackage DifferenceEngine
528 trigger_error('pure virtual', E_USER_ERROR
);
532 return $this->orig ?
sizeof($this->orig
) : 0;
535 function nclosing() {
536 return $this->closing ?
sizeof($this->closing
) : 0;
544 * @subpackage DifferenceEngine
546 class _DiffOp_Copy
extends _DiffOp
{
549 function _DiffOp_Copy ($orig, $closing = false) {
550 if (!is_array($closing))
553 $this->closing
= $closing;
557 return new _DiffOp_Copy($this->closing
, $this->orig
);
565 * @subpackage DifferenceEngine
567 class _DiffOp_Delete
extends _DiffOp
{
568 var $type = 'delete';
570 function _DiffOp_Delete ($lines) {
571 $this->orig
= $lines;
572 $this->closing
= false;
576 return new _DiffOp_Add($this->orig
);
584 * @subpackage DifferenceEngine
586 class _DiffOp_Add
extends _DiffOp
{
589 function _DiffOp_Add ($lines) {
590 $this->closing
= $lines;
595 return new _DiffOp_Delete($this->closing
);
603 * @subpackage DifferenceEngine
605 class _DiffOp_Change
extends _DiffOp
{
606 var $type = 'change';
608 function _DiffOp_Change ($orig, $closing) {
610 $this->closing
= $closing;
614 return new _DiffOp_Change($this->closing
, $this->orig
);
620 * Class used internally by Diff to actually compute the diffs.
622 * The algorithm used here is mostly lifted from the perl module
623 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
624 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
626 * More ideas are taken from:
627 * http://www.ics.uci.edu/~eppstein/161/960229.html
629 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
630 * diffutils-2.7, which can be found at:
631 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
633 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
636 * Line length limits for robustness added by Tim Starling, 2005-08-31
638 * @author Geoffrey T. Dairiki, Tim Starling
641 * @subpackage DifferenceEngine
645 function diff ($from_lines, $to_lines) {
646 $fname = '_DiffEngine::diff';
647 wfProfileIn( $fname );
649 $n_from = sizeof($from_lines);
650 $n_to = sizeof($to_lines);
652 $this->xchanged
= $this->ychanged
= array();
653 $this->xv
= $this->yv
= array();
654 $this->xind
= $this->yind
= array();
656 unset($this->in_seq
);
659 // Skip leading common lines.
660 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
661 if ($from_lines[$skip] !== $to_lines[$skip])
663 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
665 // Skip trailing common lines.
666 $xi = $n_from; $yi = $n_to;
667 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
668 if ($from_lines[$xi] !== $to_lines[$yi])
670 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
673 // Ignore lines which do not exist in both files.
674 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
675 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
678 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
679 $line = $to_lines[$yi];
680 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
682 $yhash[$this->_line_hash($line)] = 1;
686 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
687 $line = $from_lines[$xi];
688 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
695 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
697 // Merge edits when possible
698 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
699 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
701 // Compute the edit operations.
704 while ($xi < $n_from ||
$yi < $n_to) {
705 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
706 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
708 // Skip matching "snake".
710 while ( $xi < $n_from && $yi < $n_to
711 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
712 $copy[] = $from_lines[$xi++
];
716 $edits[] = new _DiffOp_Copy($copy);
718 // Find deletes & adds.
720 while ($xi < $n_from && $this->xchanged
[$xi])
721 $delete[] = $from_lines[$xi++
];
724 while ($yi < $n_to && $this->ychanged
[$yi])
725 $add[] = $to_lines[$yi++
];
728 $edits[] = new _DiffOp_Change($delete, $add);
730 $edits[] = new _DiffOp_Delete($delete);
732 $edits[] = new _DiffOp_Add($add);
734 wfProfileOut( $fname );
739 * Returns the whole line if it's small enough, or the MD5 hash otherwise
741 function _line_hash( $line ) {
742 if ( strlen( $line ) > MAX_DIFF_XREF_LENGTH
) {
750 /* Divide the Largest Common Subsequence (LCS) of the sequences
751 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
754 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
755 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
756 * sub sequences. The first sub-sequence is contained in [X0, X1),
757 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
758 * that (X0, Y0) == (XOFF, YOFF) and
759 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
761 * This function assumes that the first lines of the specified portions
762 * of the two files do not match, and likewise that the last lines do not
763 * match. The caller must trim matching lines from the beginning and end
764 * of the portions it is going to specify.
766 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
767 $fname = '_DiffEngine::_diag';
768 wfProfileIn( $fname );
771 if ($xlim - $xoff > $ylim - $yoff) {
772 // Things seems faster (I'm not sure I understand why)
773 // when the shortest sequence in X.
775 list ($xoff, $xlim, $yoff, $ylim)
776 = array( $yoff, $ylim, $xoff, $xlim);
780 for ($i = $ylim - 1; $i >= $yoff; $i--)
781 $ymatches[$this->xv
[$i]][] = $i;
783 for ($i = $ylim - 1; $i >= $yoff; $i--)
784 $ymatches[$this->yv
[$i]][] = $i;
787 $this->seq
[0]= $yoff - 1;
788 $this->in_seq
= array();
791 $numer = $xlim - $xoff +
$nchunks - 1;
793 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
794 wfProfileIn( "$fname-chunk" );
796 for ($i = 0; $i <= $this->lcs
; $i++
)
797 $ymids[$i][$chunk-1] = $this->seq
[$i];
799 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
800 for ( ; $x < $x1; $x++
) {
801 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
802 if (empty($ymatches[$line]))
804 $matches = $ymatches[$line];
806 while (list ($junk, $y) = each($matches))
807 if (empty($this->in_seq
[$y])) {
808 $k = $this->_lcs_pos($y);
809 USE_ASSERTS
&& assert($k > 0);
810 $ymids[$k] = $ymids[$k-1];
813 while (list ($junk, $y) = each($matches)) {
814 if ($y > $this->seq
[$k-1]) {
815 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
816 // Optimization: this is a common case:
817 // next match is just replacing previous match.
818 $this->in_seq
[$this->seq
[$k]] = false;
820 $this->in_seq
[$y] = 1;
821 } else if (empty($this->in_seq
[$y])) {
822 $k = $this->_lcs_pos($y);
823 USE_ASSERTS
&& assert($k > 0);
824 $ymids[$k] = $ymids[$k-1];
828 wfProfileOut( "$fname-chunk" );
831 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
832 $ymid = $ymids[$this->lcs
];
833 for ($n = 0; $n < $nchunks - 1; $n++
) {
834 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
836 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
838 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
840 wfProfileOut( $fname );
841 return array($this->lcs
, $seps);
844 function _lcs_pos ($ypos) {
845 $fname = '_DiffEngine::_lcs_pos';
846 wfProfileIn( $fname );
849 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
850 $this->seq
[++
$this->lcs
] = $ypos;
851 $this->in_seq
[$ypos] = 1;
852 wfProfileOut( $fname );
857 while ($beg < $end) {
858 $mid = (int)(($beg +
$end) / 2);
859 if ( $ypos > $this->seq
[$mid] )
865 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
867 $this->in_seq
[$this->seq
[$end]] = false;
868 $this->seq
[$end] = $ypos;
869 $this->in_seq
[$ypos] = 1;
870 wfProfileOut( $fname );
874 /* Find LCS of two sequences.
876 * The results are recorded in the vectors $this->{x,y}changed[], by
877 * storing a 1 in the element for each line that is an insertion
878 * or deletion (ie. is not in the LCS).
880 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
882 * Note that XLIM, YLIM are exclusive bounds.
883 * All line numbers are origin-0 and discarded lines are not counted.
885 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
886 $fname = '_DiffEngine::_compareseq';
887 wfProfileIn( $fname );
889 // Slide down the bottom initial diagonal.
890 while ($xoff < $xlim && $yoff < $ylim
891 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
896 // Slide up the top initial diagonal.
897 while ($xlim > $xoff && $ylim > $yoff
898 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
903 if ($xoff == $xlim ||
$yoff == $ylim)
906 // This is ad hoc but seems to work well.
907 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
908 //$nchunks = max(2,min(8,(int)$nchunks));
909 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
911 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
915 // X and Y sequences have no common subsequence:
917 while ($yoff < $ylim)
918 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
919 while ($xoff < $xlim)
920 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
922 // Use the partitions to split this problem into subproblems.
925 while ($pt2 = next($seps)) {
926 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
930 wfProfileOut( $fname );
933 /* Adjust inserts/deletes of identical lines to join changes
934 * as much as possible.
936 * We do something when a run of changed lines include a
937 * line at one end and has an excluded, identical line at the other.
938 * We are free to choose which identical line is included.
939 * `compareseq' usually chooses the one at the beginning,
940 * but usually it is cleaner to consider the following identical line
941 * to be the "change".
943 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
945 function _shift_boundaries ($lines, &$changed, $other_changed) {
946 $fname = '_DiffEngine::_shift_boundaries';
947 wfProfileIn( $fname );
951 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
952 $len = sizeof($lines);
953 $other_len = sizeof($other_changed);
957 * Scan forwards to find beginning of another run of changes.
958 * Also keep track of the corresponding point in the other file.
960 * Throughout this code, $i and $j are adjusted together so that
961 * the first $i elements of $changed and the first $j elements
962 * of $other_changed both contain the same number of zeros
964 * Furthermore, $j is always kept so that $j == $other_len or
965 * $other_changed[$j] == false.
967 while ($j < $other_len && $other_changed[$j])
970 while ($i < $len && ! $changed[$i]) {
971 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
973 while ($j < $other_len && $other_changed[$j])
982 // Find the end of this run of changes.
983 while (++
$i < $len && $changed[$i])
988 * Record the length of this run of changes, so that
989 * we can later determine whether the run has grown.
991 $runlength = $i - $start;
994 * Move the changed region back, so long as the
995 * previous unchanged line matches the last changed one.
996 * This merges with previous changed regions.
998 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
999 $changed[--$start] = 1;
1000 $changed[--$i] = false;
1001 while ($start > 0 && $changed[$start - 1])
1003 USE_ASSERTS
&& assert('$j > 0');
1004 while ($other_changed[--$j])
1006 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1010 * Set CORRESPONDING to the end of the changed run, at the last
1011 * point where it corresponds to a changed run in the other file.
1012 * CORRESPONDING == LEN means no such point has been found.
1014 $corresponding = $j < $other_len ?
$i : $len;
1017 * Move the changed region forward, so long as the
1018 * first changed line matches the following unchanged one.
1019 * This merges with following changed regions.
1020 * Do this second, so that if there are no merges,
1021 * the changed region is moved forward as far as possible.
1023 while ($i < $len && $lines[$start] == $lines[$i]) {
1024 $changed[$start++
] = false;
1026 while ($i < $len && $changed[$i])
1029 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1031 if ($j < $other_len && $other_changed[$j]) {
1032 $corresponding = $i;
1033 while ($j < $other_len && $other_changed[$j])
1037 } while ($runlength != $i - $start);
1040 * If possible, move the fully-merged run of changes
1041 * back to a corresponding run in the other file.
1043 while ($corresponding < $i) {
1044 $changed[--$start] = 1;
1046 USE_ASSERTS
&& assert('$j > 0');
1047 while ($other_changed[--$j])
1049 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1052 wfProfileOut( $fname );
1057 * Class representing a 'diff' between two sequences of strings.
1060 * @package MediaWiki
1061 * @subpackage DifferenceEngine
1069 * Computes diff between sequences of strings.
1071 * @param $from_lines array An array of strings.
1072 * (Typically these are lines from a file.)
1073 * @param $to_lines array An array of strings.
1075 function Diff($from_lines, $to_lines) {
1076 $eng = new _DiffEngine
;
1077 $this->edits
= $eng->diff($from_lines, $to_lines);
1078 //$this->_check($from_lines, $to_lines);
1082 * Compute reversed Diff.
1086 * $diff = new Diff($lines1, $lines2);
1087 * $rev = $diff->reverse();
1088 * @return object A Diff object representing the inverse of the
1091 function reverse () {
1093 $rev->edits
= array();
1094 foreach ($this->edits
as $edit) {
1095 $rev->edits
[] = $edit->reverse();
1101 * Check for empty diff.
1103 * @return bool True iff two sequences were identical.
1105 function isEmpty () {
1106 foreach ($this->edits
as $edit) {
1107 if ($edit->type
!= 'copy')
1114 * Compute the length of the Longest Common Subsequence (LCS).
1116 * This is mostly for diagnostic purposed.
1118 * @return int The length of the LCS.
1122 foreach ($this->edits
as $edit) {
1123 if ($edit->type
== 'copy')
1124 $lcs +
= sizeof($edit->orig
);
1130 * Get the original set of lines.
1132 * This reconstructs the $from_lines parameter passed to the
1135 * @return array The original sequence of strings.
1140 foreach ($this->edits
as $edit) {
1142 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1148 * Get the closing set of lines.
1150 * This reconstructs the $to_lines parameter passed to the
1153 * @return array The sequence of strings.
1155 function closing() {
1158 foreach ($this->edits
as $edit) {
1160 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1166 * Check a Diff for validity.
1168 * This is here only for debugging purposes.
1170 function _check ($from_lines, $to_lines) {
1171 $fname = 'Diff::_check';
1172 wfProfileIn( $fname );
1173 if (serialize($from_lines) != serialize($this->orig()))
1174 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1175 if (serialize($to_lines) != serialize($this->closing()))
1176 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1178 $rev = $this->reverse();
1179 if (serialize($to_lines) != serialize($rev->orig()))
1180 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1181 if (serialize($from_lines) != serialize($rev->closing()))
1182 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1186 foreach ($this->edits
as $edit) {
1187 if ( $prevtype == $edit->type
)
1188 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1189 $prevtype = $edit->type
;
1192 $lcs = $this->lcs();
1193 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1194 wfProfileOut( $fname );
1202 * @package MediaWiki
1203 * @subpackage DifferenceEngine
1205 class MappedDiff
extends Diff
1210 * Computes diff between sequences of strings.
1212 * This can be used to compute things like
1213 * case-insensitve diffs, or diffs which ignore
1214 * changes in white-space.
1216 * @param $from_lines array An array of strings.
1217 * (Typically these are lines from a file.)
1219 * @param $to_lines array An array of strings.
1221 * @param $mapped_from_lines array This array should
1222 * have the same size number of elements as $from_lines.
1223 * The elements in $mapped_from_lines and
1224 * $mapped_to_lines are what is actually compared
1225 * when computing the diff.
1227 * @param $mapped_to_lines array This array should
1228 * have the same number of elements as $to_lines.
1230 function MappedDiff($from_lines, $to_lines,
1231 $mapped_from_lines, $mapped_to_lines) {
1232 $fname = 'MappedDiff::MappedDiff';
1233 wfProfileIn( $fname );
1235 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1236 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1238 $this->Diff($mapped_from_lines, $mapped_to_lines);
1241 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1242 $orig = &$this->edits
[$i]->orig
;
1243 if (is_array($orig)) {
1244 $orig = array_slice($from_lines, $xi, sizeof($orig));
1245 $xi +
= sizeof($orig);
1248 $closing = &$this->edits
[$i]->closing
;
1249 if (is_array($closing)) {
1250 $closing = array_slice($to_lines, $yi, sizeof($closing));
1251 $yi +
= sizeof($closing);
1254 wfProfileOut( $fname );
1259 * A class to format Diffs
1261 * This class formats the diff in classic diff format.
1262 * It is intended that this class be customized via inheritance,
1263 * to obtain fancier outputs.
1266 * @package MediaWiki
1267 * @subpackage DifferenceEngine
1272 * Number of leading context "lines" to preserve.
1274 * This should be left at zero for this class, but subclasses
1275 * may want to set this to other values.
1277 var $leading_context_lines = 0;
1280 * Number of trailing context "lines" to preserve.
1282 * This should be left at zero for this class, but subclasses
1283 * may want to set this to other values.
1285 var $trailing_context_lines = 0;
1290 * @param $diff object A Diff object.
1291 * @return string The formatted output.
1293 function format($diff) {
1294 $fname = 'DiffFormatter::format';
1295 wfProfileIn( $fname );
1301 $nlead = $this->leading_context_lines
;
1302 $ntrail = $this->trailing_context_lines
;
1304 $this->_start_diff();
1306 foreach ($diff->edits
as $edit) {
1307 if ($edit->type
== 'copy') {
1308 if (is_array($block)) {
1309 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1314 $context = array_slice($edit->orig
, 0, $ntrail);
1315 $block[] = new _DiffOp_Copy($context);
1317 $this->_block($x0, $ntrail +
$xi - $x0,
1318 $y0, $ntrail +
$yi - $y0,
1323 $context = $edit->orig
;
1326 if (! is_array($block)) {
1327 $context = array_slice($context, sizeof($context) - $nlead);
1328 $x0 = $xi - sizeof($context);
1329 $y0 = $yi - sizeof($context);
1332 $block[] = new _DiffOp_Copy($context);
1338 $xi +
= sizeof($edit->orig
);
1340 $yi +
= sizeof($edit->closing
);
1343 if (is_array($block))
1344 $this->_block($x0, $xi - $x0,
1348 $end = $this->_end_diff();
1349 wfProfileOut( $fname );
1353 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1354 $fname = 'DiffFormatter::_block';
1355 wfProfileIn( $fname );
1356 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1357 foreach ($edits as $edit) {
1358 if ($edit->type
== 'copy')
1359 $this->_context($edit->orig
);
1360 elseif ($edit->type
== 'add')
1361 $this->_added($edit->closing
);
1362 elseif ($edit->type
== 'delete')
1363 $this->_deleted($edit->orig
);
1364 elseif ($edit->type
== 'change')
1365 $this->_changed($edit->orig
, $edit->closing
);
1367 trigger_error('Unknown edit type', E_USER_ERROR
);
1369 $this->_end_block();
1370 wfProfileOut( $fname );
1373 function _start_diff() {
1377 function _end_diff() {
1378 $val = ob_get_contents();
1383 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1385 $xbeg .= "," . ($xbeg +
$xlen - 1);
1387 $ybeg .= "," . ($ybeg +
$ylen - 1);
1389 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1392 function _start_block($header) {
1396 function _end_block() {
1399 function _lines($lines, $prefix = ' ') {
1400 foreach ($lines as $line)
1401 echo "$prefix $line\n";
1404 function _context($lines) {
1405 $this->_lines($lines);
1408 function _added($lines) {
1409 $this->_lines($lines, '>');
1411 function _deleted($lines) {
1412 $this->_lines($lines, '<');
1415 function _changed($orig, $closing) {
1416 $this->_deleted($orig);
1418 $this->_added($closing);
1424 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1428 define('NBSP', ' '); // iso-8859-x non-breaking space.
1433 * @package MediaWiki
1434 * @subpackage DifferenceEngine
1436 class _HWLDF_WordAccumulator
{
1437 function _HWLDF_WordAccumulator () {
1438 $this->_lines
= array();
1444 function _flushGroup ($new_tag) {
1445 if ($this->_group
!== '') {
1446 if ($this->_tag
== 'mark')
1447 $this->_line
.= '<span class="diffchange">' .
1448 htmlspecialchars ( $this->_group
) . '</span>';
1450 $this->_line
.= htmlspecialchars ( $this->_group
);
1453 $this->_tag
= $new_tag;
1456 function _flushLine ($new_tag) {
1457 $this->_flushGroup($new_tag);
1458 if ($this->_line
!= '')
1459 array_push ( $this->_lines
, $this->_line
);
1461 # make empty lines visible by inserting an NBSP
1462 array_push ( $this->_lines
, NBSP
);
1466 function addWords ($words, $tag = '') {
1467 if ($tag != $this->_tag
)
1468 $this->_flushGroup($tag);
1470 foreach ($words as $word) {
1471 // new-line should only come as first char of word.
1474 if ($word[0] == "\n") {
1475 $this->_flushLine($tag);
1476 $word = substr($word, 1);
1478 assert(!strstr($word, "\n"));
1479 $this->_group
.= $word;
1483 function getLines() {
1484 $this->_flushLine('~done');
1485 return $this->_lines
;
1492 * @package MediaWiki
1493 * @subpackage DifferenceEngine
1495 class WordLevelDiff
extends MappedDiff
1497 function WordLevelDiff ($orig_lines, $closing_lines) {
1498 $fname = 'WordLevelDiff::WordLevelDiff';
1499 wfProfileIn( $fname );
1501 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1502 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1504 $this->MappedDiff($orig_words, $closing_words,
1505 $orig_stripped, $closing_stripped);
1506 wfProfileOut( $fname );
1509 function _split($lines) {
1510 $fname = 'WordLevelDiff::_split';
1511 wfProfileIn( $fname );
1514 $stripped = array();
1516 foreach ( $lines as $line ) {
1517 # If the line is too long, just pretend the entire line is one big word
1518 # This prevents resource exhaustion problems
1525 if ( strlen( $line ) > MAX_DIFF_LINE
) {
1527 $stripped[] = $line;
1529 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1532 $words = array_merge( $words, $m[0] );
1533 $stripped = array_merge( $stripped, $m[1] );
1537 wfProfileOut( $fname );
1538 return array($words, $stripped);
1542 $fname = 'WordLevelDiff::orig';
1543 wfProfileIn( $fname );
1544 $orig = new _HWLDF_WordAccumulator
;
1546 foreach ($this->edits
as $edit) {
1547 if ($edit->type
== 'copy')
1548 $orig->addWords($edit->orig
);
1549 elseif ($edit->orig
)
1550 $orig->addWords($edit->orig
, 'mark');
1552 $lines = $orig->getLines();
1553 wfProfileOut( $fname );
1557 function closing () {
1558 $fname = 'WordLevelDiff::closing';
1559 wfProfileIn( $fname );
1560 $closing = new _HWLDF_WordAccumulator
;
1562 foreach ($this->edits
as $edit) {
1563 if ($edit->type
== 'copy')
1564 $closing->addWords($edit->closing
);
1565 elseif ($edit->closing
)
1566 $closing->addWords($edit->closing
, 'mark');
1568 $lines = $closing->getLines();
1569 wfProfileOut( $fname );
1575 * Wikipedia Table style diff formatter.
1578 * @package MediaWiki
1579 * @subpackage DifferenceEngine
1581 class TableDiffFormatter
extends DiffFormatter
1583 function TableDiffFormatter() {
1584 $this->leading_context_lines
= 2;
1585 $this->trailing_context_lines
= 2;
1588 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1589 $l1 = wfMsg( 'lineno', $xbeg );
1590 $l2 = wfMsg( 'lineno', $ybeg );
1592 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1593 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1597 function _start_block( $header ) {
1602 function _end_block() {
1605 function _lines( $lines, $prefix=' ', $color='white' ) {
1608 # HTML-escape parameter before calling this
1609 function addedLine( $line ) {
1610 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1613 # HTML-escape parameter before calling this
1614 function deletedLine( $line ) {
1615 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1618 # HTML-escape parameter before calling this
1619 function contextLine( $line ) {
1620 return "<td> </td><td class='diff-context'>{$line}</td>";
1623 function emptyLine() {
1624 return '<td colspan="2"> </td>';
1627 function _added( $lines ) {
1628 foreach ($lines as $line) {
1629 echo '<tr>' . $this->emptyLine() .
1630 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1634 function _deleted($lines) {
1635 foreach ($lines as $line) {
1636 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1637 $this->emptyLine() . "</tr>\n";
1641 function _context( $lines ) {
1642 foreach ($lines as $line) {
1644 $this->contextLine( htmlspecialchars ( $line ) ) .
1645 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1649 function _changed( $orig, $closing ) {
1650 $fname = 'TableDiffFormatter::_changed';
1651 wfProfileIn( $fname );
1653 $diff = new WordLevelDiff( $orig, $closing );
1654 $del = $diff->orig();
1655 $add = $diff->closing();
1657 # Notice that WordLevelDiff returns HTML-escaped output.
1658 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1660 while ( $line = array_shift( $del ) ) {
1661 $aline = array_shift( $add );
1662 echo '<tr>' . $this->deletedLine( $line ) .
1663 $this->addedLine( $aline ) . "</tr>\n";
1665 foreach ($add as $line) { # If any leftovers
1666 echo '<tr>' . $this->emptyLine() .
1667 $this->addedLine( $line ) . "</tr>\n";
1669 wfProfileOut( $fname );