4 * @todo indicate where diff.doc can be found.
5 * @addtogroup DifferenceEngine
9 * Constant to indicate diff cache compatibility.
10 * Bump this when changing the diff formatting in a way that
11 * fixes important bugs or such to force cached diff views to
14 define( 'MW_DIFF_VERSION', '1.11a' );
19 * @addtogroup DifferenceEngine
21 class DifferenceEngine
{
25 var $mOldid, $mNewid, $mTitle;
26 var $mOldtitle, $mNewtitle, $mPagetitle;
27 var $mOldtext, $mNewtext;
28 var $mOldPage, $mNewPage;
29 var $mRcidMarkPatrolled;
30 var $mOldRev, $mNewRev;
31 var $mRevisionsLoaded = false; // Have the revisions been loaded
32 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
37 * @param $titleObj Title object that the diff is associated with
38 * @param $old Integer: old ID we want to show and diff with.
39 * @param $new String: either 'prev' or 'next'.
40 * @param $rcid Integer: ??? FIXME (default 0)
42 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
43 $this->mTitle
= $titleObj;
44 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
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( $diffOnly = false ) {
74 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
75 $fname = 'DifferenceEngine::showDiffPage';
76 wfProfileIn( $fname );
78 # If external diffs are enabled both globally and for the user,
79 # we'll use the application/x-external-editor interface to call
80 # an external diff tool like kompare, kdiff3, etc.
81 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
82 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
84 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
85 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
86 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
87 $special=$wgLang->getNsText(NS_SPECIAL
);
92 Script={$wgServer}{$wgScript}
93 Special namespace={$special}
107 $wgOut->setArticleFlag( false );
108 if ( ! $this->loadRevisionData() ) {
109 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
110 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
111 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
112 $wgOut->addWikitext( $mtext );
113 wfProfileOut( $fname );
117 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
119 if ( $this->mNewRev
->isCurrent() ) {
120 $wgOut->setArticleFlag( true );
123 # mOldid is false if the difference engine is called with a "vague" query for
124 # a diff between a version V and its previous version V' AND the version V
125 # is the first version of that article. In that case, V' does not exist.
126 if ( $this->mOldid
=== false ) {
127 $this->showFirstRevision();
128 $this->renderNewRevision(); // should we respect $diffOnly here or not?
129 wfProfileOut( $fname );
133 $wgOut->suppressQuickbar();
135 $oldTitle = $this->mOldPage
->getPrefixedText();
136 $newTitle = $this->mNewPage
->getPrefixedText();
137 if( $oldTitle == $newTitle ) {
138 $wgOut->setPageTitle( $newTitle );
140 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
142 $wgOut->setSubtitle( wfMsg( 'difference' ) );
143 $wgOut->setRobotpolicy( 'noindex,nofollow' );
145 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
146 $wgOut->loginToUse();
148 wfProfileOut( $fname );
152 $sk = $wgUser->getSkin();
154 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
155 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
160 // Prepare a change patrol link, if applicable
161 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
162 // If we've been given an explicit change identifier, use it; saves time
163 if( $this->mRcidMarkPatrolled
) {
164 $rcid = $this->mRcidMarkPatrolled
;
166 // Look for an unpatrolled change corresponding to this diff
167 $change = RecentChange
::newFromConds(
169 // Add redundant timestamp condition so we can use the
171 'rc_timestamp' => $this->mNewRev
->getTimestamp(),
172 'rc_this_oldid' => $this->mNewid
,
173 'rc_last_oldid' => $this->mOldid
,
178 if( $change instanceof RecentChange
) {
179 $rcid = $change->mAttribs
['rc_id'];
187 $patrol = ' [' . $sk->makeKnownLinkObj(
189 wfMsgHtml( 'markaspatrolleddiff' ),
190 "action=markpatrolled&rcid={$rcid}"
199 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
200 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
201 if ( $this->mNewRev
->isCurrent() ) {
202 $nextlink = ' ';
204 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
205 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
211 if ($this->mOldRev
->mMinorEdit
== 1) {
212 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
213 wfMsg( 'minoreditletter') ) . ' ';
216 if ($this->mNewRev
->mMinorEdit
== 1) {
217 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
218 wfMsg( 'minoreditletter') ) . ' ';
221 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $this->mOldtitle
. '</strong></div>' .
222 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
) . "</div>" .
223 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly ) . "</div>" .
224 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
225 $newHeader = '<div id="mw-diff-ntitle1"><strong>' .$this->mNewtitle
. '</strong></div>' .
226 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
) . " $rollback</div>" .
227 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly ) . "</div>" .
228 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
230 $this->showDiff( $oldHeader, $newHeader );
233 $this->renderNewRevision();
235 wfProfileOut( $fname );
239 * Show the new revision of the page.
241 function renderNewRevision() {
243 $fname = 'DifferenceEngine::renderNewRevision';
244 wfProfileIn( $fname );
246 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
247 #add deleted rev tag if needed
248 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
249 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
252 if( !$this->mNewRev
->isCurrent() ) {
253 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
256 $this->loadNewText();
257 if( is_object( $this->mNewRev
) ) {
258 $wgOut->setRevisionId( $this->mNewRev
->getId() );
261 $wgOut->addWikiTextTidy( $this->mNewtext
);
263 if( !$this->mNewRev
->isCurrent() ) {
264 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
267 wfProfileOut( $fname );
271 * Show the first revision of an article. Uses normal diff headers in
272 * contrast to normal "old revision" display style.
274 function showFirstRevision() {
275 global $wgOut, $wgUser;
277 $fname = 'DifferenceEngine::showFirstRevision';
278 wfProfileIn( $fname );
280 # Get article text from the DB
282 if ( ! $this->loadNewText() ) {
283 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
285 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
286 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
287 $wgOut->addWikitext( $mtext );
288 wfProfileOut( $fname );
291 if ( $this->mNewRev
->isCurrent() ) {
292 $wgOut->setArticleFlag( true );
295 # Check if user is allowed to look at this page. If not, bail out.
297 if ( !( $this->mTitle
->userCanRead() ) ) {
298 $wgOut->loginToUse();
300 wfProfileOut( $fname );
304 # Prepare the header box
306 $sk = $wgUser->getSkin();
308 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
309 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
310 $sk->revUserTools( $this->mNewRev
) . "<br />" .
311 $sk->revComment( $this->mNewRev
) . "<br />" .
312 $nextlink . "</div>\n";
314 $wgOut->addHTML( $header );
316 $wgOut->setSubtitle( wfMsg( 'difference' ) );
317 $wgOut->setRobotpolicy( 'noindex,nofollow' );
319 wfProfileOut( $fname );
323 * Get the diff text, send it to $wgOut
324 * Returns false if the diff could not be generated, otherwise returns true
326 function showDiff( $otitle, $ntitle ) {
327 global $wgOut, $wgRequest;
328 $diff = $this->getDiff( $otitle, $ntitle, $wgRequest->getVal( 'action' ) == 'purge' );
329 if ( $diff === false ) {
330 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
333 $this->showDiffStyle();
334 $wgOut->addHTML( $diff );
340 * Add style sheets and supporting JS for diff display.
342 function showDiffStyle() {
343 global $wgStylePath, $wgStyleVersion, $wgOut;
344 $wgOut->addStyle( 'common/diff.css' );
346 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
347 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
351 * Get complete diff table, including header
353 * @param Title $otitle Old title
354 * @param Title $ntitle New title
355 * @param bool $skipCache Skip the diff cache for this request?
358 function getDiff( $otitle, $ntitle, $skipCache = false ) {
359 $body = $this->getDiffBody( $skipCache );
360 if ( $body === false ) {
363 $multi = $this->getMultiNotice();
364 return $this->addHeader( $body, $otitle, $ntitle, $multi );
369 * Get the diff table body, without header
371 * @param bool $skipCache Skip cache for this request?
374 function getDiffBody( $skipCache = false ) {
376 $fname = 'DifferenceEngine::getDiffBody';
377 wfProfileIn( $fname );
381 if ( $this->mOldid
&& $this->mNewid
&& !$skipCache ) {
383 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
384 $difftext = $wgMemc->get( $key );
386 wfIncrStats( 'diff_cache_hit' );
387 $difftext = $this->localiseLineNumbers( $difftext );
388 $difftext .= "\n<!-- diff cache key $key -->\n";
389 wfProfileOut( $fname );
394 #loadtext is permission safe, this just clears out the diff
395 if ( !$this->loadText() ) {
396 wfProfileOut( $fname );
398 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
400 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
404 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
406 // Save to cache for 7 days
407 if ( $key !== false && $difftext !== false ) {
408 wfIncrStats( 'diff_cache_miss' );
409 $wgMemc->set( $key, $difftext, 7*86400 );
411 wfIncrStats( 'diff_uncacheable' );
413 // Replace line numbers with the text in the user's language
414 if ( $difftext !== false ) {
415 $difftext = $this->localiseLineNumbers( $difftext );
417 wfProfileOut( $fname );
422 * Generate a diff, no caching
423 * $otext and $ntext must be already segmented
425 function generateDiffBody( $otext, $ntext ) {
426 global $wgExternalDiffEngine, $wgContLang;
427 $fname = 'DifferenceEngine::generateDiffBody';
429 $otext = str_replace( "\r\n", "\n", $otext );
430 $ntext = str_replace( "\r\n", "\n", $ntext );
432 if ( $wgExternalDiffEngine == 'wikidiff' ) {
433 # For historical reasons, external diff engine expects
434 # input text to be HTML-escaped already
435 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
436 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
437 if( !function_exists( 'wikidiff_do_diff' ) ) {
438 dl('php_wikidiff.so');
440 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
443 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
444 # Better external diff engine, the 2 may some day be dropped
445 # This one does the escaping and segmenting itself
446 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
447 wfProfileIn( "$fname-dl" );
448 @dl
('php_wikidiff2.so');
449 wfProfileOut( "$fname-dl" );
451 if ( function_exists( 'wikidiff2_do_diff' ) ) {
452 wfProfileIn( 'wikidiff2_do_diff' );
453 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
454 wfProfileOut( 'wikidiff2_do_diff' );
458 if ( $wgExternalDiffEngine !== false ) {
460 global $wgTmpDirectory;
461 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
462 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
464 $tempFile1 = fopen( $tempName1, "w" );
466 wfProfileOut( $fname );
469 $tempFile2 = fopen( $tempName2, "w" );
471 wfProfileOut( $fname );
474 fwrite( $tempFile1, $otext );
475 fwrite( $tempFile2, $ntext );
476 fclose( $tempFile1 );
477 fclose( $tempFile2 );
478 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
479 wfProfileIn( "$fname-shellexec" );
480 $difftext = wfShellExec( $cmd );
481 wfProfileOut( "$fname-shellexec" );
482 unlink( $tempName1 );
483 unlink( $tempName2 );
488 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
489 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
490 $diffs = new Diff( $ota, $nta );
491 $formatter = new TableDiffFormatter();
492 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
497 * Replace line numbers with the text in the user's language
499 function localiseLineNumbers( $text ) {
500 return preg_replace_callback( '/<!--LINE (\d+)-->/',
501 array( &$this, 'localiseLineNumbersCb' ), $text );
504 function localiseLineNumbersCb( $matches ) {
506 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
511 * If there are revisions between the ones being compared, return a note saying so.
513 function getMultiNotice() {
514 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
517 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
518 // Comparing two different pages? Count would be meaningless.
522 $oldid = $this->mOldRev
->getId();
523 $newid = $this->mNewRev
->getId();
524 if ( $oldid > $newid ) {
525 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
528 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
532 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
537 * Add the header to a diff body
539 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
542 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
543 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
545 if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
546 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
550 <col class='diff-marker' />
551 <col class='diff-content' />
552 <col class='diff-marker' />
553 <col class='diff-content' />
555 <td colspan='2' class='diff-otitle'>{$otitle}</td>
556 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
561 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
563 return $header . $diff . "</table>";
567 * Use specified text instead of loading from the database
569 function setText( $oldText, $newText ) {
570 $this->mOldtext
= $oldText;
571 $this->mNewtext
= $newText;
572 $this->mTextLoaded
= 2;
576 * Load revision metadata for the specified articles. If newid is 0, then compare
577 * the old article in oldid to the current article; if oldid is 0, then
578 * compare the current article to the immediately previous one (ignoring the
581 * If oldid is false, leave the corresponding revision object set
582 * to false. This is impossible via ordinary user input, and is provided for
585 function loadRevisionData() {
587 if ( $this->mRevisionsLoaded
) {
590 // Whether it succeeds or fails, we don't want to try again
591 $this->mRevisionsLoaded
= true;
594 // Load the new revision object
595 $this->mNewRev
= $this->mNewid
596 ? Revision
::newFromId( $this->mNewid
)
597 : Revision
::newFromTitle( $this->mTitle
);
598 if( !$this->mNewRev
instanceof Revision
)
601 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
602 $this->mNewid
= $this->mNewRev
->getId();
604 // Set assorted variables
605 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
606 $this->mNewPage
= $this->mNewRev
->getTitle();
607 if( $this->mNewRev
->isCurrent() ) {
608 $newLink = $this->mNewPage
->escapeLocalUrl();
609 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
610 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
612 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
613 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
616 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
617 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
618 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
620 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
621 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
624 // Load the old revision object
625 $this->mOldRev
= false;
626 if( $this->mOldid
) {
627 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
628 } elseif ( $this->mOldid
=== 0 ) {
629 $rev = $this->mNewRev
->getPrevious();
631 $this->mOldid
= $rev->getId();
632 $this->mOldRev
= $rev;
634 // No previous revision; mark to show as first-version only.
635 $this->mOldid
= false;
636 $this->mOldRev
= false;
638 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
640 if( is_null( $this->mOldRev
) ) {
644 if ( $this->mOldRev
) {
645 $this->mOldPage
= $this->mOldRev
->getTitle();
647 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
648 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
649 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
650 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
651 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
653 // Add an "undo" link
654 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
655 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
662 * Load the text of the revisions, as well as revision data.
664 function loadText() {
665 if ( $this->mTextLoaded
== 2 ) {
668 // Whether it succeeds or fails, we don't want to try again
669 $this->mTextLoaded
= 2;
672 if ( !$this->loadRevisionData() ) {
675 if ( $this->mOldRev
) {
676 // FIXME: permission tests
677 $this->mOldtext
= $this->mOldRev
->revText();
678 if ( $this->mOldtext
=== false ) {
682 if ( $this->mNewRev
) {
683 $this->mNewtext
= $this->mNewRev
->revText();
684 if ( $this->mNewtext
=== false ) {
692 * Load the text of the new revision, not the old one
694 function loadNewText() {
695 if ( $this->mTextLoaded
>= 1 ) {
698 $this->mTextLoaded
= 1;
700 if ( !$this->loadRevisionData() ) {
703 $this->mNewtext
= $this->mNewRev
->getText();
710 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
712 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
713 // You may copy this code freely under the conditions of the GPL.
716 define('USE_ASSERTS', function_exists('assert'));
721 * @addtogroup DifferenceEngine
729 trigger_error('pure virtual', E_USER_ERROR
);
733 return $this->orig ?
sizeof($this->orig
) : 0;
736 function nclosing() {
737 return $this->closing ?
sizeof($this->closing
) : 0;
744 * @addtogroup DifferenceEngine
746 class _DiffOp_Copy
extends _DiffOp
{
749 function _DiffOp_Copy ($orig, $closing = false) {
750 if (!is_array($closing))
753 $this->closing
= $closing;
757 return new _DiffOp_Copy($this->closing
, $this->orig
);
764 * @addtogroup DifferenceEngine
766 class _DiffOp_Delete
extends _DiffOp
{
767 var $type = 'delete';
769 function _DiffOp_Delete ($lines) {
770 $this->orig
= $lines;
771 $this->closing
= false;
775 return new _DiffOp_Add($this->orig
);
782 * @addtogroup DifferenceEngine
784 class _DiffOp_Add
extends _DiffOp
{
787 function _DiffOp_Add ($lines) {
788 $this->closing
= $lines;
793 return new _DiffOp_Delete($this->closing
);
800 * @addtogroup DifferenceEngine
802 class _DiffOp_Change
extends _DiffOp
{
803 var $type = 'change';
805 function _DiffOp_Change ($orig, $closing) {
807 $this->closing
= $closing;
811 return new _DiffOp_Change($this->closing
, $this->orig
);
817 * Class used internally by Diff to actually compute the diffs.
819 * The algorithm used here is mostly lifted from the perl module
820 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
821 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
823 * More ideas are taken from:
824 * http://www.ics.uci.edu/~eppstein/161/960229.html
826 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
827 * diffutils-2.7, which can be found at:
828 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
830 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
833 * Line length limits for robustness added by Tim Starling, 2005-08-31
835 * @author Geoffrey T. Dairiki, Tim Starling
837 * @addtogroup DifferenceEngine
841 const MAX_XREF_LENGTH
= 10000;
843 function diff ($from_lines, $to_lines) {
844 $fname = '_DiffEngine::diff';
845 wfProfileIn( $fname );
847 $n_from = sizeof($from_lines);
848 $n_to = sizeof($to_lines);
850 $this->xchanged
= $this->ychanged
= array();
851 $this->xv
= $this->yv
= array();
852 $this->xind
= $this->yind
= array();
854 unset($this->in_seq
);
857 // Skip leading common lines.
858 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
859 if ($from_lines[$skip] !== $to_lines[$skip])
861 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
863 // Skip trailing common lines.
864 $xi = $n_from; $yi = $n_to;
865 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
866 if ($from_lines[$xi] !== $to_lines[$yi])
868 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
871 // Ignore lines which do not exist in both files.
872 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
873 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
876 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
877 $line = $to_lines[$yi];
878 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
880 $yhash[$this->_line_hash($line)] = 1;
884 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
885 $line = $from_lines[$xi];
886 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
893 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
895 // Merge edits when possible
896 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
897 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
899 // Compute the edit operations.
902 while ($xi < $n_from ||
$yi < $n_to) {
903 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
904 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
906 // Skip matching "snake".
908 while ( $xi < $n_from && $yi < $n_to
909 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
910 $copy[] = $from_lines[$xi++
];
914 $edits[] = new _DiffOp_Copy($copy);
916 // Find deletes & adds.
918 while ($xi < $n_from && $this->xchanged
[$xi])
919 $delete[] = $from_lines[$xi++
];
922 while ($yi < $n_to && $this->ychanged
[$yi])
923 $add[] = $to_lines[$yi++
];
926 $edits[] = new _DiffOp_Change($delete, $add);
928 $edits[] = new _DiffOp_Delete($delete);
930 $edits[] = new _DiffOp_Add($add);
932 wfProfileOut( $fname );
937 * Returns the whole line if it's small enough, or the MD5 hash otherwise
939 function _line_hash( $line ) {
940 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
948 /* Divide the Largest Common Subsequence (LCS) of the sequences
949 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
952 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
953 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
954 * sub sequences. The first sub-sequence is contained in [X0, X1),
955 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
956 * that (X0, Y0) == (XOFF, YOFF) and
957 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
959 * This function assumes that the first lines of the specified portions
960 * of the two files do not match, and likewise that the last lines do not
961 * match. The caller must trim matching lines from the beginning and end
962 * of the portions it is going to specify.
964 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
965 $fname = '_DiffEngine::_diag';
966 wfProfileIn( $fname );
969 if ($xlim - $xoff > $ylim - $yoff) {
970 // Things seems faster (I'm not sure I understand why)
971 // when the shortest sequence in X.
973 list ($xoff, $xlim, $yoff, $ylim)
974 = array( $yoff, $ylim, $xoff, $xlim);
978 for ($i = $ylim - 1; $i >= $yoff; $i--)
979 $ymatches[$this->xv
[$i]][] = $i;
981 for ($i = $ylim - 1; $i >= $yoff; $i--)
982 $ymatches[$this->yv
[$i]][] = $i;
985 $this->seq
[0]= $yoff - 1;
986 $this->in_seq
= array();
989 $numer = $xlim - $xoff +
$nchunks - 1;
991 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
992 wfProfileIn( "$fname-chunk" );
994 for ($i = 0; $i <= $this->lcs
; $i++
)
995 $ymids[$i][$chunk-1] = $this->seq
[$i];
997 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
998 for ( ; $x < $x1; $x++
) {
999 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1000 if (empty($ymatches[$line]))
1002 $matches = $ymatches[$line];
1004 while (list ($junk, $y) = each($matches))
1005 if (empty($this->in_seq
[$y])) {
1006 $k = $this->_lcs_pos($y);
1007 USE_ASSERTS
&& assert($k > 0);
1008 $ymids[$k] = $ymids[$k-1];
1011 while (list ( /* $junk */, $y) = each($matches)) {
1012 if ($y > $this->seq
[$k-1]) {
1013 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1014 // Optimization: this is a common case:
1015 // next match is just replacing previous match.
1016 $this->in_seq
[$this->seq
[$k]] = false;
1017 $this->seq
[$k] = $y;
1018 $this->in_seq
[$y] = 1;
1019 } else if (empty($this->in_seq
[$y])) {
1020 $k = $this->_lcs_pos($y);
1021 USE_ASSERTS
&& assert($k > 0);
1022 $ymids[$k] = $ymids[$k-1];
1026 wfProfileOut( "$fname-chunk" );
1029 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1030 $ymid = $ymids[$this->lcs
];
1031 for ($n = 0; $n < $nchunks - 1; $n++
) {
1032 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1033 $y1 = $ymid[$n] +
1;
1034 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1036 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1038 wfProfileOut( $fname );
1039 return array($this->lcs
, $seps);
1042 function _lcs_pos ($ypos) {
1043 $fname = '_DiffEngine::_lcs_pos';
1044 wfProfileIn( $fname );
1047 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1048 $this->seq
[++
$this->lcs
] = $ypos;
1049 $this->in_seq
[$ypos] = 1;
1050 wfProfileOut( $fname );
1055 while ($beg < $end) {
1056 $mid = (int)(($beg +
$end) / 2);
1057 if ( $ypos > $this->seq
[$mid] )
1063 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1065 $this->in_seq
[$this->seq
[$end]] = false;
1066 $this->seq
[$end] = $ypos;
1067 $this->in_seq
[$ypos] = 1;
1068 wfProfileOut( $fname );
1072 /* Find LCS of two sequences.
1074 * The results are recorded in the vectors $this->{x,y}changed[], by
1075 * storing a 1 in the element for each line that is an insertion
1076 * or deletion (ie. is not in the LCS).
1078 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1080 * Note that XLIM, YLIM are exclusive bounds.
1081 * All line numbers are origin-0 and discarded lines are not counted.
1083 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1084 $fname = '_DiffEngine::_compareseq';
1085 wfProfileIn( $fname );
1087 // Slide down the bottom initial diagonal.
1088 while ($xoff < $xlim && $yoff < $ylim
1089 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1094 // Slide up the top initial diagonal.
1095 while ($xlim > $xoff && $ylim > $yoff
1096 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1101 if ($xoff == $xlim ||
$yoff == $ylim)
1104 // This is ad hoc but seems to work well.
1105 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1106 //$nchunks = max(2,min(8,(int)$nchunks));
1107 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1109 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1113 // X and Y sequences have no common subsequence:
1114 // mark all changed.
1115 while ($yoff < $ylim)
1116 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1117 while ($xoff < $xlim)
1118 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1120 // Use the partitions to split this problem into subproblems.
1123 while ($pt2 = next($seps)) {
1124 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1128 wfProfileOut( $fname );
1131 /* Adjust inserts/deletes of identical lines to join changes
1132 * as much as possible.
1134 * We do something when a run of changed lines include a
1135 * line at one end and has an excluded, identical line at the other.
1136 * We are free to choose which identical line is included.
1137 * `compareseq' usually chooses the one at the beginning,
1138 * but usually it is cleaner to consider the following identical line
1139 * to be the "change".
1141 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1143 function _shift_boundaries ($lines, &$changed, $other_changed) {
1144 $fname = '_DiffEngine::_shift_boundaries';
1145 wfProfileIn( $fname );
1149 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1150 $len = sizeof($lines);
1151 $other_len = sizeof($other_changed);
1155 * Scan forwards to find beginning of another run of changes.
1156 * Also keep track of the corresponding point in the other file.
1158 * Throughout this code, $i and $j are adjusted together so that
1159 * the first $i elements of $changed and the first $j elements
1160 * of $other_changed both contain the same number of zeros
1161 * (unchanged lines).
1162 * Furthermore, $j is always kept so that $j == $other_len or
1163 * $other_changed[$j] == false.
1165 while ($j < $other_len && $other_changed[$j])
1168 while ($i < $len && ! $changed[$i]) {
1169 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1171 while ($j < $other_len && $other_changed[$j])
1180 // Find the end of this run of changes.
1181 while (++
$i < $len && $changed[$i])
1186 * Record the length of this run of changes, so that
1187 * we can later determine whether the run has grown.
1189 $runlength = $i - $start;
1192 * Move the changed region back, so long as the
1193 * previous unchanged line matches the last changed one.
1194 * This merges with previous changed regions.
1196 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1197 $changed[--$start] = 1;
1198 $changed[--$i] = false;
1199 while ($start > 0 && $changed[$start - 1])
1201 USE_ASSERTS
&& assert('$j > 0');
1202 while ($other_changed[--$j])
1204 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1208 * Set CORRESPONDING to the end of the changed run, at the last
1209 * point where it corresponds to a changed run in the other file.
1210 * CORRESPONDING == LEN means no such point has been found.
1212 $corresponding = $j < $other_len ?
$i : $len;
1215 * Move the changed region forward, so long as the
1216 * first changed line matches the following unchanged one.
1217 * This merges with following changed regions.
1218 * Do this second, so that if there are no merges,
1219 * the changed region is moved forward as far as possible.
1221 while ($i < $len && $lines[$start] == $lines[$i]) {
1222 $changed[$start++
] = false;
1224 while ($i < $len && $changed[$i])
1227 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1229 if ($j < $other_len && $other_changed[$j]) {
1230 $corresponding = $i;
1231 while ($j < $other_len && $other_changed[$j])
1235 } while ($runlength != $i - $start);
1238 * If possible, move the fully-merged run of changes
1239 * back to a corresponding run in the other file.
1241 while ($corresponding < $i) {
1242 $changed[--$start] = 1;
1244 USE_ASSERTS
&& assert('$j > 0');
1245 while ($other_changed[--$j])
1247 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1250 wfProfileOut( $fname );
1255 * Class representing a 'diff' between two sequences of strings.
1258 * @addtogroup DifferenceEngine
1266 * Computes diff between sequences of strings.
1268 * @param $from_lines array An array of strings.
1269 * (Typically these are lines from a file.)
1270 * @param $to_lines array An array of strings.
1272 function Diff($from_lines, $to_lines) {
1273 $eng = new _DiffEngine
;
1274 $this->edits
= $eng->diff($from_lines, $to_lines);
1275 //$this->_check($from_lines, $to_lines);
1279 * Compute reversed Diff.
1283 * $diff = new Diff($lines1, $lines2);
1284 * $rev = $diff->reverse();
1285 * @return object A Diff object representing the inverse of the
1288 function reverse () {
1290 $rev->edits
= array();
1291 foreach ($this->edits
as $edit) {
1292 $rev->edits
[] = $edit->reverse();
1298 * Check for empty diff.
1300 * @return bool True iff two sequences were identical.
1302 function isEmpty () {
1303 foreach ($this->edits
as $edit) {
1304 if ($edit->type
!= 'copy')
1311 * Compute the length of the Longest Common Subsequence (LCS).
1313 * This is mostly for diagnostic purposed.
1315 * @return int The length of the LCS.
1319 foreach ($this->edits
as $edit) {
1320 if ($edit->type
== 'copy')
1321 $lcs +
= sizeof($edit->orig
);
1327 * Get the original set of lines.
1329 * This reconstructs the $from_lines parameter passed to the
1332 * @return array The original sequence of strings.
1337 foreach ($this->edits
as $edit) {
1339 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1345 * Get the closing set of lines.
1347 * This reconstructs the $to_lines parameter passed to the
1350 * @return array The sequence of strings.
1352 function closing() {
1355 foreach ($this->edits
as $edit) {
1357 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1363 * Check a Diff for validity.
1365 * This is here only for debugging purposes.
1367 function _check ($from_lines, $to_lines) {
1368 $fname = 'Diff::_check';
1369 wfProfileIn( $fname );
1370 if (serialize($from_lines) != serialize($this->orig()))
1371 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1372 if (serialize($to_lines) != serialize($this->closing()))
1373 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1375 $rev = $this->reverse();
1376 if (serialize($to_lines) != serialize($rev->orig()))
1377 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1378 if (serialize($from_lines) != serialize($rev->closing()))
1379 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1383 foreach ($this->edits
as $edit) {
1384 if ( $prevtype == $edit->type
)
1385 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1386 $prevtype = $edit->type
;
1389 $lcs = $this->lcs();
1390 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1391 wfProfileOut( $fname );
1396 * @todo document, bad name.
1398 * @addtogroup DifferenceEngine
1400 class MappedDiff
extends Diff
1405 * Computes diff between sequences of strings.
1407 * This can be used to compute things like
1408 * case-insensitve diffs, or diffs which ignore
1409 * changes in white-space.
1411 * @param $from_lines array An array of strings.
1412 * (Typically these are lines from a file.)
1414 * @param $to_lines array An array of strings.
1416 * @param $mapped_from_lines array This array should
1417 * have the same size number of elements as $from_lines.
1418 * The elements in $mapped_from_lines and
1419 * $mapped_to_lines are what is actually compared
1420 * when computing the diff.
1422 * @param $mapped_to_lines array This array should
1423 * have the same number of elements as $to_lines.
1425 function MappedDiff($from_lines, $to_lines,
1426 $mapped_from_lines, $mapped_to_lines) {
1427 $fname = 'MappedDiff::MappedDiff';
1428 wfProfileIn( $fname );
1430 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1431 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1433 $this->Diff($mapped_from_lines, $mapped_to_lines);
1436 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1437 $orig = &$this->edits
[$i]->orig
;
1438 if (is_array($orig)) {
1439 $orig = array_slice($from_lines, $xi, sizeof($orig));
1440 $xi +
= sizeof($orig);
1443 $closing = &$this->edits
[$i]->closing
;
1444 if (is_array($closing)) {
1445 $closing = array_slice($to_lines, $yi, sizeof($closing));
1446 $yi +
= sizeof($closing);
1449 wfProfileOut( $fname );
1454 * A class to format Diffs
1456 * This class formats the diff in classic diff format.
1457 * It is intended that this class be customized via inheritance,
1458 * to obtain fancier outputs.
1461 * @addtogroup DifferenceEngine
1466 * Number of leading context "lines" to preserve.
1468 * This should be left at zero for this class, but subclasses
1469 * may want to set this to other values.
1471 var $leading_context_lines = 0;
1474 * Number of trailing context "lines" to preserve.
1476 * This should be left at zero for this class, but subclasses
1477 * may want to set this to other values.
1479 var $trailing_context_lines = 0;
1484 * @param $diff object A Diff object.
1485 * @return string The formatted output.
1487 function format($diff) {
1488 $fname = 'DiffFormatter::format';
1489 wfProfileIn( $fname );
1495 $nlead = $this->leading_context_lines
;
1496 $ntrail = $this->trailing_context_lines
;
1498 $this->_start_diff();
1500 foreach ($diff->edits
as $edit) {
1501 if ($edit->type
== 'copy') {
1502 if (is_array($block)) {
1503 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1508 $context = array_slice($edit->orig
, 0, $ntrail);
1509 $block[] = new _DiffOp_Copy($context);
1511 $this->_block($x0, $ntrail +
$xi - $x0,
1512 $y0, $ntrail +
$yi - $y0,
1517 $context = $edit->orig
;
1520 if (! is_array($block)) {
1521 $context = array_slice($context, sizeof($context) - $nlead);
1522 $x0 = $xi - sizeof($context);
1523 $y0 = $yi - sizeof($context);
1526 $block[] = new _DiffOp_Copy($context);
1532 $xi +
= sizeof($edit->orig
);
1534 $yi +
= sizeof($edit->closing
);
1537 if (is_array($block))
1538 $this->_block($x0, $xi - $x0,
1542 $end = $this->_end_diff();
1543 wfProfileOut( $fname );
1547 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1548 $fname = 'DiffFormatter::_block';
1549 wfProfileIn( $fname );
1550 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1551 foreach ($edits as $edit) {
1552 if ($edit->type
== 'copy')
1553 $this->_context($edit->orig
);
1554 elseif ($edit->type
== 'add')
1555 $this->_added($edit->closing
);
1556 elseif ($edit->type
== 'delete')
1557 $this->_deleted($edit->orig
);
1558 elseif ($edit->type
== 'change')
1559 $this->_changed($edit->orig
, $edit->closing
);
1561 trigger_error('Unknown edit type', E_USER_ERROR
);
1563 $this->_end_block();
1564 wfProfileOut( $fname );
1567 function _start_diff() {
1571 function _end_diff() {
1572 $val = ob_get_contents();
1577 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1579 $xbeg .= "," . ($xbeg +
$xlen - 1);
1581 $ybeg .= "," . ($ybeg +
$ylen - 1);
1583 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1586 function _start_block($header) {
1590 function _end_block() {
1593 function _lines($lines, $prefix = ' ') {
1594 foreach ($lines as $line)
1595 echo "$prefix $line\n";
1598 function _context($lines) {
1599 $this->_lines($lines);
1602 function _added($lines) {
1603 $this->_lines($lines, '>');
1605 function _deleted($lines) {
1606 $this->_lines($lines, '<');
1609 function _changed($orig, $closing) {
1610 $this->_deleted($orig);
1612 $this->_added($closing);
1618 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1622 define('NBSP', ' '); // iso-8859-x non-breaking space.
1627 * @addtogroup DifferenceEngine
1629 class _HWLDF_WordAccumulator
{
1630 function _HWLDF_WordAccumulator () {
1631 $this->_lines
= array();
1637 function _flushGroup ($new_tag) {
1638 if ($this->_group
!== '') {
1639 if ($this->_tag
== 'ins')
1640 $this->_line
.= '<ins class="diffchange">' .
1641 htmlspecialchars ( $this->_group
) . '</ins>';
1642 elseif ($this->_tag
== 'del')
1643 $this->_line
.= '<del class="diffchange">' .
1644 htmlspecialchars ( $this->_group
) . '</del>';
1646 $this->_line
.= htmlspecialchars ( $this->_group
);
1649 $this->_tag
= $new_tag;
1652 function _flushLine ($new_tag) {
1653 $this->_flushGroup($new_tag);
1654 if ($this->_line
!= '')
1655 array_push ( $this->_lines
, $this->_line
);
1657 # make empty lines visible by inserting an NBSP
1658 array_push ( $this->_lines
, NBSP
);
1662 function addWords ($words, $tag = '') {
1663 if ($tag != $this->_tag
)
1664 $this->_flushGroup($tag);
1666 foreach ($words as $word) {
1667 // new-line should only come as first char of word.
1670 if ($word[0] == "\n") {
1671 $this->_flushLine($tag);
1672 $word = substr($word, 1);
1674 assert(!strstr($word, "\n"));
1675 $this->_group
.= $word;
1679 function getLines() {
1680 $this->_flushLine('~done');
1681 return $this->_lines
;
1688 * @addtogroup DifferenceEngine
1690 class WordLevelDiff
extends MappedDiff
1692 const MAX_LINE_LENGTH
= 10000;
1694 function WordLevelDiff ($orig_lines, $closing_lines) {
1695 $fname = 'WordLevelDiff::WordLevelDiff';
1696 wfProfileIn( $fname );
1698 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1699 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1701 $this->MappedDiff($orig_words, $closing_words,
1702 $orig_stripped, $closing_stripped);
1703 wfProfileOut( $fname );
1706 function _split($lines) {
1707 $fname = 'WordLevelDiff::_split';
1708 wfProfileIn( $fname );
1711 $stripped = array();
1713 foreach ( $lines as $line ) {
1714 # If the line is too long, just pretend the entire line is one big word
1715 # This prevents resource exhaustion problems
1722 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1724 $stripped[] = $line;
1727 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1730 $words = array_merge( $words, $m[0] );
1731 $stripped = array_merge( $stripped, $m[1] );
1735 wfProfileOut( $fname );
1736 return array($words, $stripped);
1740 $fname = 'WordLevelDiff::orig';
1741 wfProfileIn( $fname );
1742 $orig = new _HWLDF_WordAccumulator
;
1744 foreach ($this->edits
as $edit) {
1745 if ($edit->type
== 'copy')
1746 $orig->addWords($edit->orig
);
1747 elseif ($edit->orig
)
1748 $orig->addWords($edit->orig
, 'del');
1750 $lines = $orig->getLines();
1751 wfProfileOut( $fname );
1755 function closing () {
1756 $fname = 'WordLevelDiff::closing';
1757 wfProfileIn( $fname );
1758 $closing = new _HWLDF_WordAccumulator
;
1760 foreach ($this->edits
as $edit) {
1761 if ($edit->type
== 'copy')
1762 $closing->addWords($edit->closing
);
1763 elseif ($edit->closing
)
1764 $closing->addWords($edit->closing
, 'ins');
1766 $lines = $closing->getLines();
1767 wfProfileOut( $fname );
1773 * Wikipedia Table style diff formatter.
1776 * @addtogroup DifferenceEngine
1778 class TableDiffFormatter
extends DiffFormatter
1780 function TableDiffFormatter() {
1781 $this->leading_context_lines
= 2;
1782 $this->trailing_context_lines
= 2;
1785 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1786 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1787 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1791 function _start_block( $header ) {
1795 function _end_block() {
1798 function _lines( $lines, $prefix=' ', $color='white' ) {
1801 # HTML-escape parameter before calling this
1802 function addedLine( $line ) {
1803 return $this->wrapLine( '+', 'diff-addedline', $line );
1806 # HTML-escape parameter before calling this
1807 function deletedLine( $line ) {
1808 return $this->wrapLine( '-', 'diff-deletedline', $line );
1811 # HTML-escape parameter before calling this
1812 function contextLine( $line ) {
1813 return $this->wrapLine( ' ', 'diff-context', $line );
1816 private function wrapLine( $marker, $class, $line ) {
1817 if( $line !== '' ) {
1818 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1819 $line = "<div>$line</div>";
1821 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1824 function emptyLine() {
1825 return '<td colspan="2"> </td>';
1828 function _added( $lines ) {
1829 foreach ($lines as $line) {
1830 echo '<tr>' . $this->emptyLine() .
1831 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1835 function _deleted($lines) {
1836 foreach ($lines as $line) {
1837 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1838 $this->emptyLine() . "</tr>\n";
1842 function _context( $lines ) {
1843 foreach ($lines as $line) {
1845 $this->contextLine( htmlspecialchars ( $line ) ) .
1846 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1850 function _changed( $orig, $closing ) {
1851 $fname = 'TableDiffFormatter::_changed';
1852 wfProfileIn( $fname );
1854 $diff = new WordLevelDiff( $orig, $closing );
1855 $del = $diff->orig();
1856 $add = $diff->closing();
1858 # Notice that WordLevelDiff returns HTML-escaped output.
1859 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1861 while ( $line = array_shift( $del ) ) {
1862 $aline = array_shift( $add );
1863 echo '<tr>' . $this->deletedLine( $line ) .
1864 $this->addedLine( $aline ) . "</tr>\n";
1866 foreach ($add as $line) { # If any leftovers
1867 echo '<tr>' . $this->emptyLine() .
1868 $this->addedLine( $line ) . "</tr>\n";
1870 wfProfileOut( $fname );