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 $wgOut->addWikiText( $this->mNewtext
);
209 if( !$this->mNewRev
->isCurrent() ) {
210 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
213 wfProfileOut( $fname );
217 * Show the first revision of an article. Uses normal diff headers in
218 * contrast to normal "old revision" display style.
220 function showFirstRevision() {
221 global $wgOut, $wgUser, $wgLang;
223 $fname = 'DifferenceEngine::showFirstRevision';
224 wfProfileIn( $fname );
226 # Get article text from the DB
228 if ( ! $this->loadNewText() ) {
229 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
231 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
232 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
233 $wgOut->addWikitext( $mtext );
234 wfProfileOut( $fname );
237 if ( $this->mNewRev
->isCurrent() ) {
238 $wgOut->setArticleFlag( true );
241 # Check if user is allowed to look at this page. If not, bail out.
243 if ( !( $this->mTitle
->userCanRead() ) ) {
244 $wgOut->loginToUse();
246 wfProfileOut( $fname );
250 # Prepare the header box
252 $sk = $wgUser->getSkin();
254 $uTLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER_TALK
, $this->mOldUser
), $wgLang->getNsText( NS_TALK
) );
255 $userLink = $sk->makeLinkObj( Title
::makeTitleSafe( NS_USER
, $this->mOldUser
), $this->mOldUser
);
256 $contribs = $sk->makeKnownLinkObj( Title
::makeTitle( NS_SPECIAL
, 'Contributions' ), wfMsg( 'contribslink' ),
257 'target=' . urlencode($this->mOldUser
) );
258 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
259 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
260 "($uTLink | $contribs)<br />" . $this->mOldComment
.
261 '<br />' . $nextlink. "</div>\n";
263 $wgOut->addHTML( $header );
265 $wgOut->setSubtitle( wfMsg( 'difference' ) );
266 $wgOut->setRobotpolicy( 'noindex,follow' );
269 # Show current revision
271 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
272 $wgOut->addWikiText( $this->mNewtext
);
274 wfProfileOut( $fname );
278 * Get the diff text, send it to $wgOut
279 * Returns false if the diff could not be generated, otherwise returns true
281 function showDiff( $otitle, $ntitle ) {
283 $diff = $this->getDiff( $otitle, $ntitle );
284 if ( $diff === false ) {
285 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" ) );
288 $wgOut->addHTML( $diff );
294 * Get diff table, including header
295 * Note that the interface has changed, it's no longer static.
296 * Returns false on error
298 function getDiff( $otitle, $ntitle ) {
299 $body = $this->getDiffBody();
300 if ( $body === false ) {
303 return $this->addHeader( $body, $otitle, $ntitle );
308 * Get the diff table body, without header
309 * Returns false on error
311 function getDiffBody() {
312 global $wgUseExternalDiffEngine, $wgContLang, $wgMemc, $wgDBname;
316 if ( $this->mOldid
&& $this->mNewid
) {
318 $key = "$wgDBname:diff:oldid:{$this->mOldid}:newid:{$this->mNewid}";
319 $difftext = $wgMemc->get( $key );
325 if ( !$this->loadText() ) {
329 $otext = $wgContLang->segmentForDiff($this->mOldtext
);
330 $ntext = $wgContLang->segmentForDiff($this->mNewtext
);
331 if ( $wgUseExternalDiffEngine ) {
332 # For historical reasons, external diff engine expects
333 # input text to be HTML-escaped already
334 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
335 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
336 if( !function_exists( 'wikidiff_do_diff' ) ) {
337 dl('php_wikidiff.so');
339 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
341 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
342 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
343 $diffs =& new Diff( $ota, $nta );
344 $formatter =& new TableDiffFormatter();
345 $difftext = $formatter->format( $diffs );
347 $difftext = $wgContLang->unsegmentForDiff($difftext);
349 // Save to cache for 7 days
350 if ( $key !== false ) {
351 $wgMemc->set( $key, $difftext, 7*86400 );
357 * Add the header to a diff body
359 function addHeader( $diff, $otitle, $ntitle ) {
361 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
363 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
364 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
373 * Use specified text instead of loading from the database
375 function setText( $oldText, $newText ) {
376 $this->mOldtext
= $oldText;
377 $this->mNewtext
= $newText;
378 $this->mTextLoaded
= 2;
382 * Load revision metadata for the specified articles. If newid is 0, then compare
383 * the old article in oldid to the current article; if oldid is 0, then
384 * compare the current article to the immediately previous one (ignoring the
387 * If oldid is false, leave the corresponding revision object set
388 * to false. This is impossible via ordinary user input, and is provided for
391 function loadRevisionData() {
393 if ( $this->mRevisionsLoaded
) {
396 // Whether it succeeds or fails, we don't want to try again
397 $this->mRevisionsLoaded
= true;
400 // Load the new revision object
401 if( $this->mNewid
) {
402 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
404 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
407 if( is_null( $this->mNewRev
) ) {
411 // Set assorted variables
412 if( $this->mNewRev
->isCurrent() ) {
413 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
414 $this->mNewPage
= $this->mTitle
;
415 $newLink = $this->mNewPage
->escapeLocalUrl();
416 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
418 $this->mNewPage
= $this->mNewRev
->getTitle();
419 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
420 $t = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
421 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
422 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
425 $this->mNewUser
= $this->mNewRev
->getUserText();
426 $this->mNewComment
= $this->mNewRev
->getComment();
428 // Load the old revision object
429 $this->mOldRev
= false;
430 if( $this->mOldid
) {
431 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
432 } elseif ( $this->mOldid
=== 0 ) {
433 $this->mOldRev
= $this->mNewRev
->getPrevious();
434 $this->mOldid
= $this->mOldRev
->getId();
435 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
437 if( is_null( $this->mOldRev
) ) {
441 if ( $this->mOldRev
) {
442 $this->mOldPage
= $this->mOldRev
->getTitle();
444 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
445 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
446 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
449 $this->mOldUser
= $this->mOldRev
->getUserText();
450 $this->mOldComment
= $this->mOldRev
->getComment();
457 * Load the text of the revisions, as well as revision data.
459 function loadText() {
460 if ( $this->mTextLoaded
== 2 ) {
463 // Whether it succeeds or fails, we don't want to try again
464 $this->mTextLoaded
= 2;
467 if ( !$this->loadRevisionData() ) {
470 if ( $this->mOldRev
) {
471 $this->mOldtext
= $this->mOldRev
->getText();
473 if ( $this->mNewRev
) {
474 $this->mNewtext
= $this->mNewRev
->getText();
480 * Load the text of the new revision, not the old one
482 function loadNewText() {
483 if ( $this->mTextLoaded
>= 1 ) {
486 $this->mTextLoaded
= 1;
488 if ( !$this->loadRevisionData() ) {
491 $this->mNewtext
= $this->mNewRev
->getText();
498 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
500 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
501 // You may copy this code freely under the conditions of the GPL.
504 define('USE_ASSERTS', function_exists('assert'));
510 * @subpackage DifferenceEngine
518 trigger_error('pure virtual', E_USER_ERROR
);
522 return $this->orig ?
sizeof($this->orig
) : 0;
525 function nclosing() {
526 return $this->closing ?
sizeof($this->closing
) : 0;
534 * @subpackage DifferenceEngine
536 class _DiffOp_Copy
extends _DiffOp
{
539 function _DiffOp_Copy ($orig, $closing = false) {
540 if (!is_array($closing))
543 $this->closing
= $closing;
547 return new _DiffOp_Copy($this->closing
, $this->orig
);
555 * @subpackage DifferenceEngine
557 class _DiffOp_Delete
extends _DiffOp
{
558 var $type = 'delete';
560 function _DiffOp_Delete ($lines) {
561 $this->orig
= $lines;
562 $this->closing
= false;
566 return new _DiffOp_Add($this->orig
);
574 * @subpackage DifferenceEngine
576 class _DiffOp_Add
extends _DiffOp
{
579 function _DiffOp_Add ($lines) {
580 $this->closing
= $lines;
585 return new _DiffOp_Delete($this->closing
);
593 * @subpackage DifferenceEngine
595 class _DiffOp_Change
extends _DiffOp
{
596 var $type = 'change';
598 function _DiffOp_Change ($orig, $closing) {
600 $this->closing
= $closing;
604 return new _DiffOp_Change($this->closing
, $this->orig
);
610 * Class used internally by Diff to actually compute the diffs.
612 * The algorithm used here is mostly lifted from the perl module
613 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
614 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
616 * More ideas are taken from:
617 * http://www.ics.uci.edu/~eppstein/161/960229.html
619 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
620 * diffutils-2.7, which can be found at:
621 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
623 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
626 * Line length limits for robustness added by Tim Starling, 2005-08-31
628 * @author Geoffrey T. Dairiki, Tim Starling
631 * @subpackage DifferenceEngine
635 function diff ($from_lines, $to_lines) {
636 $fname = '_DiffEngine::diff';
637 wfProfileIn( $fname );
639 $n_from = sizeof($from_lines);
640 $n_to = sizeof($to_lines);
642 $this->xchanged
= $this->ychanged
= array();
643 $this->xv
= $this->yv
= array();
644 $this->xind
= $this->yind
= array();
646 unset($this->in_seq
);
649 // Skip leading common lines.
650 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
651 if ($from_lines[$skip] != $to_lines[$skip])
653 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
655 // Skip trailing common lines.
656 $xi = $n_from; $yi = $n_to;
657 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
658 if ($from_lines[$xi] != $to_lines[$yi])
660 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
663 // Ignore lines which do not exist in both files.
664 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
665 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
668 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
669 $line = $to_lines[$yi];
670 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
672 $yhash[$this->_line_hash($line)] = 1;
676 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
677 $line = $from_lines[$xi];
678 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
685 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
687 // Merge edits when possible
688 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
689 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
691 // Compute the edit operations.
694 while ($xi < $n_from ||
$yi < $n_to) {
695 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
696 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
698 // Skip matching "snake".
700 while ( $xi < $n_from && $yi < $n_to
701 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
702 $copy[] = $from_lines[$xi++
];
706 $edits[] = new _DiffOp_Copy($copy);
708 // Find deletes & adds.
710 while ($xi < $n_from && $this->xchanged
[$xi])
711 $delete[] = $from_lines[$xi++
];
714 while ($yi < $n_to && $this->ychanged
[$yi])
715 $add[] = $to_lines[$yi++
];
718 $edits[] = new _DiffOp_Change($delete, $add);
720 $edits[] = new _DiffOp_Delete($delete);
722 $edits[] = new _DiffOp_Add($add);
724 wfProfileOut( $fname );
729 * Returns the whole line if it's small enough, or the MD5 hash otherwise
731 function _line_hash( $line ) {
732 if ( strlen( $line ) > MAX_DIFF_XREF_LENGTH
) {
740 /* Divide the Largest Common Subsequence (LCS) of the sequences
741 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
744 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
745 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
746 * sub sequences. The first sub-sequence is contained in [X0, X1),
747 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
748 * that (X0, Y0) == (XOFF, YOFF) and
749 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
751 * This function assumes that the first lines of the specified portions
752 * of the two files do not match, and likewise that the last lines do not
753 * match. The caller must trim matching lines from the beginning and end
754 * of the portions it is going to specify.
756 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
757 $fname = '_DiffEngine::_diag';
758 wfProfileIn( $fname );
761 if ($xlim - $xoff > $ylim - $yoff) {
762 // Things seems faster (I'm not sure I understand why)
763 // when the shortest sequence in X.
765 list ($xoff, $xlim, $yoff, $ylim)
766 = array( $yoff, $ylim, $xoff, $xlim);
770 for ($i = $ylim - 1; $i >= $yoff; $i--)
771 $ymatches[$this->xv
[$i]][] = $i;
773 for ($i = $ylim - 1; $i >= $yoff; $i--)
774 $ymatches[$this->yv
[$i]][] = $i;
777 $this->seq
[0]= $yoff - 1;
778 $this->in_seq
= array();
781 $numer = $xlim - $xoff +
$nchunks - 1;
783 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
784 wfProfileIn( "$fname-chunk" );
786 for ($i = 0; $i <= $this->lcs
; $i++
)
787 $ymids[$i][$chunk-1] = $this->seq
[$i];
789 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
790 for ( ; $x < $x1; $x++
) {
791 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
792 if (empty($ymatches[$line]))
794 $matches = $ymatches[$line];
796 while (list ($junk, $y) = each($matches))
797 if (empty($this->in_seq
[$y])) {
798 $k = $this->_lcs_pos($y);
799 USE_ASSERTS
&& assert($k > 0);
800 $ymids[$k] = $ymids[$k-1];
803 while (list ($junk, $y) = each($matches)) {
804 if ($y > $this->seq
[$k-1]) {
805 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
806 // Optimization: this is a common case:
807 // next match is just replacing previous match.
808 $this->in_seq
[$this->seq
[$k]] = false;
810 $this->in_seq
[$y] = 1;
811 } else if (empty($this->in_seq
[$y])) {
812 $k = $this->_lcs_pos($y);
813 USE_ASSERTS
&& assert($k > 0);
814 $ymids[$k] = $ymids[$k-1];
818 wfProfileOut( "$fname-chunk" );
821 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
822 $ymid = $ymids[$this->lcs
];
823 for ($n = 0; $n < $nchunks - 1; $n++
) {
824 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
826 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
828 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
830 wfProfileOut( $fname );
831 return array($this->lcs
, $seps);
834 function _lcs_pos ($ypos) {
835 $fname = '_DiffEngine::_lcs_pos';
836 wfProfileIn( $fname );
839 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
840 $this->seq
[++
$this->lcs
] = $ypos;
841 $this->in_seq
[$ypos] = 1;
842 wfProfileOut( $fname );
847 while ($beg < $end) {
848 $mid = (int)(($beg +
$end) / 2);
849 if ( $ypos > $this->seq
[$mid] )
855 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
857 $this->in_seq
[$this->seq
[$end]] = false;
858 $this->seq
[$end] = $ypos;
859 $this->in_seq
[$ypos] = 1;
860 wfProfileOut( $fname );
864 /* Find LCS of two sequences.
866 * The results are recorded in the vectors $this->{x,y}changed[], by
867 * storing a 1 in the element for each line that is an insertion
868 * or deletion (ie. is not in the LCS).
870 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
872 * Note that XLIM, YLIM are exclusive bounds.
873 * All line numbers are origin-0 and discarded lines are not counted.
875 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
876 $fname = '_DiffEngine::_compareseq';
877 wfProfileIn( $fname );
879 // Slide down the bottom initial diagonal.
880 while ($xoff < $xlim && $yoff < $ylim
881 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
886 // Slide up the top initial diagonal.
887 while ($xlim > $xoff && $ylim > $yoff
888 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
893 if ($xoff == $xlim ||
$yoff == $ylim)
896 // This is ad hoc but seems to work well.
897 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
898 //$nchunks = max(2,min(8,(int)$nchunks));
899 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
901 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
905 // X and Y sequences have no common subsequence:
907 while ($yoff < $ylim)
908 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
909 while ($xoff < $xlim)
910 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
912 // Use the partitions to split this problem into subproblems.
915 while ($pt2 = next($seps)) {
916 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
920 wfProfileOut( $fname );
923 /* Adjust inserts/deletes of identical lines to join changes
924 * as much as possible.
926 * We do something when a run of changed lines include a
927 * line at one end and has an excluded, identical line at the other.
928 * We are free to choose which identical line is included.
929 * `compareseq' usually chooses the one at the beginning,
930 * but usually it is cleaner to consider the following identical line
931 * to be the "change".
933 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
935 function _shift_boundaries ($lines, &$changed, $other_changed) {
936 $fname = '_DiffEngine::_shift_boundaries';
937 wfProfileIn( $fname );
941 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
942 $len = sizeof($lines);
943 $other_len = sizeof($other_changed);
947 * Scan forwards to find beginning of another run of changes.
948 * Also keep track of the corresponding point in the other file.
950 * Throughout this code, $i and $j are adjusted together so that
951 * the first $i elements of $changed and the first $j elements
952 * of $other_changed both contain the same number of zeros
954 * Furthermore, $j is always kept so that $j == $other_len or
955 * $other_changed[$j] == false.
957 while ($j < $other_len && $other_changed[$j])
960 while ($i < $len && ! $changed[$i]) {
961 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
963 while ($j < $other_len && $other_changed[$j])
972 // Find the end of this run of changes.
973 while (++
$i < $len && $changed[$i])
978 * Record the length of this run of changes, so that
979 * we can later determine whether the run has grown.
981 $runlength = $i - $start;
984 * Move the changed region back, so long as the
985 * previous unchanged line matches the last changed one.
986 * This merges with previous changed regions.
988 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
989 $changed[--$start] = 1;
990 $changed[--$i] = false;
991 while ($start > 0 && $changed[$start - 1])
993 USE_ASSERTS
&& assert('$j > 0');
994 while ($other_changed[--$j])
996 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1000 * Set CORRESPONDING to the end of the changed run, at the last
1001 * point where it corresponds to a changed run in the other file.
1002 * CORRESPONDING == LEN means no such point has been found.
1004 $corresponding = $j < $other_len ?
$i : $len;
1007 * Move the changed region forward, so long as the
1008 * first changed line matches the following unchanged one.
1009 * This merges with following changed regions.
1010 * Do this second, so that if there are no merges,
1011 * the changed region is moved forward as far as possible.
1013 while ($i < $len && $lines[$start] == $lines[$i]) {
1014 $changed[$start++
] = false;
1016 while ($i < $len && $changed[$i])
1019 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1021 if ($j < $other_len && $other_changed[$j]) {
1022 $corresponding = $i;
1023 while ($j < $other_len && $other_changed[$j])
1027 } while ($runlength != $i - $start);
1030 * If possible, move the fully-merged run of changes
1031 * back to a corresponding run in the other file.
1033 while ($corresponding < $i) {
1034 $changed[--$start] = 1;
1036 USE_ASSERTS
&& assert('$j > 0');
1037 while ($other_changed[--$j])
1039 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1042 wfProfileOut( $fname );
1047 * Class representing a 'diff' between two sequences of strings.
1050 * @package MediaWiki
1051 * @subpackage DifferenceEngine
1059 * Computes diff between sequences of strings.
1061 * @param $from_lines array An array of strings.
1062 * (Typically these are lines from a file.)
1063 * @param $to_lines array An array of strings.
1065 function Diff($from_lines, $to_lines) {
1066 $eng = new _DiffEngine
;
1067 $this->edits
= $eng->diff($from_lines, $to_lines);
1068 //$this->_check($from_lines, $to_lines);
1072 * Compute reversed Diff.
1076 * $diff = new Diff($lines1, $lines2);
1077 * $rev = $diff->reverse();
1078 * @return object A Diff object representing the inverse of the
1081 function reverse () {
1083 $rev->edits
= array();
1084 foreach ($this->edits
as $edit) {
1085 $rev->edits
[] = $edit->reverse();
1091 * Check for empty diff.
1093 * @return bool True iff two sequences were identical.
1095 function isEmpty () {
1096 foreach ($this->edits
as $edit) {
1097 if ($edit->type
!= 'copy')
1104 * Compute the length of the Longest Common Subsequence (LCS).
1106 * This is mostly for diagnostic purposed.
1108 * @return int The length of the LCS.
1112 foreach ($this->edits
as $edit) {
1113 if ($edit->type
== 'copy')
1114 $lcs +
= sizeof($edit->orig
);
1120 * Get the original set of lines.
1122 * This reconstructs the $from_lines parameter passed to the
1125 * @return array The original sequence of strings.
1130 foreach ($this->edits
as $edit) {
1132 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1138 * Get the closing set of lines.
1140 * This reconstructs the $to_lines parameter passed to the
1143 * @return array The sequence of strings.
1145 function closing() {
1148 foreach ($this->edits
as $edit) {
1150 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1156 * Check a Diff for validity.
1158 * This is here only for debugging purposes.
1160 function _check ($from_lines, $to_lines) {
1161 $fname = 'Diff::_check';
1162 wfProfileIn( $fname );
1163 if (serialize($from_lines) != serialize($this->orig()))
1164 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1165 if (serialize($to_lines) != serialize($this->closing()))
1166 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1168 $rev = $this->reverse();
1169 if (serialize($to_lines) != serialize($rev->orig()))
1170 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1171 if (serialize($from_lines) != serialize($rev->closing()))
1172 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1176 foreach ($this->edits
as $edit) {
1177 if ( $prevtype == $edit->type
)
1178 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1179 $prevtype = $edit->type
;
1182 $lcs = $this->lcs();
1183 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1184 wfProfileOut( $fname );
1192 * @package MediaWiki
1193 * @subpackage DifferenceEngine
1195 class MappedDiff
extends Diff
1200 * Computes diff between sequences of strings.
1202 * This can be used to compute things like
1203 * case-insensitve diffs, or diffs which ignore
1204 * changes in white-space.
1206 * @param $from_lines array An array of strings.
1207 * (Typically these are lines from a file.)
1209 * @param $to_lines array An array of strings.
1211 * @param $mapped_from_lines array This array should
1212 * have the same size number of elements as $from_lines.
1213 * The elements in $mapped_from_lines and
1214 * $mapped_to_lines are what is actually compared
1215 * when computing the diff.
1217 * @param $mapped_to_lines array This array should
1218 * have the same number of elements as $to_lines.
1220 function MappedDiff($from_lines, $to_lines,
1221 $mapped_from_lines, $mapped_to_lines) {
1222 $fname = 'MappedDiff::MappedDiff';
1223 wfProfileIn( $fname );
1225 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1226 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1228 $this->Diff($mapped_from_lines, $mapped_to_lines);
1231 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1232 $orig = &$this->edits
[$i]->orig
;
1233 if (is_array($orig)) {
1234 $orig = array_slice($from_lines, $xi, sizeof($orig));
1235 $xi +
= sizeof($orig);
1238 $closing = &$this->edits
[$i]->closing
;
1239 if (is_array($closing)) {
1240 $closing = array_slice($to_lines, $yi, sizeof($closing));
1241 $yi +
= sizeof($closing);
1244 wfProfileOut( $fname );
1249 * A class to format Diffs
1251 * This class formats the diff in classic diff format.
1252 * It is intended that this class be customized via inheritance,
1253 * to obtain fancier outputs.
1256 * @package MediaWiki
1257 * @subpackage DifferenceEngine
1262 * Number of leading context "lines" to preserve.
1264 * This should be left at zero for this class, but subclasses
1265 * may want to set this to other values.
1267 var $leading_context_lines = 0;
1270 * Number of trailing context "lines" to preserve.
1272 * This should be left at zero for this class, but subclasses
1273 * may want to set this to other values.
1275 var $trailing_context_lines = 0;
1280 * @param $diff object A Diff object.
1281 * @return string The formatted output.
1283 function format($diff) {
1284 $fname = 'DiffFormatter::format';
1285 wfProfileIn( $fname );
1291 $nlead = $this->leading_context_lines
;
1292 $ntrail = $this->trailing_context_lines
;
1294 $this->_start_diff();
1296 foreach ($diff->edits
as $edit) {
1297 if ($edit->type
== 'copy') {
1298 if (is_array($block)) {
1299 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1304 $context = array_slice($edit->orig
, 0, $ntrail);
1305 $block[] = new _DiffOp_Copy($context);
1307 $this->_block($x0, $ntrail +
$xi - $x0,
1308 $y0, $ntrail +
$yi - $y0,
1313 $context = $edit->orig
;
1316 if (! is_array($block)) {
1317 $context = array_slice($context, sizeof($context) - $nlead);
1318 $x0 = $xi - sizeof($context);
1319 $y0 = $yi - sizeof($context);
1322 $block[] = new _DiffOp_Copy($context);
1328 $xi +
= sizeof($edit->orig
);
1330 $yi +
= sizeof($edit->closing
);
1333 if (is_array($block))
1334 $this->_block($x0, $xi - $x0,
1338 $end = $this->_end_diff();
1339 wfProfileOut( $fname );
1343 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1344 $fname = 'DiffFormatter::_block';
1345 wfProfileIn( $fname );
1346 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1347 foreach ($edits as $edit) {
1348 if ($edit->type
== 'copy')
1349 $this->_context($edit->orig
);
1350 elseif ($edit->type
== 'add')
1351 $this->_added($edit->closing
);
1352 elseif ($edit->type
== 'delete')
1353 $this->_deleted($edit->orig
);
1354 elseif ($edit->type
== 'change')
1355 $this->_changed($edit->orig
, $edit->closing
);
1357 trigger_error('Unknown edit type', E_USER_ERROR
);
1359 $this->_end_block();
1360 wfProfileOut( $fname );
1363 function _start_diff() {
1367 function _end_diff() {
1368 $val = ob_get_contents();
1373 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1375 $xbeg .= "," . ($xbeg +
$xlen - 1);
1377 $ybeg .= "," . ($ybeg +
$ylen - 1);
1379 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1382 function _start_block($header) {
1386 function _end_block() {
1389 function _lines($lines, $prefix = ' ') {
1390 foreach ($lines as $line)
1391 echo "$prefix $line\n";
1394 function _context($lines) {
1395 $this->_lines($lines);
1398 function _added($lines) {
1399 $this->_lines($lines, '>');
1401 function _deleted($lines) {
1402 $this->_lines($lines, '<');
1405 function _changed($orig, $closing) {
1406 $this->_deleted($orig);
1408 $this->_added($closing);
1414 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1418 define('NBSP', ' '); // iso-8859-x non-breaking space.
1423 * @package MediaWiki
1424 * @subpackage DifferenceEngine
1426 class _HWLDF_WordAccumulator
{
1427 function _HWLDF_WordAccumulator () {
1428 $this->_lines
= array();
1434 function _flushGroup ($new_tag) {
1435 if ($this->_group
!== '') {
1436 if ($this->_tag
== 'mark')
1437 $this->_line
.= '<span class="diffchange">' .
1438 htmlspecialchars ( $this->_group
) . '</span>';
1440 $this->_line
.= htmlspecialchars ( $this->_group
);
1443 $this->_tag
= $new_tag;
1446 function _flushLine ($new_tag) {
1447 $this->_flushGroup($new_tag);
1448 if ($this->_line
!= '')
1449 array_push ( $this->_lines
, $this->_line
);
1451 # make empty lines visible by inserting an NBSP
1452 array_push ( $this->_lines
, NBSP
);
1456 function addWords ($words, $tag = '') {
1457 if ($tag != $this->_tag
)
1458 $this->_flushGroup($tag);
1460 foreach ($words as $word) {
1461 // new-line should only come as first char of word.
1464 if ($word[0] == "\n") {
1465 $this->_flushLine($tag);
1466 $word = substr($word, 1);
1468 assert(!strstr($word, "\n"));
1469 $this->_group
.= $word;
1473 function getLines() {
1474 $this->_flushLine('~done');
1475 return $this->_lines
;
1482 * @package MediaWiki
1483 * @subpackage DifferenceEngine
1485 class WordLevelDiff
extends MappedDiff
1487 function WordLevelDiff ($orig_lines, $closing_lines) {
1488 $fname = 'WordLevelDiff::WordLevelDiff';
1489 wfProfileIn( $fname );
1491 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1492 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1494 $this->MappedDiff($orig_words, $closing_words,
1495 $orig_stripped, $closing_stripped);
1496 wfProfileOut( $fname );
1499 function _split($lines) {
1500 $fname = 'WordLevelDiff::_split';
1501 wfProfileIn( $fname );
1504 $stripped = array();
1506 foreach ( $lines as $line ) {
1507 # If the line is too long, just pretend the entire line is one big word
1508 # This prevents resource exhaustion problems
1515 if ( strlen( $line ) > MAX_DIFF_LINE
) {
1517 $stripped[] = $line;
1519 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1522 $words = array_merge( $words, $m[0] );
1523 $stripped = array_merge( $stripped, $m[1] );
1527 wfProfileOut( $fname );
1528 return array($words, $stripped);
1532 $fname = 'WordLevelDiff::orig';
1533 wfProfileIn( $fname );
1534 $orig = new _HWLDF_WordAccumulator
;
1536 foreach ($this->edits
as $edit) {
1537 if ($edit->type
== 'copy')
1538 $orig->addWords($edit->orig
);
1539 elseif ($edit->orig
)
1540 $orig->addWords($edit->orig
, 'mark');
1542 $lines = $orig->getLines();
1543 wfProfileOut( $fname );
1547 function closing () {
1548 $fname = 'WordLevelDiff::closing';
1549 wfProfileIn( $fname );
1550 $closing = new _HWLDF_WordAccumulator
;
1552 foreach ($this->edits
as $edit) {
1553 if ($edit->type
== 'copy')
1554 $closing->addWords($edit->closing
);
1555 elseif ($edit->closing
)
1556 $closing->addWords($edit->closing
, 'mark');
1558 $lines = $closing->getLines();
1559 wfProfileOut( $fname );
1565 * Wikipedia Table style diff formatter.
1568 * @package MediaWiki
1569 * @subpackage DifferenceEngine
1571 class TableDiffFormatter
extends DiffFormatter
1573 function TableDiffFormatter() {
1574 $this->leading_context_lines
= 2;
1575 $this->trailing_context_lines
= 2;
1578 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1579 $l1 = wfMsg( 'lineno', $xbeg );
1580 $l2 = wfMsg( 'lineno', $ybeg );
1582 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1583 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1587 function _start_block( $header ) {
1592 function _end_block() {
1595 function _lines( $lines, $prefix=' ', $color='white' ) {
1598 # HTML-escape parameter before calling this
1599 function addedLine( $line ) {
1600 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1603 # HTML-escape parameter before calling this
1604 function deletedLine( $line ) {
1605 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1608 # HTML-escape parameter before calling this
1609 function contextLine( $line ) {
1610 return "<td> </td><td class='diff-context'>{$line}</td>";
1613 function emptyLine() {
1614 return '<td colspan="2"> </td>';
1617 function _added( $lines ) {
1618 foreach ($lines as $line) {
1619 echo '<tr>' . $this->emptyLine() .
1620 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1624 function _deleted($lines) {
1625 foreach ($lines as $line) {
1626 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1627 $this->emptyLine() . "</tr>\n";
1631 function _context( $lines ) {
1632 foreach ($lines as $line) {
1634 $this->contextLine( htmlspecialchars ( $line ) ) .
1635 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1639 function _changed( $orig, $closing ) {
1640 $fname = 'TableDiffFormatter::_changed';
1641 wfProfileIn( $fname );
1643 $diff = new WordLevelDiff( $orig, $closing );
1644 $del = $diff->orig();
1645 $add = $diff->closing();
1647 # Notice that WordLevelDiff returns HTML-escaped output.
1648 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1650 while ( $line = array_shift( $del ) ) {
1651 $aline = array_shift( $add );
1652 echo '<tr>' . $this->deletedLine( $line ) .
1653 $this->addedLine( $aline ) . "</tr>\n";
1655 foreach ($add as $line) { # If any leftovers
1656 echo '<tr>' . $this->emptyLine() .
1657 $this->addedLine( $line ) . "</tr>\n";
1659 wfProfileOut( $fname );