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 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
265 // Stolen from Article::view --AG 2007-10-11
267 // Give hooks a chance to customise the output
268 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
269 // Wrap the whole lot in a <pre> and don't parse
271 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
272 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
273 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
274 $wgOut->addHtml( "\n</pre>\n" );
277 $wgOut->addWikiTextTidy( $this->mNewtext
);
279 if( !$this->mNewRev
->isCurrent() ) {
280 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
283 wfProfileOut( $fname );
287 * Show the first revision of an article. Uses normal diff headers in
288 * contrast to normal "old revision" display style.
290 function showFirstRevision() {
291 global $wgOut, $wgUser;
293 $fname = 'DifferenceEngine::showFirstRevision';
294 wfProfileIn( $fname );
296 # Get article text from the DB
298 if ( ! $this->loadNewText() ) {
299 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
301 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
302 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
303 $wgOut->addWikitext( $mtext );
304 wfProfileOut( $fname );
307 if ( $this->mNewRev
->isCurrent() ) {
308 $wgOut->setArticleFlag( true );
311 # Check if user is allowed to look at this page. If not, bail out.
313 if ( !( $this->mTitle
->userCanRead() ) ) {
314 $wgOut->loginToUse();
316 wfProfileOut( $fname );
320 # Prepare the header box
322 $sk = $wgUser->getSkin();
324 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
325 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
326 $sk->revUserTools( $this->mNewRev
) . "<br />" .
327 $sk->revComment( $this->mNewRev
) . "<br />" .
328 $nextlink . "</div>\n";
330 $wgOut->addHTML( $header );
332 $wgOut->setSubtitle( wfMsg( 'difference' ) );
333 $wgOut->setRobotpolicy( 'noindex,nofollow' );
335 wfProfileOut( $fname );
339 * Get the diff text, send it to $wgOut
340 * Returns false if the diff could not be generated, otherwise returns true
342 function showDiff( $otitle, $ntitle ) {
344 $diff = $this->getDiff( $otitle, $ntitle );
345 if ( $diff === false ) {
346 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
349 $this->showDiffStyle();
350 $wgOut->addHTML( $diff );
356 * Add style sheets and supporting JS for diff display.
358 function showDiffStyle() {
359 global $wgStylePath, $wgStyleVersion, $wgOut;
360 $wgOut->addStyle( 'common/diff.css' );
362 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
363 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
367 * Get complete diff table, including header
369 * @param Title $otitle Old title
370 * @param Title $ntitle New title
373 function getDiff( $otitle, $ntitle ) {
374 $body = $this->getDiffBody();
375 if ( $body === false ) {
378 $multi = $this->getMultiNotice();
379 return $this->addHeader( $body, $otitle, $ntitle, $multi );
384 * Get the diff table body, without header
388 function getDiffBody() {
390 $fname = 'DifferenceEngine::getDiffBody';
391 wfProfileIn( $fname );
395 if ( $this->mOldid
&& $this->mNewid
) {
396 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
398 if ( !$this->mRefreshCache
) {
399 $difftext = $wgMemc->get( $key );
401 wfIncrStats( 'diff_cache_hit' );
402 $difftext = $this->localiseLineNumbers( $difftext );
403 $difftext .= "\n<!-- diff cache key $key -->\n";
404 wfProfileOut( $fname );
407 } // don't try to load but save the result
410 #loadtext is permission safe, this just clears out the diff
411 if ( !$this->loadText() ) {
412 wfProfileOut( $fname );
414 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
416 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
420 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
422 // Save to cache for 7 days
423 if ( $key !== false && $difftext !== false ) {
424 wfIncrStats( 'diff_cache_miss' );
425 $wgMemc->set( $key, $difftext, 7*86400 );
427 wfIncrStats( 'diff_uncacheable' );
429 // Replace line numbers with the text in the user's language
430 if ( $difftext !== false ) {
431 $difftext = $this->localiseLineNumbers( $difftext );
433 wfProfileOut( $fname );
438 * Generate a diff, no caching
439 * $otext and $ntext must be already segmented
441 function generateDiffBody( $otext, $ntext ) {
442 global $wgExternalDiffEngine, $wgContLang;
443 $fname = 'DifferenceEngine::generateDiffBody';
445 $otext = str_replace( "\r\n", "\n", $otext );
446 $ntext = str_replace( "\r\n", "\n", $ntext );
448 if ( $wgExternalDiffEngine == 'wikidiff' ) {
449 # For historical reasons, external diff engine expects
450 # input text to be HTML-escaped already
451 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
452 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
453 if( !function_exists( 'wikidiff_do_diff' ) ) {
454 dl('php_wikidiff.so');
456 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
459 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
460 # Better external diff engine, the 2 may some day be dropped
461 # This one does the escaping and segmenting itself
462 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
463 wfProfileIn( "$fname-dl" );
464 @dl
('php_wikidiff2.so');
465 wfProfileOut( "$fname-dl" );
467 if ( function_exists( 'wikidiff2_do_diff' ) ) {
468 wfProfileIn( 'wikidiff2_do_diff' );
469 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
470 wfProfileOut( 'wikidiff2_do_diff' );
474 if ( $wgExternalDiffEngine !== false ) {
476 global $wgTmpDirectory;
477 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
478 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
480 $tempFile1 = fopen( $tempName1, "w" );
482 wfProfileOut( $fname );
485 $tempFile2 = fopen( $tempName2, "w" );
487 wfProfileOut( $fname );
490 fwrite( $tempFile1, $otext );
491 fwrite( $tempFile2, $ntext );
492 fclose( $tempFile1 );
493 fclose( $tempFile2 );
494 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
495 wfProfileIn( "$fname-shellexec" );
496 $difftext = wfShellExec( $cmd );
497 wfProfileOut( "$fname-shellexec" );
498 unlink( $tempName1 );
499 unlink( $tempName2 );
504 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
505 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
506 $diffs = new Diff( $ota, $nta );
507 $formatter = new TableDiffFormatter();
508 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
513 * Replace line numbers with the text in the user's language
515 function localiseLineNumbers( $text ) {
516 return preg_replace_callback( '/<!--LINE (\d+)-->/',
517 array( &$this, 'localiseLineNumbersCb' ), $text );
520 function localiseLineNumbersCb( $matches ) {
522 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
527 * If there are revisions between the ones being compared, return a note saying so.
529 function getMultiNotice() {
530 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
533 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
534 // Comparing two different pages? Count would be meaningless.
538 $oldid = $this->mOldRev
->getId();
539 $newid = $this->mNewRev
->getId();
540 if ( $oldid > $newid ) {
541 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
544 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
548 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
553 * Add the header to a diff body
555 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
558 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
559 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
561 if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
562 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
566 <col class='diff-marker' />
567 <col class='diff-content' />
568 <col class='diff-marker' />
569 <col class='diff-content' />
571 <td colspan='2' class='diff-otitle'>{$otitle}</td>
572 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
577 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
579 return $header . $diff . "</table>";
583 * Use specified text instead of loading from the database
585 function setText( $oldText, $newText ) {
586 $this->mOldtext
= $oldText;
587 $this->mNewtext
= $newText;
588 $this->mTextLoaded
= 2;
592 * Load revision metadata for the specified articles. If newid is 0, then compare
593 * the old article in oldid to the current article; if oldid is 0, then
594 * compare the current article to the immediately previous one (ignoring the
597 * If oldid is false, leave the corresponding revision object set
598 * to false. This is impossible via ordinary user input, and is provided for
601 function loadRevisionData() {
603 if ( $this->mRevisionsLoaded
) {
606 // Whether it succeeds or fails, we don't want to try again
607 $this->mRevisionsLoaded
= true;
610 // Load the new revision object
611 $this->mNewRev
= $this->mNewid
612 ? Revision
::newFromId( $this->mNewid
)
613 : Revision
::newFromTitle( $this->mTitle
);
614 if( !$this->mNewRev
instanceof Revision
)
617 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
618 $this->mNewid
= $this->mNewRev
->getId();
620 // Set assorted variables
621 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
622 $this->mNewPage
= $this->mNewRev
->getTitle();
623 if( $this->mNewRev
->isCurrent() ) {
624 $newLink = $this->mNewPage
->escapeLocalUrl();
625 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
626 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
628 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
629 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
632 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
633 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
634 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
636 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
637 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
640 // Load the old revision object
641 $this->mOldRev
= false;
642 if( $this->mOldid
) {
643 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
644 } elseif ( $this->mOldid
=== 0 ) {
645 $rev = $this->mNewRev
->getPrevious();
647 $this->mOldid
= $rev->getId();
648 $this->mOldRev
= $rev;
650 // No previous revision; mark to show as first-version only.
651 $this->mOldid
= false;
652 $this->mOldRev
= false;
654 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
656 if( is_null( $this->mOldRev
) ) {
660 if ( $this->mOldRev
) {
661 $this->mOldPage
= $this->mOldRev
->getTitle();
663 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
664 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
665 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
666 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
667 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
669 // Add an "undo" link
670 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
671 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
678 * Load the text of the revisions, as well as revision data.
680 function loadText() {
681 if ( $this->mTextLoaded
== 2 ) {
684 // Whether it succeeds or fails, we don't want to try again
685 $this->mTextLoaded
= 2;
688 if ( !$this->loadRevisionData() ) {
691 if ( $this->mOldRev
) {
692 // FIXME: permission tests
693 $this->mOldtext
= $this->mOldRev
->revText();
694 if ( $this->mOldtext
=== false ) {
698 if ( $this->mNewRev
) {
699 $this->mNewtext
= $this->mNewRev
->revText();
700 if ( $this->mNewtext
=== false ) {
708 * Load the text of the new revision, not the old one
710 function loadNewText() {
711 if ( $this->mTextLoaded
>= 1 ) {
714 $this->mTextLoaded
= 1;
716 if ( !$this->loadRevisionData() ) {
719 $this->mNewtext
= $this->mNewRev
->getText();
726 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
728 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
729 // You may copy this code freely under the conditions of the GPL.
732 define('USE_ASSERTS', function_exists('assert'));
737 * @addtogroup DifferenceEngine
745 trigger_error('pure virtual', E_USER_ERROR
);
749 return $this->orig ?
sizeof($this->orig
) : 0;
752 function nclosing() {
753 return $this->closing ?
sizeof($this->closing
) : 0;
760 * @addtogroup DifferenceEngine
762 class _DiffOp_Copy
extends _DiffOp
{
765 function _DiffOp_Copy ($orig, $closing = false) {
766 if (!is_array($closing))
769 $this->closing
= $closing;
773 return new _DiffOp_Copy($this->closing
, $this->orig
);
780 * @addtogroup DifferenceEngine
782 class _DiffOp_Delete
extends _DiffOp
{
783 var $type = 'delete';
785 function _DiffOp_Delete ($lines) {
786 $this->orig
= $lines;
787 $this->closing
= false;
791 return new _DiffOp_Add($this->orig
);
798 * @addtogroup DifferenceEngine
800 class _DiffOp_Add
extends _DiffOp
{
803 function _DiffOp_Add ($lines) {
804 $this->closing
= $lines;
809 return new _DiffOp_Delete($this->closing
);
816 * @addtogroup DifferenceEngine
818 class _DiffOp_Change
extends _DiffOp
{
819 var $type = 'change';
821 function _DiffOp_Change ($orig, $closing) {
823 $this->closing
= $closing;
827 return new _DiffOp_Change($this->closing
, $this->orig
);
833 * Class used internally by Diff to actually compute the diffs.
835 * The algorithm used here is mostly lifted from the perl module
836 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
837 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
839 * More ideas are taken from:
840 * http://www.ics.uci.edu/~eppstein/161/960229.html
842 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
843 * diffutils-2.7, which can be found at:
844 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
846 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
849 * Line length limits for robustness added by Tim Starling, 2005-08-31
851 * @author Geoffrey T. Dairiki, Tim Starling
853 * @addtogroup DifferenceEngine
857 const MAX_XREF_LENGTH
= 10000;
859 function diff ($from_lines, $to_lines) {
860 $fname = '_DiffEngine::diff';
861 wfProfileIn( $fname );
863 $n_from = sizeof($from_lines);
864 $n_to = sizeof($to_lines);
866 $this->xchanged
= $this->ychanged
= array();
867 $this->xv
= $this->yv
= array();
868 $this->xind
= $this->yind
= array();
870 unset($this->in_seq
);
873 // Skip leading common lines.
874 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
875 if ($from_lines[$skip] !== $to_lines[$skip])
877 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
879 // Skip trailing common lines.
880 $xi = $n_from; $yi = $n_to;
881 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
882 if ($from_lines[$xi] !== $to_lines[$yi])
884 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
887 // Ignore lines which do not exist in both files.
888 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
889 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
892 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
893 $line = $to_lines[$yi];
894 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
896 $yhash[$this->_line_hash($line)] = 1;
900 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
901 $line = $from_lines[$xi];
902 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
909 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
911 // Merge edits when possible
912 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
913 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
915 // Compute the edit operations.
918 while ($xi < $n_from ||
$yi < $n_to) {
919 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
920 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
922 // Skip matching "snake".
924 while ( $xi < $n_from && $yi < $n_to
925 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
926 $copy[] = $from_lines[$xi++
];
930 $edits[] = new _DiffOp_Copy($copy);
932 // Find deletes & adds.
934 while ($xi < $n_from && $this->xchanged
[$xi])
935 $delete[] = $from_lines[$xi++
];
938 while ($yi < $n_to && $this->ychanged
[$yi])
939 $add[] = $to_lines[$yi++
];
942 $edits[] = new _DiffOp_Change($delete, $add);
944 $edits[] = new _DiffOp_Delete($delete);
946 $edits[] = new _DiffOp_Add($add);
948 wfProfileOut( $fname );
953 * Returns the whole line if it's small enough, or the MD5 hash otherwise
955 function _line_hash( $line ) {
956 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
964 /* Divide the Largest Common Subsequence (LCS) of the sequences
965 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
968 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
969 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
970 * sub sequences. The first sub-sequence is contained in [X0, X1),
971 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
972 * that (X0, Y0) == (XOFF, YOFF) and
973 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
975 * This function assumes that the first lines of the specified portions
976 * of the two files do not match, and likewise that the last lines do not
977 * match. The caller must trim matching lines from the beginning and end
978 * of the portions it is going to specify.
980 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
981 $fname = '_DiffEngine::_diag';
982 wfProfileIn( $fname );
985 if ($xlim - $xoff > $ylim - $yoff) {
986 // Things seems faster (I'm not sure I understand why)
987 // when the shortest sequence in X.
989 list ($xoff, $xlim, $yoff, $ylim)
990 = array( $yoff, $ylim, $xoff, $xlim);
994 for ($i = $ylim - 1; $i >= $yoff; $i--)
995 $ymatches[$this->xv
[$i]][] = $i;
997 for ($i = $ylim - 1; $i >= $yoff; $i--)
998 $ymatches[$this->yv
[$i]][] = $i;
1001 $this->seq
[0]= $yoff - 1;
1002 $this->in_seq
= array();
1003 $ymids[0] = array();
1005 $numer = $xlim - $xoff +
$nchunks - 1;
1007 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1008 wfProfileIn( "$fname-chunk" );
1010 for ($i = 0; $i <= $this->lcs
; $i++
)
1011 $ymids[$i][$chunk-1] = $this->seq
[$i];
1013 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1014 for ( ; $x < $x1; $x++
) {
1015 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1016 if (empty($ymatches[$line]))
1018 $matches = $ymatches[$line];
1020 while (list ($junk, $y) = each($matches))
1021 if (empty($this->in_seq
[$y])) {
1022 $k = $this->_lcs_pos($y);
1023 USE_ASSERTS
&& assert($k > 0);
1024 $ymids[$k] = $ymids[$k-1];
1027 while (list ( /* $junk */, $y) = each($matches)) {
1028 if ($y > $this->seq
[$k-1]) {
1029 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1030 // Optimization: this is a common case:
1031 // next match is just replacing previous match.
1032 $this->in_seq
[$this->seq
[$k]] = false;
1033 $this->seq
[$k] = $y;
1034 $this->in_seq
[$y] = 1;
1035 } else if (empty($this->in_seq
[$y])) {
1036 $k = $this->_lcs_pos($y);
1037 USE_ASSERTS
&& assert($k > 0);
1038 $ymids[$k] = $ymids[$k-1];
1042 wfProfileOut( "$fname-chunk" );
1045 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1046 $ymid = $ymids[$this->lcs
];
1047 for ($n = 0; $n < $nchunks - 1; $n++
) {
1048 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1049 $y1 = $ymid[$n] +
1;
1050 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1052 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1054 wfProfileOut( $fname );
1055 return array($this->lcs
, $seps);
1058 function _lcs_pos ($ypos) {
1059 $fname = '_DiffEngine::_lcs_pos';
1060 wfProfileIn( $fname );
1063 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1064 $this->seq
[++
$this->lcs
] = $ypos;
1065 $this->in_seq
[$ypos] = 1;
1066 wfProfileOut( $fname );
1071 while ($beg < $end) {
1072 $mid = (int)(($beg +
$end) / 2);
1073 if ( $ypos > $this->seq
[$mid] )
1079 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1081 $this->in_seq
[$this->seq
[$end]] = false;
1082 $this->seq
[$end] = $ypos;
1083 $this->in_seq
[$ypos] = 1;
1084 wfProfileOut( $fname );
1088 /* Find LCS of two sequences.
1090 * The results are recorded in the vectors $this->{x,y}changed[], by
1091 * storing a 1 in the element for each line that is an insertion
1092 * or deletion (ie. is not in the LCS).
1094 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1096 * Note that XLIM, YLIM are exclusive bounds.
1097 * All line numbers are origin-0 and discarded lines are not counted.
1099 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1100 $fname = '_DiffEngine::_compareseq';
1101 wfProfileIn( $fname );
1103 // Slide down the bottom initial diagonal.
1104 while ($xoff < $xlim && $yoff < $ylim
1105 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1110 // Slide up the top initial diagonal.
1111 while ($xlim > $xoff && $ylim > $yoff
1112 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1117 if ($xoff == $xlim ||
$yoff == $ylim)
1120 // This is ad hoc but seems to work well.
1121 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1122 //$nchunks = max(2,min(8,(int)$nchunks));
1123 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1125 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1129 // X and Y sequences have no common subsequence:
1130 // mark all changed.
1131 while ($yoff < $ylim)
1132 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1133 while ($xoff < $xlim)
1134 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1136 // Use the partitions to split this problem into subproblems.
1139 while ($pt2 = next($seps)) {
1140 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1144 wfProfileOut( $fname );
1147 /* Adjust inserts/deletes of identical lines to join changes
1148 * as much as possible.
1150 * We do something when a run of changed lines include a
1151 * line at one end and has an excluded, identical line at the other.
1152 * We are free to choose which identical line is included.
1153 * `compareseq' usually chooses the one at the beginning,
1154 * but usually it is cleaner to consider the following identical line
1155 * to be the "change".
1157 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1159 function _shift_boundaries ($lines, &$changed, $other_changed) {
1160 $fname = '_DiffEngine::_shift_boundaries';
1161 wfProfileIn( $fname );
1165 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1166 $len = sizeof($lines);
1167 $other_len = sizeof($other_changed);
1171 * Scan forwards to find beginning of another run of changes.
1172 * Also keep track of the corresponding point in the other file.
1174 * Throughout this code, $i and $j are adjusted together so that
1175 * the first $i elements of $changed and the first $j elements
1176 * of $other_changed both contain the same number of zeros
1177 * (unchanged lines).
1178 * Furthermore, $j is always kept so that $j == $other_len or
1179 * $other_changed[$j] == false.
1181 while ($j < $other_len && $other_changed[$j])
1184 while ($i < $len && ! $changed[$i]) {
1185 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1187 while ($j < $other_len && $other_changed[$j])
1196 // Find the end of this run of changes.
1197 while (++
$i < $len && $changed[$i])
1202 * Record the length of this run of changes, so that
1203 * we can later determine whether the run has grown.
1205 $runlength = $i - $start;
1208 * Move the changed region back, so long as the
1209 * previous unchanged line matches the last changed one.
1210 * This merges with previous changed regions.
1212 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1213 $changed[--$start] = 1;
1214 $changed[--$i] = false;
1215 while ($start > 0 && $changed[$start - 1])
1217 USE_ASSERTS
&& assert('$j > 0');
1218 while ($other_changed[--$j])
1220 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1224 * Set CORRESPONDING to the end of the changed run, at the last
1225 * point where it corresponds to a changed run in the other file.
1226 * CORRESPONDING == LEN means no such point has been found.
1228 $corresponding = $j < $other_len ?
$i : $len;
1231 * Move the changed region forward, so long as the
1232 * first changed line matches the following unchanged one.
1233 * This merges with following changed regions.
1234 * Do this second, so that if there are no merges,
1235 * the changed region is moved forward as far as possible.
1237 while ($i < $len && $lines[$start] == $lines[$i]) {
1238 $changed[$start++
] = false;
1240 while ($i < $len && $changed[$i])
1243 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1245 if ($j < $other_len && $other_changed[$j]) {
1246 $corresponding = $i;
1247 while ($j < $other_len && $other_changed[$j])
1251 } while ($runlength != $i - $start);
1254 * If possible, move the fully-merged run of changes
1255 * back to a corresponding run in the other file.
1257 while ($corresponding < $i) {
1258 $changed[--$start] = 1;
1260 USE_ASSERTS
&& assert('$j > 0');
1261 while ($other_changed[--$j])
1263 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1266 wfProfileOut( $fname );
1271 * Class representing a 'diff' between two sequences of strings.
1274 * @addtogroup DifferenceEngine
1282 * Computes diff between sequences of strings.
1284 * @param $from_lines array An array of strings.
1285 * (Typically these are lines from a file.)
1286 * @param $to_lines array An array of strings.
1288 function Diff($from_lines, $to_lines) {
1289 $eng = new _DiffEngine
;
1290 $this->edits
= $eng->diff($from_lines, $to_lines);
1291 //$this->_check($from_lines, $to_lines);
1295 * Compute reversed Diff.
1299 * $diff = new Diff($lines1, $lines2);
1300 * $rev = $diff->reverse();
1301 * @return object A Diff object representing the inverse of the
1304 function reverse () {
1306 $rev->edits
= array();
1307 foreach ($this->edits
as $edit) {
1308 $rev->edits
[] = $edit->reverse();
1314 * Check for empty diff.
1316 * @return bool True iff two sequences were identical.
1318 function isEmpty () {
1319 foreach ($this->edits
as $edit) {
1320 if ($edit->type
!= 'copy')
1327 * Compute the length of the Longest Common Subsequence (LCS).
1329 * This is mostly for diagnostic purposed.
1331 * @return int The length of the LCS.
1335 foreach ($this->edits
as $edit) {
1336 if ($edit->type
== 'copy')
1337 $lcs +
= sizeof($edit->orig
);
1343 * Get the original set of lines.
1345 * This reconstructs the $from_lines parameter passed to the
1348 * @return array The original sequence of strings.
1353 foreach ($this->edits
as $edit) {
1355 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1361 * Get the closing set of lines.
1363 * This reconstructs the $to_lines parameter passed to the
1366 * @return array The sequence of strings.
1368 function closing() {
1371 foreach ($this->edits
as $edit) {
1373 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1379 * Check a Diff for validity.
1381 * This is here only for debugging purposes.
1383 function _check ($from_lines, $to_lines) {
1384 $fname = 'Diff::_check';
1385 wfProfileIn( $fname );
1386 if (serialize($from_lines) != serialize($this->orig()))
1387 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1388 if (serialize($to_lines) != serialize($this->closing()))
1389 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1391 $rev = $this->reverse();
1392 if (serialize($to_lines) != serialize($rev->orig()))
1393 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1394 if (serialize($from_lines) != serialize($rev->closing()))
1395 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1399 foreach ($this->edits
as $edit) {
1400 if ( $prevtype == $edit->type
)
1401 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1402 $prevtype = $edit->type
;
1405 $lcs = $this->lcs();
1406 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1407 wfProfileOut( $fname );
1412 * @todo document, bad name.
1414 * @addtogroup DifferenceEngine
1416 class MappedDiff
extends Diff
1421 * Computes diff between sequences of strings.
1423 * This can be used to compute things like
1424 * case-insensitve diffs, or diffs which ignore
1425 * changes in white-space.
1427 * @param $from_lines array An array of strings.
1428 * (Typically these are lines from a file.)
1430 * @param $to_lines array An array of strings.
1432 * @param $mapped_from_lines array This array should
1433 * have the same size number of elements as $from_lines.
1434 * The elements in $mapped_from_lines and
1435 * $mapped_to_lines are what is actually compared
1436 * when computing the diff.
1438 * @param $mapped_to_lines array This array should
1439 * have the same number of elements as $to_lines.
1441 function MappedDiff($from_lines, $to_lines,
1442 $mapped_from_lines, $mapped_to_lines) {
1443 $fname = 'MappedDiff::MappedDiff';
1444 wfProfileIn( $fname );
1446 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1447 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1449 $this->Diff($mapped_from_lines, $mapped_to_lines);
1452 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1453 $orig = &$this->edits
[$i]->orig
;
1454 if (is_array($orig)) {
1455 $orig = array_slice($from_lines, $xi, sizeof($orig));
1456 $xi +
= sizeof($orig);
1459 $closing = &$this->edits
[$i]->closing
;
1460 if (is_array($closing)) {
1461 $closing = array_slice($to_lines, $yi, sizeof($closing));
1462 $yi +
= sizeof($closing);
1465 wfProfileOut( $fname );
1470 * A class to format Diffs
1472 * This class formats the diff in classic diff format.
1473 * It is intended that this class be customized via inheritance,
1474 * to obtain fancier outputs.
1477 * @addtogroup DifferenceEngine
1482 * Number of leading context "lines" to preserve.
1484 * This should be left at zero for this class, but subclasses
1485 * may want to set this to other values.
1487 var $leading_context_lines = 0;
1490 * Number of trailing context "lines" to preserve.
1492 * This should be left at zero for this class, but subclasses
1493 * may want to set this to other values.
1495 var $trailing_context_lines = 0;
1500 * @param $diff object A Diff object.
1501 * @return string The formatted output.
1503 function format($diff) {
1504 $fname = 'DiffFormatter::format';
1505 wfProfileIn( $fname );
1511 $nlead = $this->leading_context_lines
;
1512 $ntrail = $this->trailing_context_lines
;
1514 $this->_start_diff();
1516 foreach ($diff->edits
as $edit) {
1517 if ($edit->type
== 'copy') {
1518 if (is_array($block)) {
1519 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1524 $context = array_slice($edit->orig
, 0, $ntrail);
1525 $block[] = new _DiffOp_Copy($context);
1527 $this->_block($x0, $ntrail +
$xi - $x0,
1528 $y0, $ntrail +
$yi - $y0,
1533 $context = $edit->orig
;
1536 if (! is_array($block)) {
1537 $context = array_slice($context, sizeof($context) - $nlead);
1538 $x0 = $xi - sizeof($context);
1539 $y0 = $yi - sizeof($context);
1542 $block[] = new _DiffOp_Copy($context);
1548 $xi +
= sizeof($edit->orig
);
1550 $yi +
= sizeof($edit->closing
);
1553 if (is_array($block))
1554 $this->_block($x0, $xi - $x0,
1558 $end = $this->_end_diff();
1559 wfProfileOut( $fname );
1563 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1564 $fname = 'DiffFormatter::_block';
1565 wfProfileIn( $fname );
1566 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1567 foreach ($edits as $edit) {
1568 if ($edit->type
== 'copy')
1569 $this->_context($edit->orig
);
1570 elseif ($edit->type
== 'add')
1571 $this->_added($edit->closing
);
1572 elseif ($edit->type
== 'delete')
1573 $this->_deleted($edit->orig
);
1574 elseif ($edit->type
== 'change')
1575 $this->_changed($edit->orig
, $edit->closing
);
1577 trigger_error('Unknown edit type', E_USER_ERROR
);
1579 $this->_end_block();
1580 wfProfileOut( $fname );
1583 function _start_diff() {
1587 function _end_diff() {
1588 $val = ob_get_contents();
1593 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1595 $xbeg .= "," . ($xbeg +
$xlen - 1);
1597 $ybeg .= "," . ($ybeg +
$ylen - 1);
1599 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1602 function _start_block($header) {
1606 function _end_block() {
1609 function _lines($lines, $prefix = ' ') {
1610 foreach ($lines as $line)
1611 echo "$prefix $line\n";
1614 function _context($lines) {
1615 $this->_lines($lines);
1618 function _added($lines) {
1619 $this->_lines($lines, '>');
1621 function _deleted($lines) {
1622 $this->_lines($lines, '<');
1625 function _changed($orig, $closing) {
1626 $this->_deleted($orig);
1628 $this->_added($closing);
1634 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1638 define('NBSP', ' '); // iso-8859-x non-breaking space.
1643 * @addtogroup DifferenceEngine
1645 class _HWLDF_WordAccumulator
{
1646 function _HWLDF_WordAccumulator () {
1647 $this->_lines
= array();
1653 function _flushGroup ($new_tag) {
1654 if ($this->_group
!== '') {
1655 if ($this->_tag
== 'ins')
1656 $this->_line
.= '<ins class="diffchange">' .
1657 htmlspecialchars ( $this->_group
) . '</ins>';
1658 elseif ($this->_tag
== 'del')
1659 $this->_line
.= '<del class="diffchange">' .
1660 htmlspecialchars ( $this->_group
) . '</del>';
1662 $this->_line
.= htmlspecialchars ( $this->_group
);
1665 $this->_tag
= $new_tag;
1668 function _flushLine ($new_tag) {
1669 $this->_flushGroup($new_tag);
1670 if ($this->_line
!= '')
1671 array_push ( $this->_lines
, $this->_line
);
1673 # make empty lines visible by inserting an NBSP
1674 array_push ( $this->_lines
, NBSP
);
1678 function addWords ($words, $tag = '') {
1679 if ($tag != $this->_tag
)
1680 $this->_flushGroup($tag);
1682 foreach ($words as $word) {
1683 // new-line should only come as first char of word.
1686 if ($word[0] == "\n") {
1687 $this->_flushLine($tag);
1688 $word = substr($word, 1);
1690 assert(!strstr($word, "\n"));
1691 $this->_group
.= $word;
1695 function getLines() {
1696 $this->_flushLine('~done');
1697 return $this->_lines
;
1704 * @addtogroup DifferenceEngine
1706 class WordLevelDiff
extends MappedDiff
1708 const MAX_LINE_LENGTH
= 10000;
1710 function WordLevelDiff ($orig_lines, $closing_lines) {
1711 $fname = 'WordLevelDiff::WordLevelDiff';
1712 wfProfileIn( $fname );
1714 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1715 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1717 $this->MappedDiff($orig_words, $closing_words,
1718 $orig_stripped, $closing_stripped);
1719 wfProfileOut( $fname );
1722 function _split($lines) {
1723 $fname = 'WordLevelDiff::_split';
1724 wfProfileIn( $fname );
1727 $stripped = array();
1729 foreach ( $lines as $line ) {
1730 # If the line is too long, just pretend the entire line is one big word
1731 # This prevents resource exhaustion problems
1738 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1740 $stripped[] = $line;
1743 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1746 $words = array_merge( $words, $m[0] );
1747 $stripped = array_merge( $stripped, $m[1] );
1751 wfProfileOut( $fname );
1752 return array($words, $stripped);
1756 $fname = 'WordLevelDiff::orig';
1757 wfProfileIn( $fname );
1758 $orig = new _HWLDF_WordAccumulator
;
1760 foreach ($this->edits
as $edit) {
1761 if ($edit->type
== 'copy')
1762 $orig->addWords($edit->orig
);
1763 elseif ($edit->orig
)
1764 $orig->addWords($edit->orig
, 'del');
1766 $lines = $orig->getLines();
1767 wfProfileOut( $fname );
1771 function closing () {
1772 $fname = 'WordLevelDiff::closing';
1773 wfProfileIn( $fname );
1774 $closing = new _HWLDF_WordAccumulator
;
1776 foreach ($this->edits
as $edit) {
1777 if ($edit->type
== 'copy')
1778 $closing->addWords($edit->closing
);
1779 elseif ($edit->closing
)
1780 $closing->addWords($edit->closing
, 'ins');
1782 $lines = $closing->getLines();
1783 wfProfileOut( $fname );
1789 * Wikipedia Table style diff formatter.
1792 * @addtogroup DifferenceEngine
1794 class TableDiffFormatter
extends DiffFormatter
1796 function TableDiffFormatter() {
1797 $this->leading_context_lines
= 2;
1798 $this->trailing_context_lines
= 2;
1801 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1802 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1803 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1807 function _start_block( $header ) {
1811 function _end_block() {
1814 function _lines( $lines, $prefix=' ', $color='white' ) {
1817 # HTML-escape parameter before calling this
1818 function addedLine( $line ) {
1819 return $this->wrapLine( '+', 'diff-addedline', $line );
1822 # HTML-escape parameter before calling this
1823 function deletedLine( $line ) {
1824 return $this->wrapLine( '-', 'diff-deletedline', $line );
1827 # HTML-escape parameter before calling this
1828 function contextLine( $line ) {
1829 return $this->wrapLine( ' ', 'diff-context', $line );
1832 private function wrapLine( $marker, $class, $line ) {
1833 if( $line !== '' ) {
1834 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1835 $line = "<div>$line</div>";
1837 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1840 function emptyLine() {
1841 return '<td colspan="2"> </td>';
1844 function _added( $lines ) {
1845 foreach ($lines as $line) {
1846 echo '<tr>' . $this->emptyLine() .
1847 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1851 function _deleted($lines) {
1852 foreach ($lines as $line) {
1853 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1854 $this->emptyLine() . "</tr>\n";
1858 function _context( $lines ) {
1859 foreach ($lines as $line) {
1861 $this->contextLine( htmlspecialchars ( $line ) ) .
1862 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1866 function _changed( $orig, $closing ) {
1867 $fname = 'TableDiffFormatter::_changed';
1868 wfProfileIn( $fname );
1870 $diff = new WordLevelDiff( $orig, $closing );
1871 $del = $diff->orig();
1872 $add = $diff->closing();
1874 # Notice that WordLevelDiff returns HTML-escaped output.
1875 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1877 while ( $line = array_shift( $del ) ) {
1878 $aline = array_shift( $add );
1879 echo '<tr>' . $this->deletedLine( $line ) .
1880 $this->addedLine( $aline ) . "</tr>\n";
1882 foreach ($add as $line) { # If any leftovers
1883 echo '<tr>' . $this->emptyLine() .
1884 $this->addedLine( $line ) . "</tr>\n";
1886 wfProfileOut( $fname );