e0647ee1364a3871de1d6a2f274b83280085a625
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)
41 * @param $refreshCache boolean If set, refreshes the diff cache
43 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false ) {
44 $this->mTitle
= $titleObj;
45 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
47 if ( 'prev' === $new ) {
48 # Show diff between revision $old and the previous one.
49 # Get previous one from DB.
51 $this->mNewid
= intval($old);
53 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
55 } elseif ( 'next' === $new ) {
56 # Show diff between revision $old and the previous one.
57 # Get previous one from DB.
59 $this->mOldid
= intval($old);
60 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
61 if ( false === $this->mNewid
) {
62 # if no result, NewId points to the newest old revision. The only newer
63 # revision is cur, which is "0".
68 $this->mOldid
= intval($old);
69 $this->mNewid
= intval($new);
71 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
72 $this->mRefreshCache
= $refreshCache;
75 function showDiffPage( $diffOnly = false ) {
76 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
77 $fname = 'DifferenceEngine::showDiffPage';
78 wfProfileIn( $fname );
80 # If external diffs are enabled both globally and for the user,
81 # we'll use the application/x-external-editor interface to call
82 # an external diff tool like kompare, kdiff3, etc.
83 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
84 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
86 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
87 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
88 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
89 $special=$wgLang->getNsText(NS_SPECIAL
);
94 Script={$wgServer}{$wgScript}
95 Special namespace={$special}
109 $wgOut->setArticleFlag( false );
110 if ( ! $this->loadRevisionData() ) {
111 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
112 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
113 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
114 $wgOut->addWikitext( $mtext );
115 wfProfileOut( $fname );
119 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
121 if ( $this->mNewRev
->isCurrent() ) {
122 $wgOut->setArticleFlag( true );
125 # mOldid is false if the difference engine is called with a "vague" query for
126 # a diff between a version V and its previous version V' AND the version V
127 # is the first version of that article. In that case, V' does not exist.
128 if ( $this->mOldid
=== false ) {
129 $this->showFirstRevision();
130 $this->renderNewRevision(); // should we respect $diffOnly here or not?
131 wfProfileOut( $fname );
135 $wgOut->suppressQuickbar();
137 $oldTitle = $this->mOldPage
->getPrefixedText();
138 $newTitle = $this->mNewPage
->getPrefixedText();
139 if( $oldTitle == $newTitle ) {
140 $wgOut->setPageTitle( $newTitle );
142 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
144 $wgOut->setSubtitle( wfMsg( 'difference' ) );
145 $wgOut->setRobotpolicy( 'noindex,nofollow' );
147 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
148 $wgOut->loginToUse();
150 wfProfileOut( $fname );
154 $sk = $wgUser->getSkin();
156 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
157 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
162 // Prepare a change patrol link, if applicable
163 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
164 // If we've been given an explicit change identifier, use it; saves time
165 if( $this->mRcidMarkPatrolled
) {
166 $rcid = $this->mRcidMarkPatrolled
;
168 // Look for an unpatrolled change corresponding to this diff
169 $db = wfGetDB( DB_SLAVE
);
170 $change = RecentChange
::newFromConds(
172 // Add redundant timestamp condition so we can use the
174 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
175 'rc_this_oldid' => $this->mNewid
,
176 'rc_last_oldid' => $this->mOldid
,
181 if( $change instanceof RecentChange
) {
182 $rcid = $change->mAttribs
['rc_id'];
190 $patrol = ' [' . $sk->makeKnownLinkObj(
192 wfMsgHtml( 'markaspatrolleddiff' ),
193 "action=markpatrolled&rcid={$rcid}"
202 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
203 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
204 if ( $this->mNewRev
->isCurrent() ) {
205 $nextlink = ' ';
207 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
208 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
214 if ($this->mOldRev
->mMinorEdit
== 1) {
215 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
216 wfMsg( 'minoreditletter') ) . ' ';
219 if ($this->mNewRev
->mMinorEdit
== 1) {
220 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
221 wfMsg( 'minoreditletter') ) . ' ';
224 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $this->mOldtitle
. '</strong></div>' .
225 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
) . "</div>" .
226 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly ) . "</div>" .
227 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
228 $newHeader = '<div id="mw-diff-ntitle1"><strong>' .$this->mNewtitle
. '</strong></div>' .
229 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
) . " $rollback</div>" .
230 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly ) . "</div>" .
231 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
233 $this->showDiff( $oldHeader, $newHeader );
236 $this->renderNewRevision();
238 wfProfileOut( $fname );
242 * Show the new revision of the page.
244 function renderNewRevision() {
246 $fname = 'DifferenceEngine::renderNewRevision';
247 wfProfileIn( $fname );
249 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
250 #add deleted rev tag if needed
251 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
252 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
255 if( !$this->mNewRev
->isCurrent() ) {
256 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
259 $this->loadNewText();
260 if( is_object( $this->mNewRev
) ) {
261 $wgOut->setRevisionId( $this->mNewRev
->getId() );
264 $wgOut->addWikiTextTidy( $this->mNewtext
);
266 if( !$this->mNewRev
->isCurrent() ) {
267 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
270 wfProfileOut( $fname );
274 * Show the first revision of an article. Uses normal diff headers in
275 * contrast to normal "old revision" display style.
277 function showFirstRevision() {
278 global $wgOut, $wgUser;
280 $fname = 'DifferenceEngine::showFirstRevision';
281 wfProfileIn( $fname );
283 # Get article text from the DB
285 if ( ! $this->loadNewText() ) {
286 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
288 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
289 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
290 $wgOut->addWikitext( $mtext );
291 wfProfileOut( $fname );
294 if ( $this->mNewRev
->isCurrent() ) {
295 $wgOut->setArticleFlag( true );
298 # Check if user is allowed to look at this page. If not, bail out.
300 if ( !( $this->mTitle
->userCanRead() ) ) {
301 $wgOut->loginToUse();
303 wfProfileOut( $fname );
307 # Prepare the header box
309 $sk = $wgUser->getSkin();
311 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
312 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
313 $sk->revUserTools( $this->mNewRev
) . "<br />" .
314 $sk->revComment( $this->mNewRev
) . "<br />" .
315 $nextlink . "</div>\n";
317 $wgOut->addHTML( $header );
319 $wgOut->setSubtitle( wfMsg( 'difference' ) );
320 $wgOut->setRobotpolicy( 'noindex,nofollow' );
322 wfProfileOut( $fname );
326 * Get the diff text, send it to $wgOut
327 * Returns false if the diff could not be generated, otherwise returns true
329 function showDiff( $otitle, $ntitle ) {
331 $diff = $this->getDiff( $otitle, $ntitle );
332 if ( $diff === false ) {
333 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
336 $this->showDiffStyle();
337 $wgOut->addHTML( $diff );
343 * Add style sheets and supporting JS for diff display.
345 function showDiffStyle() {
346 global $wgStylePath, $wgStyleVersion, $wgOut;
347 $wgOut->addStyle( 'common/diff.css' );
349 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
350 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
354 * Get complete diff table, including header
356 * @param Title $otitle Old title
357 * @param Title $ntitle New title
360 function getDiff( $otitle, $ntitle ) {
361 $body = $this->getDiffBody();
362 if ( $body === false ) {
365 $multi = $this->getMultiNotice();
366 return $this->addHeader( $body, $otitle, $ntitle, $multi );
371 * Get the diff table body, without header
375 function getDiffBody() {
377 $fname = 'DifferenceEngine::getDiffBody';
378 wfProfileIn( $fname );
382 if ( $this->mOldid
&& $this->mNewid
) {
383 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
385 if ( !$this->mRefreshCache
) {
386 $difftext = $wgMemc->get( $key );
388 wfIncrStats( 'diff_cache_hit' );
389 $difftext = $this->localiseLineNumbers( $difftext );
390 $difftext .= "\n<!-- diff cache key $key -->\n";
391 wfProfileOut( $fname );
394 } // don't try to load but save the result
397 #loadtext is permission safe, this just clears out the diff
398 if ( !$this->loadText() ) {
399 wfProfileOut( $fname );
401 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
403 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
407 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
409 // Save to cache for 7 days
410 if ( $key !== false && $difftext !== false ) {
411 wfIncrStats( 'diff_cache_miss' );
412 $wgMemc->set( $key, $difftext, 7*86400 );
414 wfIncrStats( 'diff_uncacheable' );
416 // Replace line numbers with the text in the user's language
417 if ( $difftext !== false ) {
418 $difftext = $this->localiseLineNumbers( $difftext );
420 wfProfileOut( $fname );
425 * Generate a diff, no caching
426 * $otext and $ntext must be already segmented
428 function generateDiffBody( $otext, $ntext ) {
429 global $wgExternalDiffEngine, $wgContLang;
430 $fname = 'DifferenceEngine::generateDiffBody';
432 $otext = str_replace( "\r\n", "\n", $otext );
433 $ntext = str_replace( "\r\n", "\n", $ntext );
435 if ( $wgExternalDiffEngine == 'wikidiff' ) {
436 # For historical reasons, external diff engine expects
437 # input text to be HTML-escaped already
438 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
439 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
440 if( !function_exists( 'wikidiff_do_diff' ) ) {
441 dl('php_wikidiff.so');
443 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
446 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
447 # Better external diff engine, the 2 may some day be dropped
448 # This one does the escaping and segmenting itself
449 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
450 wfProfileIn( "$fname-dl" );
451 @dl
('php_wikidiff2.so');
452 wfProfileOut( "$fname-dl" );
454 if ( function_exists( 'wikidiff2_do_diff' ) ) {
455 wfProfileIn( 'wikidiff2_do_diff' );
456 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
457 wfProfileOut( 'wikidiff2_do_diff' );
461 if ( $wgExternalDiffEngine !== false ) {
463 global $wgTmpDirectory;
464 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
465 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
467 $tempFile1 = fopen( $tempName1, "w" );
469 wfProfileOut( $fname );
472 $tempFile2 = fopen( $tempName2, "w" );
474 wfProfileOut( $fname );
477 fwrite( $tempFile1, $otext );
478 fwrite( $tempFile2, $ntext );
479 fclose( $tempFile1 );
480 fclose( $tempFile2 );
481 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
482 wfProfileIn( "$fname-shellexec" );
483 $difftext = wfShellExec( $cmd );
484 wfProfileOut( "$fname-shellexec" );
485 unlink( $tempName1 );
486 unlink( $tempName2 );
491 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
492 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
493 $diffs = new Diff( $ota, $nta );
494 $formatter = new TableDiffFormatter();
495 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
500 * Replace line numbers with the text in the user's language
502 function localiseLineNumbers( $text ) {
503 return preg_replace_callback( '/<!--LINE (\d+)-->/',
504 array( &$this, 'localiseLineNumbersCb' ), $text );
507 function localiseLineNumbersCb( $matches ) {
509 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
514 * If there are revisions between the ones being compared, return a note saying so.
516 function getMultiNotice() {
517 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
520 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
521 // Comparing two different pages? Count would be meaningless.
525 $oldid = $this->mOldRev
->getId();
526 $newid = $this->mNewRev
->getId();
527 if ( $oldid > $newid ) {
528 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
531 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
535 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
540 * Add the header to a diff body
542 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
545 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
546 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
548 if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
549 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
553 <col class='diff-marker' />
554 <col class='diff-content' />
555 <col class='diff-marker' />
556 <col class='diff-content' />
558 <td colspan='2' class='diff-otitle'>{$otitle}</td>
559 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
564 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
566 return $header . $diff . "</table>";
570 * Use specified text instead of loading from the database
572 function setText( $oldText, $newText ) {
573 $this->mOldtext
= $oldText;
574 $this->mNewtext
= $newText;
575 $this->mTextLoaded
= 2;
579 * Load revision metadata for the specified articles. If newid is 0, then compare
580 * the old article in oldid to the current article; if oldid is 0, then
581 * compare the current article to the immediately previous one (ignoring the
584 * If oldid is false, leave the corresponding revision object set
585 * to false. This is impossible via ordinary user input, and is provided for
588 function loadRevisionData() {
590 if ( $this->mRevisionsLoaded
) {
593 // Whether it succeeds or fails, we don't want to try again
594 $this->mRevisionsLoaded
= true;
597 // Load the new revision object
598 $this->mNewRev
= $this->mNewid
599 ? Revision
::newFromId( $this->mNewid
)
600 : Revision
::newFromTitle( $this->mTitle
);
601 if( !$this->mNewRev
instanceof Revision
)
604 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
605 $this->mNewid
= $this->mNewRev
->getId();
607 // Set assorted variables
608 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
609 $this->mNewPage
= $this->mNewRev
->getTitle();
610 if( $this->mNewRev
->isCurrent() ) {
611 $newLink = $this->mNewPage
->escapeLocalUrl();
612 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
613 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
615 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
616 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
619 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
620 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
621 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
623 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
624 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
627 // Load the old revision object
628 $this->mOldRev
= false;
629 if( $this->mOldid
) {
630 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
631 } elseif ( $this->mOldid
=== 0 ) {
632 $rev = $this->mNewRev
->getPrevious();
634 $this->mOldid
= $rev->getId();
635 $this->mOldRev
= $rev;
637 // No previous revision; mark to show as first-version only.
638 $this->mOldid
= false;
639 $this->mOldRev
= false;
641 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
643 if( is_null( $this->mOldRev
) ) {
647 if ( $this->mOldRev
) {
648 $this->mOldPage
= $this->mOldRev
->getTitle();
650 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
651 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
652 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
653 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
654 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
656 // Add an "undo" link
657 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
658 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
665 * Load the text of the revisions, as well as revision data.
667 function loadText() {
668 if ( $this->mTextLoaded
== 2 ) {
671 // Whether it succeeds or fails, we don't want to try again
672 $this->mTextLoaded
= 2;
675 if ( !$this->loadRevisionData() ) {
678 if ( $this->mOldRev
) {
679 // FIXME: permission tests
680 $this->mOldtext
= $this->mOldRev
->revText();
681 if ( $this->mOldtext
=== false ) {
685 if ( $this->mNewRev
) {
686 $this->mNewtext
= $this->mNewRev
->revText();
687 if ( $this->mNewtext
=== false ) {
695 * Load the text of the new revision, not the old one
697 function loadNewText() {
698 if ( $this->mTextLoaded
>= 1 ) {
701 $this->mTextLoaded
= 1;
703 if ( !$this->loadRevisionData() ) {
706 $this->mNewtext
= $this->mNewRev
->getText();
713 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
715 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
716 // You may copy this code freely under the conditions of the GPL.
719 define('USE_ASSERTS', function_exists('assert'));
724 * @addtogroup DifferenceEngine
732 trigger_error('pure virtual', E_USER_ERROR
);
736 return $this->orig ?
sizeof($this->orig
) : 0;
739 function nclosing() {
740 return $this->closing ?
sizeof($this->closing
) : 0;
747 * @addtogroup DifferenceEngine
749 class _DiffOp_Copy
extends _DiffOp
{
752 function _DiffOp_Copy ($orig, $closing = false) {
753 if (!is_array($closing))
756 $this->closing
= $closing;
760 return new _DiffOp_Copy($this->closing
, $this->orig
);
767 * @addtogroup DifferenceEngine
769 class _DiffOp_Delete
extends _DiffOp
{
770 var $type = 'delete';
772 function _DiffOp_Delete ($lines) {
773 $this->orig
= $lines;
774 $this->closing
= false;
778 return new _DiffOp_Add($this->orig
);
785 * @addtogroup DifferenceEngine
787 class _DiffOp_Add
extends _DiffOp
{
790 function _DiffOp_Add ($lines) {
791 $this->closing
= $lines;
796 return new _DiffOp_Delete($this->closing
);
803 * @addtogroup DifferenceEngine
805 class _DiffOp_Change
extends _DiffOp
{
806 var $type = 'change';
808 function _DiffOp_Change ($orig, $closing) {
810 $this->closing
= $closing;
814 return new _DiffOp_Change($this->closing
, $this->orig
);
820 * Class used internally by Diff to actually compute the diffs.
822 * The algorithm used here is mostly lifted from the perl module
823 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
824 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
826 * More ideas are taken from:
827 * http://www.ics.uci.edu/~eppstein/161/960229.html
829 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
830 * diffutils-2.7, which can be found at:
831 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
833 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
836 * Line length limits for robustness added by Tim Starling, 2005-08-31
838 * @author Geoffrey T. Dairiki, Tim Starling
840 * @addtogroup DifferenceEngine
844 const MAX_XREF_LENGTH
= 10000;
846 function diff ($from_lines, $to_lines) {
847 $fname = '_DiffEngine::diff';
848 wfProfileIn( $fname );
850 $n_from = sizeof($from_lines);
851 $n_to = sizeof($to_lines);
853 $this->xchanged
= $this->ychanged
= array();
854 $this->xv
= $this->yv
= array();
855 $this->xind
= $this->yind
= array();
857 unset($this->in_seq
);
860 // Skip leading common lines.
861 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
862 if ($from_lines[$skip] !== $to_lines[$skip])
864 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
866 // Skip trailing common lines.
867 $xi = $n_from; $yi = $n_to;
868 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
869 if ($from_lines[$xi] !== $to_lines[$yi])
871 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
874 // Ignore lines which do not exist in both files.
875 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
876 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
879 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
880 $line = $to_lines[$yi];
881 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
883 $yhash[$this->_line_hash($line)] = 1;
887 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
888 $line = $from_lines[$xi];
889 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
896 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
898 // Merge edits when possible
899 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
900 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
902 // Compute the edit operations.
905 while ($xi < $n_from ||
$yi < $n_to) {
906 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
907 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
909 // Skip matching "snake".
911 while ( $xi < $n_from && $yi < $n_to
912 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
913 $copy[] = $from_lines[$xi++
];
917 $edits[] = new _DiffOp_Copy($copy);
919 // Find deletes & adds.
921 while ($xi < $n_from && $this->xchanged
[$xi])
922 $delete[] = $from_lines[$xi++
];
925 while ($yi < $n_to && $this->ychanged
[$yi])
926 $add[] = $to_lines[$yi++
];
929 $edits[] = new _DiffOp_Change($delete, $add);
931 $edits[] = new _DiffOp_Delete($delete);
933 $edits[] = new _DiffOp_Add($add);
935 wfProfileOut( $fname );
940 * Returns the whole line if it's small enough, or the MD5 hash otherwise
942 function _line_hash( $line ) {
943 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
951 /* Divide the Largest Common Subsequence (LCS) of the sequences
952 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
955 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
956 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
957 * sub sequences. The first sub-sequence is contained in [X0, X1),
958 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
959 * that (X0, Y0) == (XOFF, YOFF) and
960 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
962 * This function assumes that the first lines of the specified portions
963 * of the two files do not match, and likewise that the last lines do not
964 * match. The caller must trim matching lines from the beginning and end
965 * of the portions it is going to specify.
967 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
968 $fname = '_DiffEngine::_diag';
969 wfProfileIn( $fname );
972 if ($xlim - $xoff > $ylim - $yoff) {
973 // Things seems faster (I'm not sure I understand why)
974 // when the shortest sequence in X.
976 list ($xoff, $xlim, $yoff, $ylim)
977 = array( $yoff, $ylim, $xoff, $xlim);
981 for ($i = $ylim - 1; $i >= $yoff; $i--)
982 $ymatches[$this->xv
[$i]][] = $i;
984 for ($i = $ylim - 1; $i >= $yoff; $i--)
985 $ymatches[$this->yv
[$i]][] = $i;
988 $this->seq
[0]= $yoff - 1;
989 $this->in_seq
= array();
992 $numer = $xlim - $xoff +
$nchunks - 1;
994 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
995 wfProfileIn( "$fname-chunk" );
997 for ($i = 0; $i <= $this->lcs
; $i++
)
998 $ymids[$i][$chunk-1] = $this->seq
[$i];
1000 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1001 for ( ; $x < $x1; $x++
) {
1002 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1003 if (empty($ymatches[$line]))
1005 $matches = $ymatches[$line];
1007 while (list ($junk, $y) = each($matches))
1008 if (empty($this->in_seq
[$y])) {
1009 $k = $this->_lcs_pos($y);
1010 USE_ASSERTS
&& assert($k > 0);
1011 $ymids[$k] = $ymids[$k-1];
1014 while (list ( /* $junk */, $y) = each($matches)) {
1015 if ($y > $this->seq
[$k-1]) {
1016 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1017 // Optimization: this is a common case:
1018 // next match is just replacing previous match.
1019 $this->in_seq
[$this->seq
[$k]] = false;
1020 $this->seq
[$k] = $y;
1021 $this->in_seq
[$y] = 1;
1022 } else if (empty($this->in_seq
[$y])) {
1023 $k = $this->_lcs_pos($y);
1024 USE_ASSERTS
&& assert($k > 0);
1025 $ymids[$k] = $ymids[$k-1];
1029 wfProfileOut( "$fname-chunk" );
1032 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1033 $ymid = $ymids[$this->lcs
];
1034 for ($n = 0; $n < $nchunks - 1; $n++
) {
1035 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1036 $y1 = $ymid[$n] +
1;
1037 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1039 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1041 wfProfileOut( $fname );
1042 return array($this->lcs
, $seps);
1045 function _lcs_pos ($ypos) {
1046 $fname = '_DiffEngine::_lcs_pos';
1047 wfProfileIn( $fname );
1050 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1051 $this->seq
[++
$this->lcs
] = $ypos;
1052 $this->in_seq
[$ypos] = 1;
1053 wfProfileOut( $fname );
1058 while ($beg < $end) {
1059 $mid = (int)(($beg +
$end) / 2);
1060 if ( $ypos > $this->seq
[$mid] )
1066 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1068 $this->in_seq
[$this->seq
[$end]] = false;
1069 $this->seq
[$end] = $ypos;
1070 $this->in_seq
[$ypos] = 1;
1071 wfProfileOut( $fname );
1075 /* Find LCS of two sequences.
1077 * The results are recorded in the vectors $this->{x,y}changed[], by
1078 * storing a 1 in the element for each line that is an insertion
1079 * or deletion (ie. is not in the LCS).
1081 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1083 * Note that XLIM, YLIM are exclusive bounds.
1084 * All line numbers are origin-0 and discarded lines are not counted.
1086 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1087 $fname = '_DiffEngine::_compareseq';
1088 wfProfileIn( $fname );
1090 // Slide down the bottom initial diagonal.
1091 while ($xoff < $xlim && $yoff < $ylim
1092 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1097 // Slide up the top initial diagonal.
1098 while ($xlim > $xoff && $ylim > $yoff
1099 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1104 if ($xoff == $xlim ||
$yoff == $ylim)
1107 // This is ad hoc but seems to work well.
1108 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1109 //$nchunks = max(2,min(8,(int)$nchunks));
1110 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1112 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1116 // X and Y sequences have no common subsequence:
1117 // mark all changed.
1118 while ($yoff < $ylim)
1119 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1120 while ($xoff < $xlim)
1121 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1123 // Use the partitions to split this problem into subproblems.
1126 while ($pt2 = next($seps)) {
1127 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1131 wfProfileOut( $fname );
1134 /* Adjust inserts/deletes of identical lines to join changes
1135 * as much as possible.
1137 * We do something when a run of changed lines include a
1138 * line at one end and has an excluded, identical line at the other.
1139 * We are free to choose which identical line is included.
1140 * `compareseq' usually chooses the one at the beginning,
1141 * but usually it is cleaner to consider the following identical line
1142 * to be the "change".
1144 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1146 function _shift_boundaries ($lines, &$changed, $other_changed) {
1147 $fname = '_DiffEngine::_shift_boundaries';
1148 wfProfileIn( $fname );
1152 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1153 $len = sizeof($lines);
1154 $other_len = sizeof($other_changed);
1158 * Scan forwards to find beginning of another run of changes.
1159 * Also keep track of the corresponding point in the other file.
1161 * Throughout this code, $i and $j are adjusted together so that
1162 * the first $i elements of $changed and the first $j elements
1163 * of $other_changed both contain the same number of zeros
1164 * (unchanged lines).
1165 * Furthermore, $j is always kept so that $j == $other_len or
1166 * $other_changed[$j] == false.
1168 while ($j < $other_len && $other_changed[$j])
1171 while ($i < $len && ! $changed[$i]) {
1172 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1174 while ($j < $other_len && $other_changed[$j])
1183 // Find the end of this run of changes.
1184 while (++
$i < $len && $changed[$i])
1189 * Record the length of this run of changes, so that
1190 * we can later determine whether the run has grown.
1192 $runlength = $i - $start;
1195 * Move the changed region back, so long as the
1196 * previous unchanged line matches the last changed one.
1197 * This merges with previous changed regions.
1199 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1200 $changed[--$start] = 1;
1201 $changed[--$i] = false;
1202 while ($start > 0 && $changed[$start - 1])
1204 USE_ASSERTS
&& assert('$j > 0');
1205 while ($other_changed[--$j])
1207 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1211 * Set CORRESPONDING to the end of the changed run, at the last
1212 * point where it corresponds to a changed run in the other file.
1213 * CORRESPONDING == LEN means no such point has been found.
1215 $corresponding = $j < $other_len ?
$i : $len;
1218 * Move the changed region forward, so long as the
1219 * first changed line matches the following unchanged one.
1220 * This merges with following changed regions.
1221 * Do this second, so that if there are no merges,
1222 * the changed region is moved forward as far as possible.
1224 while ($i < $len && $lines[$start] == $lines[$i]) {
1225 $changed[$start++
] = false;
1227 while ($i < $len && $changed[$i])
1230 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1232 if ($j < $other_len && $other_changed[$j]) {
1233 $corresponding = $i;
1234 while ($j < $other_len && $other_changed[$j])
1238 } while ($runlength != $i - $start);
1241 * If possible, move the fully-merged run of changes
1242 * back to a corresponding run in the other file.
1244 while ($corresponding < $i) {
1245 $changed[--$start] = 1;
1247 USE_ASSERTS
&& assert('$j > 0');
1248 while ($other_changed[--$j])
1250 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1253 wfProfileOut( $fname );
1258 * Class representing a 'diff' between two sequences of strings.
1261 * @addtogroup DifferenceEngine
1269 * Computes diff between sequences of strings.
1271 * @param $from_lines array An array of strings.
1272 * (Typically these are lines from a file.)
1273 * @param $to_lines array An array of strings.
1275 function Diff($from_lines, $to_lines) {
1276 $eng = new _DiffEngine
;
1277 $this->edits
= $eng->diff($from_lines, $to_lines);
1278 //$this->_check($from_lines, $to_lines);
1282 * Compute reversed Diff.
1286 * $diff = new Diff($lines1, $lines2);
1287 * $rev = $diff->reverse();
1288 * @return object A Diff object representing the inverse of the
1291 function reverse () {
1293 $rev->edits
= array();
1294 foreach ($this->edits
as $edit) {
1295 $rev->edits
[] = $edit->reverse();
1301 * Check for empty diff.
1303 * @return bool True iff two sequences were identical.
1305 function isEmpty () {
1306 foreach ($this->edits
as $edit) {
1307 if ($edit->type
!= 'copy')
1314 * Compute the length of the Longest Common Subsequence (LCS).
1316 * This is mostly for diagnostic purposed.
1318 * @return int The length of the LCS.
1322 foreach ($this->edits
as $edit) {
1323 if ($edit->type
== 'copy')
1324 $lcs +
= sizeof($edit->orig
);
1330 * Get the original set of lines.
1332 * This reconstructs the $from_lines parameter passed to the
1335 * @return array The original sequence of strings.
1340 foreach ($this->edits
as $edit) {
1342 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1348 * Get the closing set of lines.
1350 * This reconstructs the $to_lines parameter passed to the
1353 * @return array The sequence of strings.
1355 function closing() {
1358 foreach ($this->edits
as $edit) {
1360 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1366 * Check a Diff for validity.
1368 * This is here only for debugging purposes.
1370 function _check ($from_lines, $to_lines) {
1371 $fname = 'Diff::_check';
1372 wfProfileIn( $fname );
1373 if (serialize($from_lines) != serialize($this->orig()))
1374 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1375 if (serialize($to_lines) != serialize($this->closing()))
1376 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1378 $rev = $this->reverse();
1379 if (serialize($to_lines) != serialize($rev->orig()))
1380 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1381 if (serialize($from_lines) != serialize($rev->closing()))
1382 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1386 foreach ($this->edits
as $edit) {
1387 if ( $prevtype == $edit->type
)
1388 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1389 $prevtype = $edit->type
;
1392 $lcs = $this->lcs();
1393 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1394 wfProfileOut( $fname );
1399 * @todo document, bad name.
1401 * @addtogroup DifferenceEngine
1403 class MappedDiff
extends Diff
1408 * Computes diff between sequences of strings.
1410 * This can be used to compute things like
1411 * case-insensitve diffs, or diffs which ignore
1412 * changes in white-space.
1414 * @param $from_lines array An array of strings.
1415 * (Typically these are lines from a file.)
1417 * @param $to_lines array An array of strings.
1419 * @param $mapped_from_lines array This array should
1420 * have the same size number of elements as $from_lines.
1421 * The elements in $mapped_from_lines and
1422 * $mapped_to_lines are what is actually compared
1423 * when computing the diff.
1425 * @param $mapped_to_lines array This array should
1426 * have the same number of elements as $to_lines.
1428 function MappedDiff($from_lines, $to_lines,
1429 $mapped_from_lines, $mapped_to_lines) {
1430 $fname = 'MappedDiff::MappedDiff';
1431 wfProfileIn( $fname );
1433 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1434 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1436 $this->Diff($mapped_from_lines, $mapped_to_lines);
1439 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1440 $orig = &$this->edits
[$i]->orig
;
1441 if (is_array($orig)) {
1442 $orig = array_slice($from_lines, $xi, sizeof($orig));
1443 $xi +
= sizeof($orig);
1446 $closing = &$this->edits
[$i]->closing
;
1447 if (is_array($closing)) {
1448 $closing = array_slice($to_lines, $yi, sizeof($closing));
1449 $yi +
= sizeof($closing);
1452 wfProfileOut( $fname );
1457 * A class to format Diffs
1459 * This class formats the diff in classic diff format.
1460 * It is intended that this class be customized via inheritance,
1461 * to obtain fancier outputs.
1464 * @addtogroup DifferenceEngine
1469 * Number of leading context "lines" to preserve.
1471 * This should be left at zero for this class, but subclasses
1472 * may want to set this to other values.
1474 var $leading_context_lines = 0;
1477 * Number of trailing context "lines" to preserve.
1479 * This should be left at zero for this class, but subclasses
1480 * may want to set this to other values.
1482 var $trailing_context_lines = 0;
1487 * @param $diff object A Diff object.
1488 * @return string The formatted output.
1490 function format($diff) {
1491 $fname = 'DiffFormatter::format';
1492 wfProfileIn( $fname );
1498 $nlead = $this->leading_context_lines
;
1499 $ntrail = $this->trailing_context_lines
;
1501 $this->_start_diff();
1503 foreach ($diff->edits
as $edit) {
1504 if ($edit->type
== 'copy') {
1505 if (is_array($block)) {
1506 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1511 $context = array_slice($edit->orig
, 0, $ntrail);
1512 $block[] = new _DiffOp_Copy($context);
1514 $this->_block($x0, $ntrail +
$xi - $x0,
1515 $y0, $ntrail +
$yi - $y0,
1520 $context = $edit->orig
;
1523 if (! is_array($block)) {
1524 $context = array_slice($context, sizeof($context) - $nlead);
1525 $x0 = $xi - sizeof($context);
1526 $y0 = $yi - sizeof($context);
1529 $block[] = new _DiffOp_Copy($context);
1535 $xi +
= sizeof($edit->orig
);
1537 $yi +
= sizeof($edit->closing
);
1540 if (is_array($block))
1541 $this->_block($x0, $xi - $x0,
1545 $end = $this->_end_diff();
1546 wfProfileOut( $fname );
1550 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1551 $fname = 'DiffFormatter::_block';
1552 wfProfileIn( $fname );
1553 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1554 foreach ($edits as $edit) {
1555 if ($edit->type
== 'copy')
1556 $this->_context($edit->orig
);
1557 elseif ($edit->type
== 'add')
1558 $this->_added($edit->closing
);
1559 elseif ($edit->type
== 'delete')
1560 $this->_deleted($edit->orig
);
1561 elseif ($edit->type
== 'change')
1562 $this->_changed($edit->orig
, $edit->closing
);
1564 trigger_error('Unknown edit type', E_USER_ERROR
);
1566 $this->_end_block();
1567 wfProfileOut( $fname );
1570 function _start_diff() {
1574 function _end_diff() {
1575 $val = ob_get_contents();
1580 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1582 $xbeg .= "," . ($xbeg +
$xlen - 1);
1584 $ybeg .= "," . ($ybeg +
$ylen - 1);
1586 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1589 function _start_block($header) {
1593 function _end_block() {
1596 function _lines($lines, $prefix = ' ') {
1597 foreach ($lines as $line)
1598 echo "$prefix $line\n";
1601 function _context($lines) {
1602 $this->_lines($lines);
1605 function _added($lines) {
1606 $this->_lines($lines, '>');
1608 function _deleted($lines) {
1609 $this->_lines($lines, '<');
1612 function _changed($orig, $closing) {
1613 $this->_deleted($orig);
1615 $this->_added($closing);
1621 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1625 define('NBSP', ' '); // iso-8859-x non-breaking space.
1630 * @addtogroup DifferenceEngine
1632 class _HWLDF_WordAccumulator
{
1633 function _HWLDF_WordAccumulator () {
1634 $this->_lines
= array();
1640 function _flushGroup ($new_tag) {
1641 if ($this->_group
!== '') {
1642 if ($this->_tag
== 'ins')
1643 $this->_line
.= '<ins class="diffchange">' .
1644 htmlspecialchars ( $this->_group
) . '</ins>';
1645 elseif ($this->_tag
== 'del')
1646 $this->_line
.= '<del class="diffchange">' .
1647 htmlspecialchars ( $this->_group
) . '</del>';
1649 $this->_line
.= htmlspecialchars ( $this->_group
);
1652 $this->_tag
= $new_tag;
1655 function _flushLine ($new_tag) {
1656 $this->_flushGroup($new_tag);
1657 if ($this->_line
!= '')
1658 array_push ( $this->_lines
, $this->_line
);
1660 # make empty lines visible by inserting an NBSP
1661 array_push ( $this->_lines
, NBSP
);
1665 function addWords ($words, $tag = '') {
1666 if ($tag != $this->_tag
)
1667 $this->_flushGroup($tag);
1669 foreach ($words as $word) {
1670 // new-line should only come as first char of word.
1673 if ($word[0] == "\n") {
1674 $this->_flushLine($tag);
1675 $word = substr($word, 1);
1677 assert(!strstr($word, "\n"));
1678 $this->_group
.= $word;
1682 function getLines() {
1683 $this->_flushLine('~done');
1684 return $this->_lines
;
1691 * @addtogroup DifferenceEngine
1693 class WordLevelDiff
extends MappedDiff
1695 const MAX_LINE_LENGTH
= 10000;
1697 function WordLevelDiff ($orig_lines, $closing_lines) {
1698 $fname = 'WordLevelDiff::WordLevelDiff';
1699 wfProfileIn( $fname );
1701 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1702 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1704 $this->MappedDiff($orig_words, $closing_words,
1705 $orig_stripped, $closing_stripped);
1706 wfProfileOut( $fname );
1709 function _split($lines) {
1710 $fname = 'WordLevelDiff::_split';
1711 wfProfileIn( $fname );
1714 $stripped = array();
1716 foreach ( $lines as $line ) {
1717 # If the line is too long, just pretend the entire line is one big word
1718 # This prevents resource exhaustion problems
1725 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1727 $stripped[] = $line;
1730 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1733 $words = array_merge( $words, $m[0] );
1734 $stripped = array_merge( $stripped, $m[1] );
1738 wfProfileOut( $fname );
1739 return array($words, $stripped);
1743 $fname = 'WordLevelDiff::orig';
1744 wfProfileIn( $fname );
1745 $orig = new _HWLDF_WordAccumulator
;
1747 foreach ($this->edits
as $edit) {
1748 if ($edit->type
== 'copy')
1749 $orig->addWords($edit->orig
);
1750 elseif ($edit->orig
)
1751 $orig->addWords($edit->orig
, 'del');
1753 $lines = $orig->getLines();
1754 wfProfileOut( $fname );
1758 function closing () {
1759 $fname = 'WordLevelDiff::closing';
1760 wfProfileIn( $fname );
1761 $closing = new _HWLDF_WordAccumulator
;
1763 foreach ($this->edits
as $edit) {
1764 if ($edit->type
== 'copy')
1765 $closing->addWords($edit->closing
);
1766 elseif ($edit->closing
)
1767 $closing->addWords($edit->closing
, 'ins');
1769 $lines = $closing->getLines();
1770 wfProfileOut( $fname );
1776 * Wikipedia Table style diff formatter.
1779 * @addtogroup DifferenceEngine
1781 class TableDiffFormatter
extends DiffFormatter
1783 function TableDiffFormatter() {
1784 $this->leading_context_lines
= 2;
1785 $this->trailing_context_lines
= 2;
1788 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1789 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1790 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1794 function _start_block( $header ) {
1798 function _end_block() {
1801 function _lines( $lines, $prefix=' ', $color='white' ) {
1804 # HTML-escape parameter before calling this
1805 function addedLine( $line ) {
1806 return $this->wrapLine( '+', 'diff-addedline', $line );
1809 # HTML-escape parameter before calling this
1810 function deletedLine( $line ) {
1811 return $this->wrapLine( '-', 'diff-deletedline', $line );
1814 # HTML-escape parameter before calling this
1815 function contextLine( $line ) {
1816 return $this->wrapLine( ' ', 'diff-context', $line );
1819 private function wrapLine( $marker, $class, $line ) {
1820 if( $line !== '' ) {
1821 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1822 $line = "<div>$line</div>";
1824 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1827 function emptyLine() {
1828 return '<td colspan="2"> </td>';
1831 function _added( $lines ) {
1832 foreach ($lines as $line) {
1833 echo '<tr>' . $this->emptyLine() .
1834 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1838 function _deleted($lines) {
1839 foreach ($lines as $line) {
1840 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1841 $this->emptyLine() . "</tr>\n";
1845 function _context( $lines ) {
1846 foreach ($lines as $line) {
1848 $this->contextLine( htmlspecialchars ( $line ) ) .
1849 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1853 function _changed( $orig, $closing ) {
1854 $fname = 'TableDiffFormatter::_changed';
1855 wfProfileIn( $fname );
1857 $diff = new WordLevelDiff( $orig, $closing );
1858 $del = $diff->orig();
1859 $add = $diff->closing();
1861 # Notice that WordLevelDiff returns HTML-escaped output.
1862 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1864 while ( $line = array_shift( $del ) ) {
1865 $aline = array_shift( $add );
1866 echo '<tr>' . $this->deletedLine( $line ) .
1867 $this->addedLine( $aline ) . "</tr>\n";
1869 foreach ($add as $line) { # If any leftovers
1870 echo '<tr>' . $this->emptyLine() .
1871 $this->addedLine( $line ) . "</tr>\n";
1873 wfProfileOut( $fname );