e88234269c5d2daef625f055a967d58fb4760f7a
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 $change = RecentChange
::newFromConds(
171 // Add redundant timestamp condition so we can use the
173 'rc_timestamp' => $this->mNewRev
->getTimestamp(),
174 'rc_this_oldid' => $this->mNewid
,
175 'rc_last_oldid' => $this->mOldid
,
180 if( $change instanceof RecentChange
) {
181 $rcid = $change->mAttribs
['rc_id'];
189 $patrol = ' [' . $sk->makeKnownLinkObj(
191 wfMsgHtml( 'markaspatrolleddiff' ),
192 "action=markpatrolled&rcid={$rcid}"
201 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
202 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
203 if ( $this->mNewRev
->isCurrent() ) {
204 $nextlink = ' ';
206 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
207 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
213 if ($this->mOldRev
->mMinorEdit
== 1) {
214 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
215 wfMsg( 'minoreditletter') ) . ' ';
218 if ($this->mNewRev
->mMinorEdit
== 1) {
219 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
220 wfMsg( 'minoreditletter') ) . ' ';
223 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $this->mOldtitle
. '</strong></div>' .
224 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
) . "</div>" .
225 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly ) . "</div>" .
226 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
227 $newHeader = '<div id="mw-diff-ntitle1"><strong>' .$this->mNewtitle
. '</strong></div>' .
228 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
) . " $rollback</div>" .
229 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly ) . "</div>" .
230 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
232 $this->showDiff( $oldHeader, $newHeader );
235 $this->renderNewRevision();
237 wfProfileOut( $fname );
241 * Show the new revision of the page.
243 function renderNewRevision() {
245 $fname = 'DifferenceEngine::renderNewRevision';
246 wfProfileIn( $fname );
248 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
249 #add deleted rev tag if needed
250 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
251 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
254 if( !$this->mNewRev
->isCurrent() ) {
255 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
258 $this->loadNewText();
259 if( is_object( $this->mNewRev
) ) {
260 $wgOut->setRevisionId( $this->mNewRev
->getId() );
263 $wgOut->addWikiTextTidy( $this->mNewtext
);
265 if( !$this->mNewRev
->isCurrent() ) {
266 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
269 wfProfileOut( $fname );
273 * Show the first revision of an article. Uses normal diff headers in
274 * contrast to normal "old revision" display style.
276 function showFirstRevision() {
277 global $wgOut, $wgUser;
279 $fname = 'DifferenceEngine::showFirstRevision';
280 wfProfileIn( $fname );
282 # Get article text from the DB
284 if ( ! $this->loadNewText() ) {
285 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
287 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
288 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
289 $wgOut->addWikitext( $mtext );
290 wfProfileOut( $fname );
293 if ( $this->mNewRev
->isCurrent() ) {
294 $wgOut->setArticleFlag( true );
297 # Check if user is allowed to look at this page. If not, bail out.
299 if ( !( $this->mTitle
->userCanRead() ) ) {
300 $wgOut->loginToUse();
302 wfProfileOut( $fname );
306 # Prepare the header box
308 $sk = $wgUser->getSkin();
310 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
311 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
312 $sk->revUserTools( $this->mNewRev
) . "<br />" .
313 $sk->revComment( $this->mNewRev
) . "<br />" .
314 $nextlink . "</div>\n";
316 $wgOut->addHTML( $header );
318 $wgOut->setSubtitle( wfMsg( 'difference' ) );
319 $wgOut->setRobotpolicy( 'noindex,nofollow' );
321 wfProfileOut( $fname );
325 * Get the diff text, send it to $wgOut
326 * Returns false if the diff could not be generated, otherwise returns true
328 function showDiff( $otitle, $ntitle ) {
330 $diff = $this->getDiff( $otitle, $ntitle );
331 if ( $diff === false ) {
332 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
335 $this->showDiffStyle();
336 $wgOut->addHTML( $diff );
342 * Add style sheets and supporting JS for diff display.
344 function showDiffStyle() {
345 global $wgStylePath, $wgStyleVersion, $wgOut;
346 $wgOut->addStyle( 'common/diff.css' );
348 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
349 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
353 * Get complete diff table, including header
355 * @param Title $otitle Old title
356 * @param Title $ntitle New title
359 function getDiff( $otitle, $ntitle ) {
360 $body = $this->getDiffBody();
361 if ( $body === false ) {
364 $multi = $this->getMultiNotice();
365 return $this->addHeader( $body, $otitle, $ntitle, $multi );
370 * Get the diff table body, without header
374 function getDiffBody() {
376 $fname = 'DifferenceEngine::getDiffBody';
377 wfProfileIn( $fname );
381 if ( $this->mOldid
&& $this->mNewid
) {
382 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
384 if ( !$this->mRefreshCache
) {
385 $difftext = $wgMemc->get( $key );
387 wfIncrStats( 'diff_cache_hit' );
388 $difftext = $this->localiseLineNumbers( $difftext );
389 $difftext .= "\n<!-- diff cache key $key -->\n";
390 wfProfileOut( $fname );
393 } // don't try to load but save the result
396 #loadtext is permission safe, this just clears out the diff
397 if ( !$this->loadText() ) {
398 wfProfileOut( $fname );
400 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
402 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
406 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
408 // Save to cache for 7 days
409 if ( $key !== false && $difftext !== false ) {
410 wfIncrStats( 'diff_cache_miss' );
411 $wgMemc->set( $key, $difftext, 7*86400 );
413 wfIncrStats( 'diff_uncacheable' );
415 // Replace line numbers with the text in the user's language
416 if ( $difftext !== false ) {
417 $difftext = $this->localiseLineNumbers( $difftext );
419 wfProfileOut( $fname );
424 * Generate a diff, no caching
425 * $otext and $ntext must be already segmented
427 function generateDiffBody( $otext, $ntext ) {
428 global $wgExternalDiffEngine, $wgContLang;
429 $fname = 'DifferenceEngine::generateDiffBody';
431 $otext = str_replace( "\r\n", "\n", $otext );
432 $ntext = str_replace( "\r\n", "\n", $ntext );
434 if ( $wgExternalDiffEngine == 'wikidiff' ) {
435 # For historical reasons, external diff engine expects
436 # input text to be HTML-escaped already
437 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
438 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
439 if( !function_exists( 'wikidiff_do_diff' ) ) {
440 dl('php_wikidiff.so');
442 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
445 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
446 # Better external diff engine, the 2 may some day be dropped
447 # This one does the escaping and segmenting itself
448 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
449 wfProfileIn( "$fname-dl" );
450 @dl
('php_wikidiff2.so');
451 wfProfileOut( "$fname-dl" );
453 if ( function_exists( 'wikidiff2_do_diff' ) ) {
454 wfProfileIn( 'wikidiff2_do_diff' );
455 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
456 wfProfileOut( 'wikidiff2_do_diff' );
460 if ( $wgExternalDiffEngine !== false ) {
462 global $wgTmpDirectory;
463 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
464 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
466 $tempFile1 = fopen( $tempName1, "w" );
468 wfProfileOut( $fname );
471 $tempFile2 = fopen( $tempName2, "w" );
473 wfProfileOut( $fname );
476 fwrite( $tempFile1, $otext );
477 fwrite( $tempFile2, $ntext );
478 fclose( $tempFile1 );
479 fclose( $tempFile2 );
480 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
481 wfProfileIn( "$fname-shellexec" );
482 $difftext = wfShellExec( $cmd );
483 wfProfileOut( "$fname-shellexec" );
484 unlink( $tempName1 );
485 unlink( $tempName2 );
490 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
491 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
492 $diffs = new Diff( $ota, $nta );
493 $formatter = new TableDiffFormatter();
494 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
499 * Replace line numbers with the text in the user's language
501 function localiseLineNumbers( $text ) {
502 return preg_replace_callback( '/<!--LINE (\d+)-->/',
503 array( &$this, 'localiseLineNumbersCb' ), $text );
506 function localiseLineNumbersCb( $matches ) {
508 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
513 * If there are revisions between the ones being compared, return a note saying so.
515 function getMultiNotice() {
516 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
519 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
520 // Comparing two different pages? Count would be meaningless.
524 $oldid = $this->mOldRev
->getId();
525 $newid = $this->mNewRev
->getId();
526 if ( $oldid > $newid ) {
527 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
530 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
534 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
539 * Add the header to a diff body
541 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
544 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
545 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
547 if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
548 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
552 <col class='diff-marker' />
553 <col class='diff-content' />
554 <col class='diff-marker' />
555 <col class='diff-content' />
557 <td colspan='2' class='diff-otitle'>{$otitle}</td>
558 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
563 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
565 return $header . $diff . "</table>";
569 * Use specified text instead of loading from the database
571 function setText( $oldText, $newText ) {
572 $this->mOldtext
= $oldText;
573 $this->mNewtext
= $newText;
574 $this->mTextLoaded
= 2;
578 * Load revision metadata for the specified articles. If newid is 0, then compare
579 * the old article in oldid to the current article; if oldid is 0, then
580 * compare the current article to the immediately previous one (ignoring the
583 * If oldid is false, leave the corresponding revision object set
584 * to false. This is impossible via ordinary user input, and is provided for
587 function loadRevisionData() {
589 if ( $this->mRevisionsLoaded
) {
592 // Whether it succeeds or fails, we don't want to try again
593 $this->mRevisionsLoaded
= true;
596 // Load the new revision object
597 $this->mNewRev
= $this->mNewid
598 ? Revision
::newFromId( $this->mNewid
)
599 : Revision
::newFromTitle( $this->mTitle
);
600 if( !$this->mNewRev
instanceof Revision
)
603 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
604 $this->mNewid
= $this->mNewRev
->getId();
606 // Set assorted variables
607 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
608 $this->mNewPage
= $this->mNewRev
->getTitle();
609 if( $this->mNewRev
->isCurrent() ) {
610 $newLink = $this->mNewPage
->escapeLocalUrl();
611 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
612 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
614 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
615 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
618 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
619 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
620 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
622 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
623 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
626 // Load the old revision object
627 $this->mOldRev
= false;
628 if( $this->mOldid
) {
629 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
630 } elseif ( $this->mOldid
=== 0 ) {
631 $rev = $this->mNewRev
->getPrevious();
633 $this->mOldid
= $rev->getId();
634 $this->mOldRev
= $rev;
636 // No previous revision; mark to show as first-version only.
637 $this->mOldid
= false;
638 $this->mOldRev
= false;
640 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
642 if( is_null( $this->mOldRev
) ) {
646 if ( $this->mOldRev
) {
647 $this->mOldPage
= $this->mOldRev
->getTitle();
649 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
650 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
651 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
652 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
653 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
655 // Add an "undo" link
656 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
657 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
664 * Load the text of the revisions, as well as revision data.
666 function loadText() {
667 if ( $this->mTextLoaded
== 2 ) {
670 // Whether it succeeds or fails, we don't want to try again
671 $this->mTextLoaded
= 2;
674 if ( !$this->loadRevisionData() ) {
677 if ( $this->mOldRev
) {
678 // FIXME: permission tests
679 $this->mOldtext
= $this->mOldRev
->revText();
680 if ( $this->mOldtext
=== false ) {
684 if ( $this->mNewRev
) {
685 $this->mNewtext
= $this->mNewRev
->revText();
686 if ( $this->mNewtext
=== false ) {
694 * Load the text of the new revision, not the old one
696 function loadNewText() {
697 if ( $this->mTextLoaded
>= 1 ) {
700 $this->mTextLoaded
= 1;
702 if ( !$this->loadRevisionData() ) {
705 $this->mNewtext
= $this->mNewRev
->getText();
712 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
714 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
715 // You may copy this code freely under the conditions of the GPL.
718 define('USE_ASSERTS', function_exists('assert'));
723 * @addtogroup DifferenceEngine
731 trigger_error('pure virtual', E_USER_ERROR
);
735 return $this->orig ?
sizeof($this->orig
) : 0;
738 function nclosing() {
739 return $this->closing ?
sizeof($this->closing
) : 0;
746 * @addtogroup DifferenceEngine
748 class _DiffOp_Copy
extends _DiffOp
{
751 function _DiffOp_Copy ($orig, $closing = false) {
752 if (!is_array($closing))
755 $this->closing
= $closing;
759 return new _DiffOp_Copy($this->closing
, $this->orig
);
766 * @addtogroup DifferenceEngine
768 class _DiffOp_Delete
extends _DiffOp
{
769 var $type = 'delete';
771 function _DiffOp_Delete ($lines) {
772 $this->orig
= $lines;
773 $this->closing
= false;
777 return new _DiffOp_Add($this->orig
);
784 * @addtogroup DifferenceEngine
786 class _DiffOp_Add
extends _DiffOp
{
789 function _DiffOp_Add ($lines) {
790 $this->closing
= $lines;
795 return new _DiffOp_Delete($this->closing
);
802 * @addtogroup DifferenceEngine
804 class _DiffOp_Change
extends _DiffOp
{
805 var $type = 'change';
807 function _DiffOp_Change ($orig, $closing) {
809 $this->closing
= $closing;
813 return new _DiffOp_Change($this->closing
, $this->orig
);
819 * Class used internally by Diff to actually compute the diffs.
821 * The algorithm used here is mostly lifted from the perl module
822 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
823 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
825 * More ideas are taken from:
826 * http://www.ics.uci.edu/~eppstein/161/960229.html
828 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
829 * diffutils-2.7, which can be found at:
830 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
832 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
835 * Line length limits for robustness added by Tim Starling, 2005-08-31
837 * @author Geoffrey T. Dairiki, Tim Starling
839 * @addtogroup DifferenceEngine
843 const MAX_XREF_LENGTH
= 10000;
845 function diff ($from_lines, $to_lines) {
846 $fname = '_DiffEngine::diff';
847 wfProfileIn( $fname );
849 $n_from = sizeof($from_lines);
850 $n_to = sizeof($to_lines);
852 $this->xchanged
= $this->ychanged
= array();
853 $this->xv
= $this->yv
= array();
854 $this->xind
= $this->yind
= array();
856 unset($this->in_seq
);
859 // Skip leading common lines.
860 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
861 if ($from_lines[$skip] !== $to_lines[$skip])
863 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
865 // Skip trailing common lines.
866 $xi = $n_from; $yi = $n_to;
867 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
868 if ($from_lines[$xi] !== $to_lines[$yi])
870 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
873 // Ignore lines which do not exist in both files.
874 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
875 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
878 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
879 $line = $to_lines[$yi];
880 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
882 $yhash[$this->_line_hash($line)] = 1;
886 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
887 $line = $from_lines[$xi];
888 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
895 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
897 // Merge edits when possible
898 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
899 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
901 // Compute the edit operations.
904 while ($xi < $n_from ||
$yi < $n_to) {
905 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
906 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
908 // Skip matching "snake".
910 while ( $xi < $n_from && $yi < $n_to
911 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
912 $copy[] = $from_lines[$xi++
];
916 $edits[] = new _DiffOp_Copy($copy);
918 // Find deletes & adds.
920 while ($xi < $n_from && $this->xchanged
[$xi])
921 $delete[] = $from_lines[$xi++
];
924 while ($yi < $n_to && $this->ychanged
[$yi])
925 $add[] = $to_lines[$yi++
];
928 $edits[] = new _DiffOp_Change($delete, $add);
930 $edits[] = new _DiffOp_Delete($delete);
932 $edits[] = new _DiffOp_Add($add);
934 wfProfileOut( $fname );
939 * Returns the whole line if it's small enough, or the MD5 hash otherwise
941 function _line_hash( $line ) {
942 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
950 /* Divide the Largest Common Subsequence (LCS) of the sequences
951 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
954 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
955 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
956 * sub sequences. The first sub-sequence is contained in [X0, X1),
957 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
958 * that (X0, Y0) == (XOFF, YOFF) and
959 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
961 * This function assumes that the first lines of the specified portions
962 * of the two files do not match, and likewise that the last lines do not
963 * match. The caller must trim matching lines from the beginning and end
964 * of the portions it is going to specify.
966 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
967 $fname = '_DiffEngine::_diag';
968 wfProfileIn( $fname );
971 if ($xlim - $xoff > $ylim - $yoff) {
972 // Things seems faster (I'm not sure I understand why)
973 // when the shortest sequence in X.
975 list ($xoff, $xlim, $yoff, $ylim)
976 = array( $yoff, $ylim, $xoff, $xlim);
980 for ($i = $ylim - 1; $i >= $yoff; $i--)
981 $ymatches[$this->xv
[$i]][] = $i;
983 for ($i = $ylim - 1; $i >= $yoff; $i--)
984 $ymatches[$this->yv
[$i]][] = $i;
987 $this->seq
[0]= $yoff - 1;
988 $this->in_seq
= array();
991 $numer = $xlim - $xoff +
$nchunks - 1;
993 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
994 wfProfileIn( "$fname-chunk" );
996 for ($i = 0; $i <= $this->lcs
; $i++
)
997 $ymids[$i][$chunk-1] = $this->seq
[$i];
999 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1000 for ( ; $x < $x1; $x++
) {
1001 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1002 if (empty($ymatches[$line]))
1004 $matches = $ymatches[$line];
1006 while (list ($junk, $y) = each($matches))
1007 if (empty($this->in_seq
[$y])) {
1008 $k = $this->_lcs_pos($y);
1009 USE_ASSERTS
&& assert($k > 0);
1010 $ymids[$k] = $ymids[$k-1];
1013 while (list ( /* $junk */, $y) = each($matches)) {
1014 if ($y > $this->seq
[$k-1]) {
1015 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1016 // Optimization: this is a common case:
1017 // next match is just replacing previous match.
1018 $this->in_seq
[$this->seq
[$k]] = false;
1019 $this->seq
[$k] = $y;
1020 $this->in_seq
[$y] = 1;
1021 } else if (empty($this->in_seq
[$y])) {
1022 $k = $this->_lcs_pos($y);
1023 USE_ASSERTS
&& assert($k > 0);
1024 $ymids[$k] = $ymids[$k-1];
1028 wfProfileOut( "$fname-chunk" );
1031 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1032 $ymid = $ymids[$this->lcs
];
1033 for ($n = 0; $n < $nchunks - 1; $n++
) {
1034 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1035 $y1 = $ymid[$n] +
1;
1036 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1038 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1040 wfProfileOut( $fname );
1041 return array($this->lcs
, $seps);
1044 function _lcs_pos ($ypos) {
1045 $fname = '_DiffEngine::_lcs_pos';
1046 wfProfileIn( $fname );
1049 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1050 $this->seq
[++
$this->lcs
] = $ypos;
1051 $this->in_seq
[$ypos] = 1;
1052 wfProfileOut( $fname );
1057 while ($beg < $end) {
1058 $mid = (int)(($beg +
$end) / 2);
1059 if ( $ypos > $this->seq
[$mid] )
1065 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1067 $this->in_seq
[$this->seq
[$end]] = false;
1068 $this->seq
[$end] = $ypos;
1069 $this->in_seq
[$ypos] = 1;
1070 wfProfileOut( $fname );
1074 /* Find LCS of two sequences.
1076 * The results are recorded in the vectors $this->{x,y}changed[], by
1077 * storing a 1 in the element for each line that is an insertion
1078 * or deletion (ie. is not in the LCS).
1080 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1082 * Note that XLIM, YLIM are exclusive bounds.
1083 * All line numbers are origin-0 and discarded lines are not counted.
1085 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1086 $fname = '_DiffEngine::_compareseq';
1087 wfProfileIn( $fname );
1089 // Slide down the bottom initial diagonal.
1090 while ($xoff < $xlim && $yoff < $ylim
1091 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1096 // Slide up the top initial diagonal.
1097 while ($xlim > $xoff && $ylim > $yoff
1098 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1103 if ($xoff == $xlim ||
$yoff == $ylim)
1106 // This is ad hoc but seems to work well.
1107 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1108 //$nchunks = max(2,min(8,(int)$nchunks));
1109 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1111 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1115 // X and Y sequences have no common subsequence:
1116 // mark all changed.
1117 while ($yoff < $ylim)
1118 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1119 while ($xoff < $xlim)
1120 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1122 // Use the partitions to split this problem into subproblems.
1125 while ($pt2 = next($seps)) {
1126 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1130 wfProfileOut( $fname );
1133 /* Adjust inserts/deletes of identical lines to join changes
1134 * as much as possible.
1136 * We do something when a run of changed lines include a
1137 * line at one end and has an excluded, identical line at the other.
1138 * We are free to choose which identical line is included.
1139 * `compareseq' usually chooses the one at the beginning,
1140 * but usually it is cleaner to consider the following identical line
1141 * to be the "change".
1143 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1145 function _shift_boundaries ($lines, &$changed, $other_changed) {
1146 $fname = '_DiffEngine::_shift_boundaries';
1147 wfProfileIn( $fname );
1151 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1152 $len = sizeof($lines);
1153 $other_len = sizeof($other_changed);
1157 * Scan forwards to find beginning of another run of changes.
1158 * Also keep track of the corresponding point in the other file.
1160 * Throughout this code, $i and $j are adjusted together so that
1161 * the first $i elements of $changed and the first $j elements
1162 * of $other_changed both contain the same number of zeros
1163 * (unchanged lines).
1164 * Furthermore, $j is always kept so that $j == $other_len or
1165 * $other_changed[$j] == false.
1167 while ($j < $other_len && $other_changed[$j])
1170 while ($i < $len && ! $changed[$i]) {
1171 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1173 while ($j < $other_len && $other_changed[$j])
1182 // Find the end of this run of changes.
1183 while (++
$i < $len && $changed[$i])
1188 * Record the length of this run of changes, so that
1189 * we can later determine whether the run has grown.
1191 $runlength = $i - $start;
1194 * Move the changed region back, so long as the
1195 * previous unchanged line matches the last changed one.
1196 * This merges with previous changed regions.
1198 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1199 $changed[--$start] = 1;
1200 $changed[--$i] = false;
1201 while ($start > 0 && $changed[$start - 1])
1203 USE_ASSERTS
&& assert('$j > 0');
1204 while ($other_changed[--$j])
1206 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1210 * Set CORRESPONDING to the end of the changed run, at the last
1211 * point where it corresponds to a changed run in the other file.
1212 * CORRESPONDING == LEN means no such point has been found.
1214 $corresponding = $j < $other_len ?
$i : $len;
1217 * Move the changed region forward, so long as the
1218 * first changed line matches the following unchanged one.
1219 * This merges with following changed regions.
1220 * Do this second, so that if there are no merges,
1221 * the changed region is moved forward as far as possible.
1223 while ($i < $len && $lines[$start] == $lines[$i]) {
1224 $changed[$start++
] = false;
1226 while ($i < $len && $changed[$i])
1229 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1231 if ($j < $other_len && $other_changed[$j]) {
1232 $corresponding = $i;
1233 while ($j < $other_len && $other_changed[$j])
1237 } while ($runlength != $i - $start);
1240 * If possible, move the fully-merged run of changes
1241 * back to a corresponding run in the other file.
1243 while ($corresponding < $i) {
1244 $changed[--$start] = 1;
1246 USE_ASSERTS
&& assert('$j > 0');
1247 while ($other_changed[--$j])
1249 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1252 wfProfileOut( $fname );
1257 * Class representing a 'diff' between two sequences of strings.
1260 * @addtogroup DifferenceEngine
1268 * Computes diff between sequences of strings.
1270 * @param $from_lines array An array of strings.
1271 * (Typically these are lines from a file.)
1272 * @param $to_lines array An array of strings.
1274 function Diff($from_lines, $to_lines) {
1275 $eng = new _DiffEngine
;
1276 $this->edits
= $eng->diff($from_lines, $to_lines);
1277 //$this->_check($from_lines, $to_lines);
1281 * Compute reversed Diff.
1285 * $diff = new Diff($lines1, $lines2);
1286 * $rev = $diff->reverse();
1287 * @return object A Diff object representing the inverse of the
1290 function reverse () {
1292 $rev->edits
= array();
1293 foreach ($this->edits
as $edit) {
1294 $rev->edits
[] = $edit->reverse();
1300 * Check for empty diff.
1302 * @return bool True iff two sequences were identical.
1304 function isEmpty () {
1305 foreach ($this->edits
as $edit) {
1306 if ($edit->type
!= 'copy')
1313 * Compute the length of the Longest Common Subsequence (LCS).
1315 * This is mostly for diagnostic purposed.
1317 * @return int The length of the LCS.
1321 foreach ($this->edits
as $edit) {
1322 if ($edit->type
== 'copy')
1323 $lcs +
= sizeof($edit->orig
);
1329 * Get the original set of lines.
1331 * This reconstructs the $from_lines parameter passed to the
1334 * @return array The original sequence of strings.
1339 foreach ($this->edits
as $edit) {
1341 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1347 * Get the closing set of lines.
1349 * This reconstructs the $to_lines parameter passed to the
1352 * @return array The sequence of strings.
1354 function closing() {
1357 foreach ($this->edits
as $edit) {
1359 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1365 * Check a Diff for validity.
1367 * This is here only for debugging purposes.
1369 function _check ($from_lines, $to_lines) {
1370 $fname = 'Diff::_check';
1371 wfProfileIn( $fname );
1372 if (serialize($from_lines) != serialize($this->orig()))
1373 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1374 if (serialize($to_lines) != serialize($this->closing()))
1375 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1377 $rev = $this->reverse();
1378 if (serialize($to_lines) != serialize($rev->orig()))
1379 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1380 if (serialize($from_lines) != serialize($rev->closing()))
1381 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1385 foreach ($this->edits
as $edit) {
1386 if ( $prevtype == $edit->type
)
1387 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1388 $prevtype = $edit->type
;
1391 $lcs = $this->lcs();
1392 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1393 wfProfileOut( $fname );
1398 * @todo document, bad name.
1400 * @addtogroup DifferenceEngine
1402 class MappedDiff
extends Diff
1407 * Computes diff between sequences of strings.
1409 * This can be used to compute things like
1410 * case-insensitve diffs, or diffs which ignore
1411 * changes in white-space.
1413 * @param $from_lines array An array of strings.
1414 * (Typically these are lines from a file.)
1416 * @param $to_lines array An array of strings.
1418 * @param $mapped_from_lines array This array should
1419 * have the same size number of elements as $from_lines.
1420 * The elements in $mapped_from_lines and
1421 * $mapped_to_lines are what is actually compared
1422 * when computing the diff.
1424 * @param $mapped_to_lines array This array should
1425 * have the same number of elements as $to_lines.
1427 function MappedDiff($from_lines, $to_lines,
1428 $mapped_from_lines, $mapped_to_lines) {
1429 $fname = 'MappedDiff::MappedDiff';
1430 wfProfileIn( $fname );
1432 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1433 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1435 $this->Diff($mapped_from_lines, $mapped_to_lines);
1438 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1439 $orig = &$this->edits
[$i]->orig
;
1440 if (is_array($orig)) {
1441 $orig = array_slice($from_lines, $xi, sizeof($orig));
1442 $xi +
= sizeof($orig);
1445 $closing = &$this->edits
[$i]->closing
;
1446 if (is_array($closing)) {
1447 $closing = array_slice($to_lines, $yi, sizeof($closing));
1448 $yi +
= sizeof($closing);
1451 wfProfileOut( $fname );
1456 * A class to format Diffs
1458 * This class formats the diff in classic diff format.
1459 * It is intended that this class be customized via inheritance,
1460 * to obtain fancier outputs.
1463 * @addtogroup DifferenceEngine
1468 * Number of leading context "lines" to preserve.
1470 * This should be left at zero for this class, but subclasses
1471 * may want to set this to other values.
1473 var $leading_context_lines = 0;
1476 * Number of trailing context "lines" to preserve.
1478 * This should be left at zero for this class, but subclasses
1479 * may want to set this to other values.
1481 var $trailing_context_lines = 0;
1486 * @param $diff object A Diff object.
1487 * @return string The formatted output.
1489 function format($diff) {
1490 $fname = 'DiffFormatter::format';
1491 wfProfileIn( $fname );
1497 $nlead = $this->leading_context_lines
;
1498 $ntrail = $this->trailing_context_lines
;
1500 $this->_start_diff();
1502 foreach ($diff->edits
as $edit) {
1503 if ($edit->type
== 'copy') {
1504 if (is_array($block)) {
1505 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1510 $context = array_slice($edit->orig
, 0, $ntrail);
1511 $block[] = new _DiffOp_Copy($context);
1513 $this->_block($x0, $ntrail +
$xi - $x0,
1514 $y0, $ntrail +
$yi - $y0,
1519 $context = $edit->orig
;
1522 if (! is_array($block)) {
1523 $context = array_slice($context, sizeof($context) - $nlead);
1524 $x0 = $xi - sizeof($context);
1525 $y0 = $yi - sizeof($context);
1528 $block[] = new _DiffOp_Copy($context);
1534 $xi +
= sizeof($edit->orig
);
1536 $yi +
= sizeof($edit->closing
);
1539 if (is_array($block))
1540 $this->_block($x0, $xi - $x0,
1544 $end = $this->_end_diff();
1545 wfProfileOut( $fname );
1549 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1550 $fname = 'DiffFormatter::_block';
1551 wfProfileIn( $fname );
1552 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1553 foreach ($edits as $edit) {
1554 if ($edit->type
== 'copy')
1555 $this->_context($edit->orig
);
1556 elseif ($edit->type
== 'add')
1557 $this->_added($edit->closing
);
1558 elseif ($edit->type
== 'delete')
1559 $this->_deleted($edit->orig
);
1560 elseif ($edit->type
== 'change')
1561 $this->_changed($edit->orig
, $edit->closing
);
1563 trigger_error('Unknown edit type', E_USER_ERROR
);
1565 $this->_end_block();
1566 wfProfileOut( $fname );
1569 function _start_diff() {
1573 function _end_diff() {
1574 $val = ob_get_contents();
1579 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1581 $xbeg .= "," . ($xbeg +
$xlen - 1);
1583 $ybeg .= "," . ($ybeg +
$ylen - 1);
1585 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1588 function _start_block($header) {
1592 function _end_block() {
1595 function _lines($lines, $prefix = ' ') {
1596 foreach ($lines as $line)
1597 echo "$prefix $line\n";
1600 function _context($lines) {
1601 $this->_lines($lines);
1604 function _added($lines) {
1605 $this->_lines($lines, '>');
1607 function _deleted($lines) {
1608 $this->_lines($lines, '<');
1611 function _changed($orig, $closing) {
1612 $this->_deleted($orig);
1614 $this->_added($closing);
1620 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1624 define('NBSP', ' '); // iso-8859-x non-breaking space.
1629 * @addtogroup DifferenceEngine
1631 class _HWLDF_WordAccumulator
{
1632 function _HWLDF_WordAccumulator () {
1633 $this->_lines
= array();
1639 function _flushGroup ($new_tag) {
1640 if ($this->_group
!== '') {
1641 if ($this->_tag
== 'ins')
1642 $this->_line
.= '<ins class="diffchange">' .
1643 htmlspecialchars ( $this->_group
) . '</ins>';
1644 elseif ($this->_tag
== 'del')
1645 $this->_line
.= '<del class="diffchange">' .
1646 htmlspecialchars ( $this->_group
) . '</del>';
1648 $this->_line
.= htmlspecialchars ( $this->_group
);
1651 $this->_tag
= $new_tag;
1654 function _flushLine ($new_tag) {
1655 $this->_flushGroup($new_tag);
1656 if ($this->_line
!= '')
1657 array_push ( $this->_lines
, $this->_line
);
1659 # make empty lines visible by inserting an NBSP
1660 array_push ( $this->_lines
, NBSP
);
1664 function addWords ($words, $tag = '') {
1665 if ($tag != $this->_tag
)
1666 $this->_flushGroup($tag);
1668 foreach ($words as $word) {
1669 // new-line should only come as first char of word.
1672 if ($word[0] == "\n") {
1673 $this->_flushLine($tag);
1674 $word = substr($word, 1);
1676 assert(!strstr($word, "\n"));
1677 $this->_group
.= $word;
1681 function getLines() {
1682 $this->_flushLine('~done');
1683 return $this->_lines
;
1690 * @addtogroup DifferenceEngine
1692 class WordLevelDiff
extends MappedDiff
1694 const MAX_LINE_LENGTH
= 10000;
1696 function WordLevelDiff ($orig_lines, $closing_lines) {
1697 $fname = 'WordLevelDiff::WordLevelDiff';
1698 wfProfileIn( $fname );
1700 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1701 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1703 $this->MappedDiff($orig_words, $closing_words,
1704 $orig_stripped, $closing_stripped);
1705 wfProfileOut( $fname );
1708 function _split($lines) {
1709 $fname = 'WordLevelDiff::_split';
1710 wfProfileIn( $fname );
1713 $stripped = array();
1715 foreach ( $lines as $line ) {
1716 # If the line is too long, just pretend the entire line is one big word
1717 # This prevents resource exhaustion problems
1724 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1726 $stripped[] = $line;
1729 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1732 $words = array_merge( $words, $m[0] );
1733 $stripped = array_merge( $stripped, $m[1] );
1737 wfProfileOut( $fname );
1738 return array($words, $stripped);
1742 $fname = 'WordLevelDiff::orig';
1743 wfProfileIn( $fname );
1744 $orig = new _HWLDF_WordAccumulator
;
1746 foreach ($this->edits
as $edit) {
1747 if ($edit->type
== 'copy')
1748 $orig->addWords($edit->orig
);
1749 elseif ($edit->orig
)
1750 $orig->addWords($edit->orig
, 'del');
1752 $lines = $orig->getLines();
1753 wfProfileOut( $fname );
1757 function closing () {
1758 $fname = 'WordLevelDiff::closing';
1759 wfProfileIn( $fname );
1760 $closing = new _HWLDF_WordAccumulator
;
1762 foreach ($this->edits
as $edit) {
1763 if ($edit->type
== 'copy')
1764 $closing->addWords($edit->closing
);
1765 elseif ($edit->closing
)
1766 $closing->addWords($edit->closing
, 'ins');
1768 $lines = $closing->getLines();
1769 wfProfileOut( $fname );
1775 * Wikipedia Table style diff formatter.
1778 * @addtogroup DifferenceEngine
1780 class TableDiffFormatter
extends DiffFormatter
1782 function TableDiffFormatter() {
1783 $this->leading_context_lines
= 2;
1784 $this->trailing_context_lines
= 2;
1787 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1788 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1789 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1793 function _start_block( $header ) {
1797 function _end_block() {
1800 function _lines( $lines, $prefix=' ', $color='white' ) {
1803 # HTML-escape parameter before calling this
1804 function addedLine( $line ) {
1805 return $this->wrapLine( '+', 'diff-addedline', $line );
1808 # HTML-escape parameter before calling this
1809 function deletedLine( $line ) {
1810 return $this->wrapLine( '-', 'diff-deletedline', $line );
1813 # HTML-escape parameter before calling this
1814 function contextLine( $line ) {
1815 return $this->wrapLine( ' ', 'diff-context', $line );
1818 private function wrapLine( $marker, $class, $line ) {
1819 if( $line !== '' ) {
1820 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1821 $line = "<div>$line</div>";
1823 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1826 function emptyLine() {
1827 return '<td colspan="2"> </td>';
1830 function _added( $lines ) {
1831 foreach ($lines as $line) {
1832 echo '<tr>' . $this->emptyLine() .
1833 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1837 function _deleted($lines) {
1838 foreach ($lines as $line) {
1839 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1840 $this->emptyLine() . "</tr>\n";
1844 function _context( $lines ) {
1845 foreach ($lines as $line) {
1847 $this->contextLine( htmlspecialchars ( $line ) ) .
1848 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1852 function _changed( $orig, $closing ) {
1853 $fname = 'TableDiffFormatter::_changed';
1854 wfProfileIn( $fname );
1856 $diff = new WordLevelDiff( $orig, $closing );
1857 $del = $diff->orig();
1858 $add = $diff->closing();
1860 # Notice that WordLevelDiff returns HTML-escaped output.
1861 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1863 while ( $line = array_shift( $del ) ) {
1864 $aline = array_shift( $add );
1865 echo '<tr>' . $this->deletedLine( $line ) .
1866 $this->addedLine( $aline ) . "</tr>\n";
1868 foreach ($add as $line) { # If any leftovers
1869 echo '<tr>' . $this->emptyLine() .
1870 $this->addedLine( $line ) . "</tr>\n";
1872 wfProfileOut( $fname );