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->addSecondaryWikiText( $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->addSecondaryWikiText( $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' );
328 $difftext .= "\n<!-- diff cache key $key -->\n";
333 if ( !$this->loadText() ) {
337 $otext = $wgContLang->segmentForDiff($this->mOldtext
);
338 $ntext = $wgContLang->segmentForDiff($this->mNewtext
);
339 if ( $wgUseExternalDiffEngine ) {
340 # For historical reasons, external diff engine expects
341 # input text to be HTML-escaped already
342 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
343 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
344 if( !function_exists( 'wikidiff_do_diff' ) ) {
345 dl('php_wikidiff.so');
347 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
349 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
350 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
351 $diffs =& new Diff( $ota, $nta );
352 $formatter =& new TableDiffFormatter();
353 $difftext = $formatter->format( $diffs );
355 $difftext = $wgContLang->unsegmentForDiff($difftext);
357 // Save to cache for 7 days
358 if ( $key !== false ) {
359 wfIncrStats( 'diff_cache_miss' );
360 $wgMemc->set( $key, $difftext, 7*86400 );
362 wfIncrStats( 'diff_uncacheable' );
368 * Add the header to a diff body
370 function addHeader( $diff, $otitle, $ntitle ) {
372 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
374 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
375 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
384 * Use specified text instead of loading from the database
386 function setText( $oldText, $newText ) {
387 $this->mOldtext
= $oldText;
388 $this->mNewtext
= $newText;
389 $this->mTextLoaded
= 2;
393 * Load revision metadata for the specified articles. If newid is 0, then compare
394 * the old article in oldid to the current article; if oldid is 0, then
395 * compare the current article to the immediately previous one (ignoring the
398 * If oldid is false, leave the corresponding revision object set
399 * to false. This is impossible via ordinary user input, and is provided for
402 function loadRevisionData() {
404 if ( $this->mRevisionsLoaded
) {
407 // Whether it succeeds or fails, we don't want to try again
408 $this->mRevisionsLoaded
= true;
411 // Load the new revision object
412 if( $this->mNewid
) {
413 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
415 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
418 if( is_null( $this->mNewRev
) ) {
422 // Set assorted variables
423 if( $this->mNewRev
->isCurrent() ) {
424 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
425 $this->mNewPage
= $this->mTitle
;
426 $newLink = $this->mNewPage
->escapeLocalUrl();
427 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
429 $this->mNewPage
= $this->mNewRev
->getTitle();
430 $newLink = $this->mNewPage
->escapeLocalUrl ('oldid=' . $this->mNewid
);
431 $t = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
432 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
433 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
436 $this->mNewUser
= $this->mNewRev
->getUserText();
437 $this->mNewComment
= $this->mNewRev
->getComment();
439 // Load the old revision object
440 $this->mOldRev
= false;
441 if( $this->mOldid
) {
442 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
443 } elseif ( $this->mOldid
=== 0 ) {
444 $this->mOldRev
= $this->mNewRev
->getPrevious();
445 $this->mOldid
= $this->mOldRev
->getId();
446 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
448 if( is_null( $this->mOldRev
) ) {
452 if ( $this->mOldRev
) {
453 $this->mOldPage
= $this->mOldRev
->getTitle();
455 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
456 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
457 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
460 $this->mOldUser
= $this->mOldRev
->getUserText();
461 $this->mOldComment
= $this->mOldRev
->getComment();
468 * Load the text of the revisions, as well as revision data.
470 function loadText() {
471 if ( $this->mTextLoaded
== 2 ) {
474 // Whether it succeeds or fails, we don't want to try again
475 $this->mTextLoaded
= 2;
478 if ( !$this->loadRevisionData() ) {
481 if ( $this->mOldRev
) {
482 $this->mOldtext
= $this->mOldRev
->getText();
483 if ( $this->mOldtext
=== false ) {
487 if ( $this->mNewRev
) {
488 $this->mNewtext
= $this->mNewRev
->getText();
489 if ( $this->mNewtext
=== false ) {
497 * Load the text of the new revision, not the old one
499 function loadNewText() {
500 if ( $this->mTextLoaded
>= 1 ) {
503 $this->mTextLoaded
= 1;
505 if ( !$this->loadRevisionData() ) {
508 $this->mNewtext
= $this->mNewRev
->getText();
515 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
517 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
518 // You may copy this code freely under the conditions of the GPL.
521 define('USE_ASSERTS', function_exists('assert'));
527 * @subpackage DifferenceEngine
535 trigger_error('pure virtual', E_USER_ERROR
);
539 return $this->orig ?
sizeof($this->orig
) : 0;
542 function nclosing() {
543 return $this->closing ?
sizeof($this->closing
) : 0;
551 * @subpackage DifferenceEngine
553 class _DiffOp_Copy
extends _DiffOp
{
556 function _DiffOp_Copy ($orig, $closing = false) {
557 if (!is_array($closing))
560 $this->closing
= $closing;
564 return new _DiffOp_Copy($this->closing
, $this->orig
);
572 * @subpackage DifferenceEngine
574 class _DiffOp_Delete
extends _DiffOp
{
575 var $type = 'delete';
577 function _DiffOp_Delete ($lines) {
578 $this->orig
= $lines;
579 $this->closing
= false;
583 return new _DiffOp_Add($this->orig
);
591 * @subpackage DifferenceEngine
593 class _DiffOp_Add
extends _DiffOp
{
596 function _DiffOp_Add ($lines) {
597 $this->closing
= $lines;
602 return new _DiffOp_Delete($this->closing
);
610 * @subpackage DifferenceEngine
612 class _DiffOp_Change
extends _DiffOp
{
613 var $type = 'change';
615 function _DiffOp_Change ($orig, $closing) {
617 $this->closing
= $closing;
621 return new _DiffOp_Change($this->closing
, $this->orig
);
627 * Class used internally by Diff to actually compute the diffs.
629 * The algorithm used here is mostly lifted from the perl module
630 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
631 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
633 * More ideas are taken from:
634 * http://www.ics.uci.edu/~eppstein/161/960229.html
636 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
637 * diffutils-2.7, which can be found at:
638 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
640 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
643 * Line length limits for robustness added by Tim Starling, 2005-08-31
645 * @author Geoffrey T. Dairiki, Tim Starling
648 * @subpackage DifferenceEngine
652 function diff ($from_lines, $to_lines) {
653 $fname = '_DiffEngine::diff';
654 wfProfileIn( $fname );
656 $n_from = sizeof($from_lines);
657 $n_to = sizeof($to_lines);
659 $this->xchanged
= $this->ychanged
= array();
660 $this->xv
= $this->yv
= array();
661 $this->xind
= $this->yind
= array();
663 unset($this->in_seq
);
666 // Skip leading common lines.
667 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
668 if ($from_lines[$skip] !== $to_lines[$skip])
670 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
672 // Skip trailing common lines.
673 $xi = $n_from; $yi = $n_to;
674 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
675 if ($from_lines[$xi] !== $to_lines[$yi])
677 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
680 // Ignore lines which do not exist in both files.
681 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
682 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
685 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
686 $line = $to_lines[$yi];
687 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
689 $yhash[$this->_line_hash($line)] = 1;
693 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
694 $line = $from_lines[$xi];
695 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
702 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
704 // Merge edits when possible
705 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
706 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
708 // Compute the edit operations.
711 while ($xi < $n_from ||
$yi < $n_to) {
712 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
713 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
715 // Skip matching "snake".
717 while ( $xi < $n_from && $yi < $n_to
718 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
719 $copy[] = $from_lines[$xi++
];
723 $edits[] = new _DiffOp_Copy($copy);
725 // Find deletes & adds.
727 while ($xi < $n_from && $this->xchanged
[$xi])
728 $delete[] = $from_lines[$xi++
];
731 while ($yi < $n_to && $this->ychanged
[$yi])
732 $add[] = $to_lines[$yi++
];
735 $edits[] = new _DiffOp_Change($delete, $add);
737 $edits[] = new _DiffOp_Delete($delete);
739 $edits[] = new _DiffOp_Add($add);
741 wfProfileOut( $fname );
746 * Returns the whole line if it's small enough, or the MD5 hash otherwise
748 function _line_hash( $line ) {
749 if ( strlen( $line ) > MAX_DIFF_XREF_LENGTH
) {
757 /* Divide the Largest Common Subsequence (LCS) of the sequences
758 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
761 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
762 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
763 * sub sequences. The first sub-sequence is contained in [X0, X1),
764 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
765 * that (X0, Y0) == (XOFF, YOFF) and
766 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
768 * This function assumes that the first lines of the specified portions
769 * of the two files do not match, and likewise that the last lines do not
770 * match. The caller must trim matching lines from the beginning and end
771 * of the portions it is going to specify.
773 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
774 $fname = '_DiffEngine::_diag';
775 wfProfileIn( $fname );
778 if ($xlim - $xoff > $ylim - $yoff) {
779 // Things seems faster (I'm not sure I understand why)
780 // when the shortest sequence in X.
782 list ($xoff, $xlim, $yoff, $ylim)
783 = array( $yoff, $ylim, $xoff, $xlim);
787 for ($i = $ylim - 1; $i >= $yoff; $i--)
788 $ymatches[$this->xv
[$i]][] = $i;
790 for ($i = $ylim - 1; $i >= $yoff; $i--)
791 $ymatches[$this->yv
[$i]][] = $i;
794 $this->seq
[0]= $yoff - 1;
795 $this->in_seq
= array();
798 $numer = $xlim - $xoff +
$nchunks - 1;
800 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
801 wfProfileIn( "$fname-chunk" );
803 for ($i = 0; $i <= $this->lcs
; $i++
)
804 $ymids[$i][$chunk-1] = $this->seq
[$i];
806 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
807 for ( ; $x < $x1; $x++
) {
808 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
809 if (empty($ymatches[$line]))
811 $matches = $ymatches[$line];
813 while (list ($junk, $y) = each($matches))
814 if (empty($this->in_seq
[$y])) {
815 $k = $this->_lcs_pos($y);
816 USE_ASSERTS
&& assert($k > 0);
817 $ymids[$k] = $ymids[$k-1];
820 while (list ($junk, $y) = each($matches)) {
821 if ($y > $this->seq
[$k-1]) {
822 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
823 // Optimization: this is a common case:
824 // next match is just replacing previous match.
825 $this->in_seq
[$this->seq
[$k]] = false;
827 $this->in_seq
[$y] = 1;
828 } else if (empty($this->in_seq
[$y])) {
829 $k = $this->_lcs_pos($y);
830 USE_ASSERTS
&& assert($k > 0);
831 $ymids[$k] = $ymids[$k-1];
835 wfProfileOut( "$fname-chunk" );
838 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
839 $ymid = $ymids[$this->lcs
];
840 for ($n = 0; $n < $nchunks - 1; $n++
) {
841 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
843 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
845 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
847 wfProfileOut( $fname );
848 return array($this->lcs
, $seps);
851 function _lcs_pos ($ypos) {
852 $fname = '_DiffEngine::_lcs_pos';
853 wfProfileIn( $fname );
856 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
857 $this->seq
[++
$this->lcs
] = $ypos;
858 $this->in_seq
[$ypos] = 1;
859 wfProfileOut( $fname );
864 while ($beg < $end) {
865 $mid = (int)(($beg +
$end) / 2);
866 if ( $ypos > $this->seq
[$mid] )
872 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
874 $this->in_seq
[$this->seq
[$end]] = false;
875 $this->seq
[$end] = $ypos;
876 $this->in_seq
[$ypos] = 1;
877 wfProfileOut( $fname );
881 /* Find LCS of two sequences.
883 * The results are recorded in the vectors $this->{x,y}changed[], by
884 * storing a 1 in the element for each line that is an insertion
885 * or deletion (ie. is not in the LCS).
887 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
889 * Note that XLIM, YLIM are exclusive bounds.
890 * All line numbers are origin-0 and discarded lines are not counted.
892 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
893 $fname = '_DiffEngine::_compareseq';
894 wfProfileIn( $fname );
896 // Slide down the bottom initial diagonal.
897 while ($xoff < $xlim && $yoff < $ylim
898 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
903 // Slide up the top initial diagonal.
904 while ($xlim > $xoff && $ylim > $yoff
905 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
910 if ($xoff == $xlim ||
$yoff == $ylim)
913 // This is ad hoc but seems to work well.
914 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
915 //$nchunks = max(2,min(8,(int)$nchunks));
916 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
918 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
922 // X and Y sequences have no common subsequence:
924 while ($yoff < $ylim)
925 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
926 while ($xoff < $xlim)
927 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
929 // Use the partitions to split this problem into subproblems.
932 while ($pt2 = next($seps)) {
933 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
937 wfProfileOut( $fname );
940 /* Adjust inserts/deletes of identical lines to join changes
941 * as much as possible.
943 * We do something when a run of changed lines include a
944 * line at one end and has an excluded, identical line at the other.
945 * We are free to choose which identical line is included.
946 * `compareseq' usually chooses the one at the beginning,
947 * but usually it is cleaner to consider the following identical line
948 * to be the "change".
950 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
952 function _shift_boundaries ($lines, &$changed, $other_changed) {
953 $fname = '_DiffEngine::_shift_boundaries';
954 wfProfileIn( $fname );
958 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
959 $len = sizeof($lines);
960 $other_len = sizeof($other_changed);
964 * Scan forwards to find beginning of another run of changes.
965 * Also keep track of the corresponding point in the other file.
967 * Throughout this code, $i and $j are adjusted together so that
968 * the first $i elements of $changed and the first $j elements
969 * of $other_changed both contain the same number of zeros
971 * Furthermore, $j is always kept so that $j == $other_len or
972 * $other_changed[$j] == false.
974 while ($j < $other_len && $other_changed[$j])
977 while ($i < $len && ! $changed[$i]) {
978 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
980 while ($j < $other_len && $other_changed[$j])
989 // Find the end of this run of changes.
990 while (++
$i < $len && $changed[$i])
995 * Record the length of this run of changes, so that
996 * we can later determine whether the run has grown.
998 $runlength = $i - $start;
1001 * Move the changed region back, so long as the
1002 * previous unchanged line matches the last changed one.
1003 * This merges with previous changed regions.
1005 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1006 $changed[--$start] = 1;
1007 $changed[--$i] = false;
1008 while ($start > 0 && $changed[$start - 1])
1010 USE_ASSERTS
&& assert('$j > 0');
1011 while ($other_changed[--$j])
1013 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1017 * Set CORRESPONDING to the end of the changed run, at the last
1018 * point where it corresponds to a changed run in the other file.
1019 * CORRESPONDING == LEN means no such point has been found.
1021 $corresponding = $j < $other_len ?
$i : $len;
1024 * Move the changed region forward, so long as the
1025 * first changed line matches the following unchanged one.
1026 * This merges with following changed regions.
1027 * Do this second, so that if there are no merges,
1028 * the changed region is moved forward as far as possible.
1030 while ($i < $len && $lines[$start] == $lines[$i]) {
1031 $changed[$start++
] = false;
1033 while ($i < $len && $changed[$i])
1036 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1038 if ($j < $other_len && $other_changed[$j]) {
1039 $corresponding = $i;
1040 while ($j < $other_len && $other_changed[$j])
1044 } while ($runlength != $i - $start);
1047 * If possible, move the fully-merged run of changes
1048 * back to a corresponding run in the other file.
1050 while ($corresponding < $i) {
1051 $changed[--$start] = 1;
1053 USE_ASSERTS
&& assert('$j > 0');
1054 while ($other_changed[--$j])
1056 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1059 wfProfileOut( $fname );
1064 * Class representing a 'diff' between two sequences of strings.
1067 * @package MediaWiki
1068 * @subpackage DifferenceEngine
1076 * Computes diff between sequences of strings.
1078 * @param $from_lines array An array of strings.
1079 * (Typically these are lines from a file.)
1080 * @param $to_lines array An array of strings.
1082 function Diff($from_lines, $to_lines) {
1083 $eng = new _DiffEngine
;
1084 $this->edits
= $eng->diff($from_lines, $to_lines);
1085 //$this->_check($from_lines, $to_lines);
1089 * Compute reversed Diff.
1093 * $diff = new Diff($lines1, $lines2);
1094 * $rev = $diff->reverse();
1095 * @return object A Diff object representing the inverse of the
1098 function reverse () {
1100 $rev->edits
= array();
1101 foreach ($this->edits
as $edit) {
1102 $rev->edits
[] = $edit->reverse();
1108 * Check for empty diff.
1110 * @return bool True iff two sequences were identical.
1112 function isEmpty () {
1113 foreach ($this->edits
as $edit) {
1114 if ($edit->type
!= 'copy')
1121 * Compute the length of the Longest Common Subsequence (LCS).
1123 * This is mostly for diagnostic purposed.
1125 * @return int The length of the LCS.
1129 foreach ($this->edits
as $edit) {
1130 if ($edit->type
== 'copy')
1131 $lcs +
= sizeof($edit->orig
);
1137 * Get the original set of lines.
1139 * This reconstructs the $from_lines parameter passed to the
1142 * @return array The original sequence of strings.
1147 foreach ($this->edits
as $edit) {
1149 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1155 * Get the closing set of lines.
1157 * This reconstructs the $to_lines parameter passed to the
1160 * @return array The sequence of strings.
1162 function closing() {
1165 foreach ($this->edits
as $edit) {
1167 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1173 * Check a Diff for validity.
1175 * This is here only for debugging purposes.
1177 function _check ($from_lines, $to_lines) {
1178 $fname = 'Diff::_check';
1179 wfProfileIn( $fname );
1180 if (serialize($from_lines) != serialize($this->orig()))
1181 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1182 if (serialize($to_lines) != serialize($this->closing()))
1183 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1185 $rev = $this->reverse();
1186 if (serialize($to_lines) != serialize($rev->orig()))
1187 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1188 if (serialize($from_lines) != serialize($rev->closing()))
1189 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1193 foreach ($this->edits
as $edit) {
1194 if ( $prevtype == $edit->type
)
1195 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1196 $prevtype = $edit->type
;
1199 $lcs = $this->lcs();
1200 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1201 wfProfileOut( $fname );
1209 * @package MediaWiki
1210 * @subpackage DifferenceEngine
1212 class MappedDiff
extends Diff
1217 * Computes diff between sequences of strings.
1219 * This can be used to compute things like
1220 * case-insensitve diffs, or diffs which ignore
1221 * changes in white-space.
1223 * @param $from_lines array An array of strings.
1224 * (Typically these are lines from a file.)
1226 * @param $to_lines array An array of strings.
1228 * @param $mapped_from_lines array This array should
1229 * have the same size number of elements as $from_lines.
1230 * The elements in $mapped_from_lines and
1231 * $mapped_to_lines are what is actually compared
1232 * when computing the diff.
1234 * @param $mapped_to_lines array This array should
1235 * have the same number of elements as $to_lines.
1237 function MappedDiff($from_lines, $to_lines,
1238 $mapped_from_lines, $mapped_to_lines) {
1239 $fname = 'MappedDiff::MappedDiff';
1240 wfProfileIn( $fname );
1242 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1243 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1245 $this->Diff($mapped_from_lines, $mapped_to_lines);
1248 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1249 $orig = &$this->edits
[$i]->orig
;
1250 if (is_array($orig)) {
1251 $orig = array_slice($from_lines, $xi, sizeof($orig));
1252 $xi +
= sizeof($orig);
1255 $closing = &$this->edits
[$i]->closing
;
1256 if (is_array($closing)) {
1257 $closing = array_slice($to_lines, $yi, sizeof($closing));
1258 $yi +
= sizeof($closing);
1261 wfProfileOut( $fname );
1266 * A class to format Diffs
1268 * This class formats the diff in classic diff format.
1269 * It is intended that this class be customized via inheritance,
1270 * to obtain fancier outputs.
1273 * @package MediaWiki
1274 * @subpackage DifferenceEngine
1279 * Number of leading context "lines" to preserve.
1281 * This should be left at zero for this class, but subclasses
1282 * may want to set this to other values.
1284 var $leading_context_lines = 0;
1287 * Number of trailing context "lines" to preserve.
1289 * This should be left at zero for this class, but subclasses
1290 * may want to set this to other values.
1292 var $trailing_context_lines = 0;
1297 * @param $diff object A Diff object.
1298 * @return string The formatted output.
1300 function format($diff) {
1301 $fname = 'DiffFormatter::format';
1302 wfProfileIn( $fname );
1308 $nlead = $this->leading_context_lines
;
1309 $ntrail = $this->trailing_context_lines
;
1311 $this->_start_diff();
1313 foreach ($diff->edits
as $edit) {
1314 if ($edit->type
== 'copy') {
1315 if (is_array($block)) {
1316 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1321 $context = array_slice($edit->orig
, 0, $ntrail);
1322 $block[] = new _DiffOp_Copy($context);
1324 $this->_block($x0, $ntrail +
$xi - $x0,
1325 $y0, $ntrail +
$yi - $y0,
1330 $context = $edit->orig
;
1333 if (! is_array($block)) {
1334 $context = array_slice($context, sizeof($context) - $nlead);
1335 $x0 = $xi - sizeof($context);
1336 $y0 = $yi - sizeof($context);
1339 $block[] = new _DiffOp_Copy($context);
1345 $xi +
= sizeof($edit->orig
);
1347 $yi +
= sizeof($edit->closing
);
1350 if (is_array($block))
1351 $this->_block($x0, $xi - $x0,
1355 $end = $this->_end_diff();
1356 wfProfileOut( $fname );
1360 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1361 $fname = 'DiffFormatter::_block';
1362 wfProfileIn( $fname );
1363 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1364 foreach ($edits as $edit) {
1365 if ($edit->type
== 'copy')
1366 $this->_context($edit->orig
);
1367 elseif ($edit->type
== 'add')
1368 $this->_added($edit->closing
);
1369 elseif ($edit->type
== 'delete')
1370 $this->_deleted($edit->orig
);
1371 elseif ($edit->type
== 'change')
1372 $this->_changed($edit->orig
, $edit->closing
);
1374 trigger_error('Unknown edit type', E_USER_ERROR
);
1376 $this->_end_block();
1377 wfProfileOut( $fname );
1380 function _start_diff() {
1384 function _end_diff() {
1385 $val = ob_get_contents();
1390 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1392 $xbeg .= "," . ($xbeg +
$xlen - 1);
1394 $ybeg .= "," . ($ybeg +
$ylen - 1);
1396 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1399 function _start_block($header) {
1403 function _end_block() {
1406 function _lines($lines, $prefix = ' ') {
1407 foreach ($lines as $line)
1408 echo "$prefix $line\n";
1411 function _context($lines) {
1412 $this->_lines($lines);
1415 function _added($lines) {
1416 $this->_lines($lines, '>');
1418 function _deleted($lines) {
1419 $this->_lines($lines, '<');
1422 function _changed($orig, $closing) {
1423 $this->_deleted($orig);
1425 $this->_added($closing);
1431 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1435 define('NBSP', ' '); // iso-8859-x non-breaking space.
1440 * @package MediaWiki
1441 * @subpackage DifferenceEngine
1443 class _HWLDF_WordAccumulator
{
1444 function _HWLDF_WordAccumulator () {
1445 $this->_lines
= array();
1451 function _flushGroup ($new_tag) {
1452 if ($this->_group
!== '') {
1453 if ($this->_tag
== 'mark')
1454 $this->_line
.= '<span class="diffchange">' .
1455 htmlspecialchars ( $this->_group
) . '</span>';
1457 $this->_line
.= htmlspecialchars ( $this->_group
);
1460 $this->_tag
= $new_tag;
1463 function _flushLine ($new_tag) {
1464 $this->_flushGroup($new_tag);
1465 if ($this->_line
!= '')
1466 array_push ( $this->_lines
, $this->_line
);
1468 # make empty lines visible by inserting an NBSP
1469 array_push ( $this->_lines
, NBSP
);
1473 function addWords ($words, $tag = '') {
1474 if ($tag != $this->_tag
)
1475 $this->_flushGroup($tag);
1477 foreach ($words as $word) {
1478 // new-line should only come as first char of word.
1481 if ($word[0] == "\n") {
1482 $this->_flushLine($tag);
1483 $word = substr($word, 1);
1485 assert(!strstr($word, "\n"));
1486 $this->_group
.= $word;
1490 function getLines() {
1491 $this->_flushLine('~done');
1492 return $this->_lines
;
1499 * @package MediaWiki
1500 * @subpackage DifferenceEngine
1502 class WordLevelDiff
extends MappedDiff
1504 function WordLevelDiff ($orig_lines, $closing_lines) {
1505 $fname = 'WordLevelDiff::WordLevelDiff';
1506 wfProfileIn( $fname );
1508 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1509 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1511 $this->MappedDiff($orig_words, $closing_words,
1512 $orig_stripped, $closing_stripped);
1513 wfProfileOut( $fname );
1516 function _split($lines) {
1517 $fname = 'WordLevelDiff::_split';
1518 wfProfileIn( $fname );
1521 $stripped = array();
1523 foreach ( $lines as $line ) {
1524 # If the line is too long, just pretend the entire line is one big word
1525 # This prevents resource exhaustion problems
1532 if ( strlen( $line ) > MAX_DIFF_LINE
) {
1534 $stripped[] = $line;
1536 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1539 $words = array_merge( $words, $m[0] );
1540 $stripped = array_merge( $stripped, $m[1] );
1544 wfProfileOut( $fname );
1545 return array($words, $stripped);
1549 $fname = 'WordLevelDiff::orig';
1550 wfProfileIn( $fname );
1551 $orig = new _HWLDF_WordAccumulator
;
1553 foreach ($this->edits
as $edit) {
1554 if ($edit->type
== 'copy')
1555 $orig->addWords($edit->orig
);
1556 elseif ($edit->orig
)
1557 $orig->addWords($edit->orig
, 'mark');
1559 $lines = $orig->getLines();
1560 wfProfileOut( $fname );
1564 function closing () {
1565 $fname = 'WordLevelDiff::closing';
1566 wfProfileIn( $fname );
1567 $closing = new _HWLDF_WordAccumulator
;
1569 foreach ($this->edits
as $edit) {
1570 if ($edit->type
== 'copy')
1571 $closing->addWords($edit->closing
);
1572 elseif ($edit->closing
)
1573 $closing->addWords($edit->closing
, 'mark');
1575 $lines = $closing->getLines();
1576 wfProfileOut( $fname );
1582 * Wikipedia Table style diff formatter.
1585 * @package MediaWiki
1586 * @subpackage DifferenceEngine
1588 class TableDiffFormatter
extends DiffFormatter
1590 function TableDiffFormatter() {
1591 $this->leading_context_lines
= 2;
1592 $this->trailing_context_lines
= 2;
1595 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1596 $l1 = wfMsg( 'lineno', $xbeg );
1597 $l2 = wfMsg( 'lineno', $ybeg );
1599 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1600 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1604 function _start_block( $header ) {
1609 function _end_block() {
1612 function _lines( $lines, $prefix=' ', $color='white' ) {
1615 # HTML-escape parameter before calling this
1616 function addedLine( $line ) {
1617 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1620 # HTML-escape parameter before calling this
1621 function deletedLine( $line ) {
1622 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1625 # HTML-escape parameter before calling this
1626 function contextLine( $line ) {
1627 return "<td> </td><td class='diff-context'>{$line}</td>";
1630 function emptyLine() {
1631 return '<td colspan="2"> </td>';
1634 function _added( $lines ) {
1635 foreach ($lines as $line) {
1636 echo '<tr>' . $this->emptyLine() .
1637 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1641 function _deleted($lines) {
1642 foreach ($lines as $line) {
1643 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1644 $this->emptyLine() . "</tr>\n";
1648 function _context( $lines ) {
1649 foreach ($lines as $line) {
1651 $this->contextLine( htmlspecialchars ( $line ) ) .
1652 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1656 function _changed( $orig, $closing ) {
1657 $fname = 'TableDiffFormatter::_changed';
1658 wfProfileIn( $fname );
1660 $diff = new WordLevelDiff( $orig, $closing );
1661 $del = $diff->orig();
1662 $add = $diff->closing();
1664 # Notice that WordLevelDiff returns HTML-escaped output.
1665 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1667 while ( $line = array_shift( $del ) ) {
1668 $aline = array_shift( $add );
1669 echo '<tr>' . $this->deletedLine( $line ) .
1670 $this->addedLine( $aline ) . "</tr>\n";
1672 foreach ($add as $line) { # If any leftovers
1673 echo '<tr>' . $this->emptyLine() .
1674 $this->addedLine( $line ) . "</tr>\n";
1676 wfProfileOut( $fname );