3f41d1677c384aab56bf3da880c07a99f51af05e
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 __construct( $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 wfProfileIn( __METHOD__
);
79 # If external diffs are enabled both globally and for the user,
80 # we'll use the application/x-external-editor interface to call
81 # an external diff tool like kompare, kdiff3, etc.
82 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
83 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
85 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
86 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
87 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
88 $special=$wgLang->getNsText(NS_SPECIAL
);
93 Script={$wgServer}{$wgScript}
94 Special namespace={$special}
108 $wgOut->setArticleFlag( false );
109 if ( ! $this->loadRevisionData() ) {
110 $t = $this->mTitle
->getPrefixedText() . ' ' . wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
111 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
112 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
113 wfProfileOut( __METHOD__
);
117 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
119 if ( $this->mNewRev
->isCurrent() ) {
120 $wgOut->setArticleFlag( true );
123 # mOldid is false if the difference engine is called with a "vague" query for
124 # a diff between a version V and its previous version V' AND the version V
125 # is the first version of that article. In that case, V' does not exist.
126 if ( $this->mOldid
=== false ) {
127 $this->showFirstRevision();
128 $this->renderNewRevision(); // should we respect $diffOnly here or not?
129 wfProfileOut( __METHOD__
);
133 $wgOut->suppressQuickbar();
135 $oldTitle = $this->mOldPage
->getPrefixedText();
136 $newTitle = $this->mNewPage
->getPrefixedText();
137 if( $oldTitle == $newTitle ) {
138 $wgOut->setPageTitle( $newTitle );
140 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
142 $wgOut->setSubtitle( wfMsg( 'difference' ) );
143 $wgOut->setRobotpolicy( 'noindex,nofollow' );
145 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
146 $wgOut->loginToUse();
148 wfProfileOut( __METHOD__
);
152 $sk = $wgUser->getSkin();
154 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
155 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
160 // Prepare a change patrol link, if applicable
161 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
162 // If we've been given an explicit change identifier, use it; saves time
163 if( $this->mRcidMarkPatrolled
) {
164 $rcid = $this->mRcidMarkPatrolled
;
166 // Look for an unpatrolled change corresponding to this diff
167 $db = wfGetDB( DB_SLAVE
);
168 $change = RecentChange
::newFromConds(
170 // Add redundant user,timestamp condition so we can use the existing index
171 'rc_user_text' => $this->mNewRev
->getRawUserText(),
172 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
173 'rc_this_oldid' => $this->mNewid
,
174 'rc_last_oldid' => $this->mOldid
,
179 if( $change instanceof RecentChange
) {
180 $rcid = $change->mAttribs
['rc_id'];
188 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
190 wfMsgHtml( 'markaspatrolleddiff' ),
191 "action=markpatrolled&rcid={$rcid}"
200 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
201 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
202 if ( $this->mNewRev
->isCurrent() ) {
203 $nextlink = ' ';
205 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
206 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
212 if ($this->mOldRev
->mMinorEdit
== 1) {
213 $oldminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
216 if ($this->mNewRev
->mMinorEdit
== 1) {
217 $newminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
220 $rdel = ''; $ldel = '';
221 if( $wgUser->isAllowed( 'deleterevision' ) ) {
222 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
223 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
224 // If revision was hidden from sysops
225 $ldel = wfMsgHtml('rev-delundel');
227 $ldel = $sk->makeKnownLinkObj( $revdel,
228 wfMsgHtml('rev-delundel'),
229 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
230 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
231 // Bolden oversighted content
232 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
233 $ldel = "<strong>$ldel</strong>";
235 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
236 // We don't currently handle well changing the top revision's settings
237 if( $this->mNewRev
->isCurrent() ) {
238 // If revision was hidden from sysops
239 $rdel = wfMsgHtml('rev-delundel');
240 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
241 // If revision was hidden from sysops
242 $rdel = wfMsgHtml('rev-delundel');
244 $rdel = $sk->makeKnownLinkObj( $revdel,
245 wfMsgHtml('rev-delundel'),
246 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
247 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
248 // Bolden oversighted content
249 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
250 $rdel = "<strong>$rdel</strong>";
252 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
255 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
256 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
257 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
258 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
259 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
260 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
261 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
262 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
264 $this->showDiff( $oldHeader, $newHeader );
267 $this->renderNewRevision();
269 wfProfileOut( __METHOD__
);
273 * Show the new revision of the page.
275 function renderNewRevision() {
277 wfProfileIn( __METHOD__
);
279 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
280 #add deleted rev tag if needed
281 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
282 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
283 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
284 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
287 if( !$this->mNewRev
->isCurrent() ) {
288 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
291 $this->loadNewText();
292 if( is_object( $this->mNewRev
) ) {
293 $wgOut->setRevisionId( $this->mNewRev
->getId() );
296 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
297 // Stolen from Article::view --AG 2007-10-11
299 // Give hooks a chance to customise the output
300 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
301 // Wrap the whole lot in a <pre> and don't parse
303 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
304 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
305 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
306 $wgOut->addHtml( "\n</pre>\n" );
309 $wgOut->addWikiTextTidy( $this->mNewtext
);
311 if( !$this->mNewRev
->isCurrent() ) {
312 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
315 wfProfileOut( __METHOD__
);
319 * Show the first revision of an article. Uses normal diff headers in
320 * contrast to normal "old revision" display style.
322 function showFirstRevision() {
323 global $wgOut, $wgUser;
324 wfProfileIn( __METHOD__
);
326 # Get article text from the DB
328 if ( ! $this->loadNewText() ) {
329 $t = $this->mTitle
->getPrefixedText() . ' ' . wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
330 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
331 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
332 wfProfileOut( __METHOD__
);
335 if ( $this->mNewRev
->isCurrent() ) {
336 $wgOut->setArticleFlag( true );
339 # Check if user is allowed to look at this page. If not, bail out.
341 if ( !( $this->mTitle
->userCanRead() ) ) {
342 $wgOut->loginToUse();
344 wfProfileOut( __METHOD__
);
348 # Prepare the header box
350 $sk = $wgUser->getSkin();
352 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
353 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
354 $sk->revUserTools( $this->mNewRev
) . "<br />" .
355 $sk->revComment( $this->mNewRev
) . "<br />" .
356 $nextlink . "</div>\n";
358 $wgOut->addHTML( $header );
360 $wgOut->setSubtitle( wfMsg( 'difference' ) );
361 $wgOut->setRobotpolicy( 'noindex,nofollow' );
363 wfProfileOut( __METHOD__
);
367 * Get the diff text, send it to $wgOut
368 * Returns false if the diff could not be generated, otherwise returns true
370 function showDiff( $otitle, $ntitle ) {
372 $diff = $this->getDiff( $otitle, $ntitle );
373 if ( $diff === false ) {
374 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" );
377 $this->showDiffStyle();
378 $wgOut->addHTML( $diff );
384 * Add style sheets and supporting JS for diff display.
386 function showDiffStyle() {
387 global $wgStylePath, $wgStyleVersion, $wgOut;
388 $wgOut->addStyle( 'common/diff.css' );
390 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
391 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
395 * Get complete diff table, including header
397 * @param Title $otitle Old title
398 * @param Title $ntitle New title
401 function getDiff( $otitle, $ntitle ) {
402 $body = $this->getDiffBody();
403 if ( $body === false ) {
406 $multi = $this->getMultiNotice();
407 return $this->addHeader( $body, $otitle, $ntitle, $multi );
412 * Get the diff table body, without header
416 function getDiffBody() {
418 wfProfileIn( __METHOD__
);
419 // Check if the diff should be hidden from this user
420 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
422 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
427 if ( $this->mOldid
&& $this->mNewid
) {
428 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
430 if ( !$this->mRefreshCache
) {
431 $difftext = $wgMemc->get( $key );
433 wfIncrStats( 'diff_cache_hit' );
434 $difftext = $this->localiseLineNumbers( $difftext );
435 $difftext .= "\n<!-- diff cache key $key -->\n";
436 wfProfileOut( __METHOD__
);
439 } // don't try to load but save the result
442 // Loadtext is permission safe, this just clears out the diff
443 if ( !$this->loadText() ) {
444 wfProfileOut( __METHOD__
);
448 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
450 // Save to cache for 7 days
451 if ( $key !== false && $difftext !== false ) {
452 wfIncrStats( 'diff_cache_miss' );
453 $wgMemc->set( $key, $difftext, 7*86400 );
455 wfIncrStats( 'diff_uncacheable' );
457 // Replace line numbers with the text in the user's language
458 if ( $difftext !== false ) {
459 $difftext = $this->localiseLineNumbers( $difftext );
461 wfProfileOut( __METHOD__
);
466 * Generate a diff, no caching
467 * $otext and $ntext must be already segmented
469 function generateDiffBody( $otext, $ntext ) {
470 global $wgExternalDiffEngine, $wgContLang;
472 $otext = str_replace( "\r\n", "\n", $otext );
473 $ntext = str_replace( "\r\n", "\n", $ntext );
475 if ( $wgExternalDiffEngine == 'wikidiff' ) {
476 # For historical reasons, external diff engine expects
477 # input text to be HTML-escaped already
478 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
479 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
480 if( !function_exists( 'wikidiff_do_diff' ) ) {
481 dl('php_wikidiff.so');
483 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
486 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
487 # Better external diff engine, the 2 may some day be dropped
488 # This one does the escaping and segmenting itself
489 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
490 wfProfileIn( __METHOD__
. "-dl" );
491 @dl
('php_wikidiff2.so');
492 wfProfileOut( __METHOD__
. "-dl" );
494 if ( function_exists( 'wikidiff2_do_diff' ) ) {
495 wfProfileIn( 'wikidiff2_do_diff' );
496 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
497 wfProfileOut( 'wikidiff2_do_diff' );
501 if ( $wgExternalDiffEngine !== false ) {
503 global $wgTmpDirectory;
504 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
505 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
507 $tempFile1 = fopen( $tempName1, "w" );
509 wfProfileOut( __METHOD__
);
512 $tempFile2 = fopen( $tempName2, "w" );
514 wfProfileOut( __METHOD__
);
517 fwrite( $tempFile1, $otext );
518 fwrite( $tempFile2, $ntext );
519 fclose( $tempFile1 );
520 fclose( $tempFile2 );
521 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
522 wfProfileIn( __METHOD__
. "-shellexec" );
523 $difftext = wfShellExec( $cmd );
524 wfProfileOut( __METHOD__
. "-shellexec" );
525 unlink( $tempName1 );
526 unlink( $tempName2 );
531 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
532 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
533 $diffs = new Diff( $ota, $nta );
534 $formatter = new TableDiffFormatter();
535 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
540 * Replace line numbers with the text in the user's language
542 function localiseLineNumbers( $text ) {
543 return preg_replace_callback( '/<!--LINE (\d+)-->/',
544 array( &$this, 'localiseLineNumbersCb' ), $text );
547 function localiseLineNumbersCb( $matches ) {
549 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
554 * If there are revisions between the ones being compared, return a note saying so.
556 function getMultiNotice() {
557 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
560 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
561 // Comparing two different pages? Count would be meaningless.
565 $oldid = $this->mOldRev
->getId();
566 $newid = $this->mNewRev
->getId();
567 if ( $oldid > $newid ) {
568 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
571 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
575 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
580 * Add the header to a diff body
582 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
587 <col class='diff-marker' />
588 <col class='diff-content' />
589 <col class='diff-marker' />
590 <col class='diff-content' />
592 <td colspan='2' class='diff-otitle'>{$otitle}</td>
593 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
598 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
600 return $header . $diff . "</table>";
604 * Use specified text instead of loading from the database
606 function setText( $oldText, $newText ) {
607 $this->mOldtext
= $oldText;
608 $this->mNewtext
= $newText;
609 $this->mTextLoaded
= 2;
613 * Load revision metadata for the specified articles. If newid is 0, then compare
614 * the old article in oldid to the current article; if oldid is 0, then
615 * compare the current article to the immediately previous one (ignoring the
618 * If oldid is false, leave the corresponding revision object set
619 * to false. This is impossible via ordinary user input, and is provided for
622 function loadRevisionData() {
624 if ( $this->mRevisionsLoaded
) {
627 // Whether it succeeds or fails, we don't want to try again
628 $this->mRevisionsLoaded
= true;
631 // Load the new revision object
632 $this->mNewRev
= $this->mNewid
633 ? Revision
::newFromId( $this->mNewid
)
634 : Revision
::newFromTitle( $this->mTitle
);
635 if( !$this->mNewRev
instanceof Revision
)
638 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
639 $this->mNewid
= $this->mNewRev
->getId();
641 // Check if page is editable
642 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
644 // Set assorted variables
645 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
646 $this->mNewPage
= $this->mNewRev
->getTitle();
647 if( $this->mNewRev
->isCurrent() ) {
648 $newLink = $this->mNewPage
->escapeLocalUrl();
649 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
650 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
652 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
653 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
656 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
657 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
658 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
660 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
661 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
663 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
664 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
665 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
666 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
669 // Load the old revision object
670 $this->mOldRev
= false;
671 if( $this->mOldid
) {
672 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
673 } elseif ( $this->mOldid
=== 0 ) {
674 $rev = $this->mNewRev
->getPrevious();
676 $this->mOldid
= $rev->getId();
677 $this->mOldRev
= $rev;
679 // No previous revision; mark to show as first-version only.
680 $this->mOldid
= false;
681 $this->mOldRev
= false;
683 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
685 if( is_null( $this->mOldRev
) ) {
689 if ( $this->mOldRev
) {
690 $this->mOldPage
= $this->mOldRev
->getTitle();
692 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
693 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
694 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
695 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
697 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
698 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
699 // Add an "undo" link
700 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
701 if ( $editable && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
) )
702 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
704 if ( !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
705 $this->mOldtitle
= "<span class='history-deleted'>{$this->mOldPagetitle}</span>";
706 } else if ( $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
707 $this->mOldtitle
= '<span class="history-deleted">'.$this->mOldtitle
.'</span>';
715 * Load the text of the revisions, as well as revision data.
717 function loadText() {
718 if ( $this->mTextLoaded
== 2 ) {
721 // Whether it succeeds or fails, we don't want to try again
722 $this->mTextLoaded
= 2;
725 if ( !$this->loadRevisionData() ) {
728 if ( $this->mOldRev
) {
729 $this->mOldtext
= $this->mOldRev
->revText();
730 if ( $this->mOldtext
=== false ) {
734 if ( $this->mNewRev
) {
735 $this->mNewtext
= $this->mNewRev
->revText();
736 if ( $this->mNewtext
=== false ) {
744 * Load the text of the new revision, not the old one
746 function loadNewText() {
747 if ( $this->mTextLoaded
>= 1 ) {
750 $this->mTextLoaded
= 1;
752 if ( !$this->loadRevisionData() ) {
755 $this->mNewtext
= $this->mNewRev
->getText();
762 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
764 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
765 // You may copy this code freely under the conditions of the GPL.
768 define('USE_ASSERTS', function_exists('assert'));
773 * @addtogroup DifferenceEngine
781 trigger_error('pure virtual', E_USER_ERROR
);
785 return $this->orig ?
sizeof($this->orig
) : 0;
788 function nclosing() {
789 return $this->closing ?
sizeof($this->closing
) : 0;
796 * @addtogroup DifferenceEngine
798 class _DiffOp_Copy
extends _DiffOp
{
801 function _DiffOp_Copy ($orig, $closing = false) {
802 if (!is_array($closing))
805 $this->closing
= $closing;
809 return new _DiffOp_Copy($this->closing
, $this->orig
);
816 * @addtogroup DifferenceEngine
818 class _DiffOp_Delete
extends _DiffOp
{
819 var $type = 'delete';
821 function _DiffOp_Delete ($lines) {
822 $this->orig
= $lines;
823 $this->closing
= false;
827 return new _DiffOp_Add($this->orig
);
834 * @addtogroup DifferenceEngine
836 class _DiffOp_Add
extends _DiffOp
{
839 function _DiffOp_Add ($lines) {
840 $this->closing
= $lines;
845 return new _DiffOp_Delete($this->closing
);
852 * @addtogroup DifferenceEngine
854 class _DiffOp_Change
extends _DiffOp
{
855 var $type = 'change';
857 function _DiffOp_Change ($orig, $closing) {
859 $this->closing
= $closing;
863 return new _DiffOp_Change($this->closing
, $this->orig
);
869 * Class used internally by Diff to actually compute the diffs.
871 * The algorithm used here is mostly lifted from the perl module
872 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
873 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
875 * More ideas are taken from:
876 * http://www.ics.uci.edu/~eppstein/161/960229.html
878 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
879 * diffutils-2.7, which can be found at:
880 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
882 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
885 * Line length limits for robustness added by Tim Starling, 2005-08-31
887 * @author Geoffrey T. Dairiki, Tim Starling
889 * @addtogroup DifferenceEngine
892 const MAX_XREF_LENGTH
= 10000;
894 function diff ($from_lines, $to_lines) {
895 wfProfileIn( __METHOD__
);
897 $n_from = sizeof($from_lines);
898 $n_to = sizeof($to_lines);
900 $this->xchanged
= $this->ychanged
= array();
901 $this->xv
= $this->yv
= array();
902 $this->xind
= $this->yind
= array();
904 unset($this->in_seq
);
907 // Skip leading common lines.
908 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
909 if ($from_lines[$skip] !== $to_lines[$skip])
911 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
913 // Skip trailing common lines.
914 $xi = $n_from; $yi = $n_to;
915 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
916 if ($from_lines[$xi] !== $to_lines[$yi])
918 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
921 // Ignore lines which do not exist in both files.
922 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
923 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
926 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
927 $line = $to_lines[$yi];
928 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
930 $yhash[$this->_line_hash($line)] = 1;
934 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
935 $line = $from_lines[$xi];
936 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
943 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
945 // Merge edits when possible
946 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
947 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
949 // Compute the edit operations.
952 while ($xi < $n_from ||
$yi < $n_to) {
953 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
954 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
956 // Skip matching "snake".
958 while ( $xi < $n_from && $yi < $n_to
959 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
960 $copy[] = $from_lines[$xi++
];
964 $edits[] = new _DiffOp_Copy($copy);
966 // Find deletes & adds.
968 while ($xi < $n_from && $this->xchanged
[$xi])
969 $delete[] = $from_lines[$xi++
];
972 while ($yi < $n_to && $this->ychanged
[$yi])
973 $add[] = $to_lines[$yi++
];
976 $edits[] = new _DiffOp_Change($delete, $add);
978 $edits[] = new _DiffOp_Delete($delete);
980 $edits[] = new _DiffOp_Add($add);
982 wfProfileOut( __METHOD__
);
987 * Returns the whole line if it's small enough, or the MD5 hash otherwise
989 function _line_hash( $line ) {
990 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
998 /* Divide the Largest Common Subsequence (LCS) of the sequences
999 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1002 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1003 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1004 * sub sequences. The first sub-sequence is contained in [X0, X1),
1005 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1006 * that (X0, Y0) == (XOFF, YOFF) and
1007 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1009 * This function assumes that the first lines of the specified portions
1010 * of the two files do not match, and likewise that the last lines do not
1011 * match. The caller must trim matching lines from the beginning and end
1012 * of the portions it is going to specify.
1014 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1015 wfProfileIn( __METHOD__
);
1018 if ($xlim - $xoff > $ylim - $yoff) {
1019 // Things seems faster (I'm not sure I understand why)
1020 // when the shortest sequence in X.
1022 list ($xoff, $xlim, $yoff, $ylim)
1023 = array( $yoff, $ylim, $xoff, $xlim);
1027 for ($i = $ylim - 1; $i >= $yoff; $i--)
1028 $ymatches[$this->xv
[$i]][] = $i;
1030 for ($i = $ylim - 1; $i >= $yoff; $i--)
1031 $ymatches[$this->yv
[$i]][] = $i;
1034 $this->seq
[0]= $yoff - 1;
1035 $this->in_seq
= array();
1036 $ymids[0] = array();
1038 $numer = $xlim - $xoff +
$nchunks - 1;
1040 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1041 wfProfileIn( __METHOD__
. "-chunk" );
1043 for ($i = 0; $i <= $this->lcs
; $i++
)
1044 $ymids[$i][$chunk-1] = $this->seq
[$i];
1046 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1047 for ( ; $x < $x1; $x++
) {
1048 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1049 if (empty($ymatches[$line]))
1051 $matches = $ymatches[$line];
1053 while (list ($junk, $y) = each($matches))
1054 if (empty($this->in_seq
[$y])) {
1055 $k = $this->_lcs_pos($y);
1056 USE_ASSERTS
&& assert($k > 0);
1057 $ymids[$k] = $ymids[$k-1];
1060 while (list ( /* $junk */, $y) = each($matches)) {
1061 if ($y > $this->seq
[$k-1]) {
1062 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1063 // Optimization: this is a common case:
1064 // next match is just replacing previous match.
1065 $this->in_seq
[$this->seq
[$k]] = false;
1066 $this->seq
[$k] = $y;
1067 $this->in_seq
[$y] = 1;
1068 } else if (empty($this->in_seq
[$y])) {
1069 $k = $this->_lcs_pos($y);
1070 USE_ASSERTS
&& assert($k > 0);
1071 $ymids[$k] = $ymids[$k-1];
1075 wfProfileOut( __METHOD__
. "-chunk" );
1078 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1079 $ymid = $ymids[$this->lcs
];
1080 for ($n = 0; $n < $nchunks - 1; $n++
) {
1081 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1082 $y1 = $ymid[$n] +
1;
1083 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1085 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1087 wfProfileOut( __METHOD__
);
1088 return array($this->lcs
, $seps);
1091 function _lcs_pos ($ypos) {
1092 wfProfileIn( __METHOD__
);
1095 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1096 $this->seq
[++
$this->lcs
] = $ypos;
1097 $this->in_seq
[$ypos] = 1;
1098 wfProfileOut( __METHOD__
);
1103 while ($beg < $end) {
1104 $mid = (int)(($beg +
$end) / 2);
1105 if ( $ypos > $this->seq
[$mid] )
1111 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1113 $this->in_seq
[$this->seq
[$end]] = false;
1114 $this->seq
[$end] = $ypos;
1115 $this->in_seq
[$ypos] = 1;
1116 wfProfileOut( __METHOD__
);
1120 /* Find LCS of two sequences.
1122 * The results are recorded in the vectors $this->{x,y}changed[], by
1123 * storing a 1 in the element for each line that is an insertion
1124 * or deletion (ie. is not in the LCS).
1126 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1128 * Note that XLIM, YLIM are exclusive bounds.
1129 * All line numbers are origin-0 and discarded lines are not counted.
1131 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1132 wfProfileIn( __METHOD__
);
1134 // Slide down the bottom initial diagonal.
1135 while ($xoff < $xlim && $yoff < $ylim
1136 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1141 // Slide up the top initial diagonal.
1142 while ($xlim > $xoff && $ylim > $yoff
1143 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1148 if ($xoff == $xlim ||
$yoff == $ylim)
1151 // This is ad hoc but seems to work well.
1152 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1153 //$nchunks = max(2,min(8,(int)$nchunks));
1154 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1156 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1160 // X and Y sequences have no common subsequence:
1161 // mark all changed.
1162 while ($yoff < $ylim)
1163 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1164 while ($xoff < $xlim)
1165 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1167 // Use the partitions to split this problem into subproblems.
1170 while ($pt2 = next($seps)) {
1171 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1175 wfProfileOut( __METHOD__
);
1178 /* Adjust inserts/deletes of identical lines to join changes
1179 * as much as possible.
1181 * We do something when a run of changed lines include a
1182 * line at one end and has an excluded, identical line at the other.
1183 * We are free to choose which identical line is included.
1184 * `compareseq' usually chooses the one at the beginning,
1185 * but usually it is cleaner to consider the following identical line
1186 * to be the "change".
1188 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1190 function _shift_boundaries ($lines, &$changed, $other_changed) {
1191 wfProfileIn( __METHOD__
);
1195 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1196 $len = sizeof($lines);
1197 $other_len = sizeof($other_changed);
1201 * Scan forwards to find beginning of another run of changes.
1202 * Also keep track of the corresponding point in the other file.
1204 * Throughout this code, $i and $j are adjusted together so that
1205 * the first $i elements of $changed and the first $j elements
1206 * of $other_changed both contain the same number of zeros
1207 * (unchanged lines).
1208 * Furthermore, $j is always kept so that $j == $other_len or
1209 * $other_changed[$j] == false.
1211 while ($j < $other_len && $other_changed[$j])
1214 while ($i < $len && ! $changed[$i]) {
1215 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1217 while ($j < $other_len && $other_changed[$j])
1226 // Find the end of this run of changes.
1227 while (++
$i < $len && $changed[$i])
1232 * Record the length of this run of changes, so that
1233 * we can later determine whether the run has grown.
1235 $runlength = $i - $start;
1238 * Move the changed region back, so long as the
1239 * previous unchanged line matches the last changed one.
1240 * This merges with previous changed regions.
1242 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1243 $changed[--$start] = 1;
1244 $changed[--$i] = false;
1245 while ($start > 0 && $changed[$start - 1])
1247 USE_ASSERTS
&& assert('$j > 0');
1248 while ($other_changed[--$j])
1250 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1254 * Set CORRESPONDING to the end of the changed run, at the last
1255 * point where it corresponds to a changed run in the other file.
1256 * CORRESPONDING == LEN means no such point has been found.
1258 $corresponding = $j < $other_len ?
$i : $len;
1261 * Move the changed region forward, so long as the
1262 * first changed line matches the following unchanged one.
1263 * This merges with following changed regions.
1264 * Do this second, so that if there are no merges,
1265 * the changed region is moved forward as far as possible.
1267 while ($i < $len && $lines[$start] == $lines[$i]) {
1268 $changed[$start++
] = false;
1270 while ($i < $len && $changed[$i])
1273 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1275 if ($j < $other_len && $other_changed[$j]) {
1276 $corresponding = $i;
1277 while ($j < $other_len && $other_changed[$j])
1281 } while ($runlength != $i - $start);
1284 * If possible, move the fully-merged run of changes
1285 * back to a corresponding run in the other file.
1287 while ($corresponding < $i) {
1288 $changed[--$start] = 1;
1290 USE_ASSERTS
&& assert('$j > 0');
1291 while ($other_changed[--$j])
1293 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1296 wfProfileOut( __METHOD__
);
1301 * Class representing a 'diff' between two sequences of strings.
1304 * @addtogroup DifferenceEngine
1312 * Computes diff between sequences of strings.
1314 * @param $from_lines array An array of strings.
1315 * (Typically these are lines from a file.)
1316 * @param $to_lines array An array of strings.
1318 function Diff($from_lines, $to_lines) {
1319 $eng = new _DiffEngine
;
1320 $this->edits
= $eng->diff($from_lines, $to_lines);
1321 //$this->_check($from_lines, $to_lines);
1325 * Compute reversed Diff.
1329 * $diff = new Diff($lines1, $lines2);
1330 * $rev = $diff->reverse();
1331 * @return object A Diff object representing the inverse of the
1334 function reverse () {
1336 $rev->edits
= array();
1337 foreach ($this->edits
as $edit) {
1338 $rev->edits
[] = $edit->reverse();
1344 * Check for empty diff.
1346 * @return bool True iff two sequences were identical.
1348 function isEmpty () {
1349 foreach ($this->edits
as $edit) {
1350 if ($edit->type
!= 'copy')
1357 * Compute the length of the Longest Common Subsequence (LCS).
1359 * This is mostly for diagnostic purposed.
1361 * @return int The length of the LCS.
1365 foreach ($this->edits
as $edit) {
1366 if ($edit->type
== 'copy')
1367 $lcs +
= sizeof($edit->orig
);
1373 * Get the original set of lines.
1375 * This reconstructs the $from_lines parameter passed to the
1378 * @return array The original sequence of strings.
1383 foreach ($this->edits
as $edit) {
1385 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1391 * Get the closing set of lines.
1393 * This reconstructs the $to_lines parameter passed to the
1396 * @return array The sequence of strings.
1398 function closing() {
1401 foreach ($this->edits
as $edit) {
1403 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1409 * Check a Diff for validity.
1411 * This is here only for debugging purposes.
1413 function _check ($from_lines, $to_lines) {
1414 wfProfileIn( __METHOD__
);
1415 if (serialize($from_lines) != serialize($this->orig()))
1416 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1417 if (serialize($to_lines) != serialize($this->closing()))
1418 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1420 $rev = $this->reverse();
1421 if (serialize($to_lines) != serialize($rev->orig()))
1422 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1423 if (serialize($from_lines) != serialize($rev->closing()))
1424 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1428 foreach ($this->edits
as $edit) {
1429 if ( $prevtype == $edit->type
)
1430 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1431 $prevtype = $edit->type
;
1434 $lcs = $this->lcs();
1435 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1436 wfProfileOut( __METHOD__
);
1441 * @todo document, bad name.
1443 * @addtogroup DifferenceEngine
1445 class MappedDiff
extends Diff
1450 * Computes diff between sequences of strings.
1452 * This can be used to compute things like
1453 * case-insensitve diffs, or diffs which ignore
1454 * changes in white-space.
1456 * @param $from_lines array An array of strings.
1457 * (Typically these are lines from a file.)
1459 * @param $to_lines array An array of strings.
1461 * @param $mapped_from_lines array This array should
1462 * have the same size number of elements as $from_lines.
1463 * The elements in $mapped_from_lines and
1464 * $mapped_to_lines are what is actually compared
1465 * when computing the diff.
1467 * @param $mapped_to_lines array This array should
1468 * have the same number of elements as $to_lines.
1470 function MappedDiff($from_lines, $to_lines,
1471 $mapped_from_lines, $mapped_to_lines) {
1472 wfProfileIn( __METHOD__
);
1474 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1475 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1477 $this->Diff($mapped_from_lines, $mapped_to_lines);
1480 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1481 $orig = &$this->edits
[$i]->orig
;
1482 if (is_array($orig)) {
1483 $orig = array_slice($from_lines, $xi, sizeof($orig));
1484 $xi +
= sizeof($orig);
1487 $closing = &$this->edits
[$i]->closing
;
1488 if (is_array($closing)) {
1489 $closing = array_slice($to_lines, $yi, sizeof($closing));
1490 $yi +
= sizeof($closing);
1493 wfProfileOut( __METHOD__
);
1498 * A class to format Diffs
1500 * This class formats the diff in classic diff format.
1501 * It is intended that this class be customized via inheritance,
1502 * to obtain fancier outputs.
1505 * @addtogroup DifferenceEngine
1507 class DiffFormatter
{
1509 * Number of leading context "lines" to preserve.
1511 * This should be left at zero for this class, but subclasses
1512 * may want to set this to other values.
1514 var $leading_context_lines = 0;
1517 * Number of trailing context "lines" to preserve.
1519 * This should be left at zero for this class, but subclasses
1520 * may want to set this to other values.
1522 var $trailing_context_lines = 0;
1527 * @param $diff object A Diff object.
1528 * @return string The formatted output.
1530 function format($diff) {
1531 wfProfileIn( __METHOD__
);
1537 $nlead = $this->leading_context_lines
;
1538 $ntrail = $this->trailing_context_lines
;
1540 $this->_start_diff();
1542 foreach ($diff->edits
as $edit) {
1543 if ($edit->type
== 'copy') {
1544 if (is_array($block)) {
1545 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1550 $context = array_slice($edit->orig
, 0, $ntrail);
1551 $block[] = new _DiffOp_Copy($context);
1553 $this->_block($x0, $ntrail +
$xi - $x0,
1554 $y0, $ntrail +
$yi - $y0,
1559 $context = $edit->orig
;
1562 if (! is_array($block)) {
1563 $context = array_slice($context, sizeof($context) - $nlead);
1564 $x0 = $xi - sizeof($context);
1565 $y0 = $yi - sizeof($context);
1568 $block[] = new _DiffOp_Copy($context);
1574 $xi +
= sizeof($edit->orig
);
1576 $yi +
= sizeof($edit->closing
);
1579 if (is_array($block))
1580 $this->_block($x0, $xi - $x0,
1584 $end = $this->_end_diff();
1585 wfProfileOut( __METHOD__
);
1589 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1590 wfProfileIn( __METHOD__
);
1591 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1592 foreach ($edits as $edit) {
1593 if ($edit->type
== 'copy')
1594 $this->_context($edit->orig
);
1595 elseif ($edit->type
== 'add')
1596 $this->_added($edit->closing
);
1597 elseif ($edit->type
== 'delete')
1598 $this->_deleted($edit->orig
);
1599 elseif ($edit->type
== 'change')
1600 $this->_changed($edit->orig
, $edit->closing
);
1602 trigger_error('Unknown edit type', E_USER_ERROR
);
1604 $this->_end_block();
1605 wfProfileOut( __METHOD__
);
1608 function _start_diff() {
1612 function _end_diff() {
1613 $val = ob_get_contents();
1618 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1620 $xbeg .= "," . ($xbeg +
$xlen - 1);
1622 $ybeg .= "," . ($ybeg +
$ylen - 1);
1624 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1627 function _start_block($header) {
1628 echo $header . "\n";
1631 function _end_block() {
1634 function _lines($lines, $prefix = ' ') {
1635 foreach ($lines as $line)
1636 echo "$prefix $line\n";
1639 function _context($lines) {
1640 $this->_lines($lines);
1643 function _added($lines) {
1644 $this->_lines($lines, '>');
1646 function _deleted($lines) {
1647 $this->_lines($lines, '<');
1650 function _changed($orig, $closing) {
1651 $this->_deleted($orig);
1653 $this->_added($closing);
1658 * A formatter that outputs unified diffs
1659 * @addtogroup DifferenceEngine
1662 class UnifiedDiffFormatter
extends DiffFormatter
{
1663 var $leading_context_lines = 2;
1664 var $trailing_context_lines = 2;
1666 function _added($lines) {
1667 $this->_lines($lines, '+');
1669 function _deleted($lines) {
1670 $this->_lines($lines, '-');
1672 function _changed($orig, $closing) {
1673 $this->_deleted($orig);
1674 $this->_added($closing);
1676 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1677 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1682 * A pseudo-formatter that just passes along the Diff::$edits array
1683 * @addtogroup DifferenceEngine
1685 class ArrayDiffFormatter
extends DiffFormatter
{
1686 function format($diff) {
1690 foreach($diff->edits
as $edit)
1691 switch($edit->type
) {
1693 foreach($edit->closing
as $l) {
1697 'newline' => $newline++
1702 foreach($edit->orig
as $l) {
1704 'action' => 'delete',
1706 'oldline' => $oldline++
,
1711 foreach($edit->orig
as $i => $l) {
1713 'action' => 'change',
1715 'new' => @$edit->closing
[$i],
1716 'oldline' => $oldline++
,
1717 'newline' => $newline++
,
1722 $oldline +
= count($edit->orig
);
1723 $newline +
= count($edit->orig
);
1730 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1734 define('NBSP', ' '); // iso-8859-x non-breaking space.
1739 * @addtogroup DifferenceEngine
1741 class _HWLDF_WordAccumulator
{
1742 function _HWLDF_WordAccumulator () {
1743 $this->_lines
= array();
1749 function _flushGroup ($new_tag) {
1750 if ($this->_group
!== '') {
1751 if ($this->_tag
== 'ins')
1752 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1753 htmlspecialchars ( $this->_group
) . '</ins>';
1754 elseif ($this->_tag
== 'del')
1755 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1756 htmlspecialchars ( $this->_group
) . '</del>';
1758 $this->_line
.= htmlspecialchars ( $this->_group
);
1761 $this->_tag
= $new_tag;
1764 function _flushLine ($new_tag) {
1765 $this->_flushGroup($new_tag);
1766 if ($this->_line
!= '')
1767 array_push ( $this->_lines
, $this->_line
);
1769 # make empty lines visible by inserting an NBSP
1770 array_push ( $this->_lines
, NBSP
);
1774 function addWords ($words, $tag = '') {
1775 if ($tag != $this->_tag
)
1776 $this->_flushGroup($tag);
1778 foreach ($words as $word) {
1779 // new-line should only come as first char of word.
1782 if ($word[0] == "\n") {
1783 $this->_flushLine($tag);
1784 $word = substr($word, 1);
1786 assert(!strstr($word, "\n"));
1787 $this->_group
.= $word;
1791 function getLines() {
1792 $this->_flushLine('~done');
1793 return $this->_lines
;
1800 * @addtogroup DifferenceEngine
1802 class WordLevelDiff
extends MappedDiff
{
1803 const MAX_LINE_LENGTH
= 10000;
1805 function WordLevelDiff ($orig_lines, $closing_lines) {
1806 wfProfileIn( __METHOD__
);
1808 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1809 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1811 $this->MappedDiff($orig_words, $closing_words,
1812 $orig_stripped, $closing_stripped);
1813 wfProfileOut( __METHOD__
);
1816 function _split($lines) {
1817 wfProfileIn( __METHOD__
);
1820 $stripped = array();
1822 foreach ( $lines as $line ) {
1823 # If the line is too long, just pretend the entire line is one big word
1824 # This prevents resource exhaustion problems
1831 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1833 $stripped[] = $line;
1836 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1839 $words = array_merge( $words, $m[0] );
1840 $stripped = array_merge( $stripped, $m[1] );
1844 wfProfileOut( __METHOD__
);
1845 return array($words, $stripped);
1849 wfProfileIn( __METHOD__
);
1850 $orig = new _HWLDF_WordAccumulator
;
1852 foreach ($this->edits
as $edit) {
1853 if ($edit->type
== 'copy')
1854 $orig->addWords($edit->orig
);
1855 elseif ($edit->orig
)
1856 $orig->addWords($edit->orig
, 'del');
1858 $lines = $orig->getLines();
1859 wfProfileOut( __METHOD__
);
1863 function closing () {
1864 wfProfileIn( __METHOD__
);
1865 $closing = new _HWLDF_WordAccumulator
;
1867 foreach ($this->edits
as $edit) {
1868 if ($edit->type
== 'copy')
1869 $closing->addWords($edit->closing
);
1870 elseif ($edit->closing
)
1871 $closing->addWords($edit->closing
, 'ins');
1873 $lines = $closing->getLines();
1874 wfProfileOut( __METHOD__
);
1880 * Wikipedia Table style diff formatter.
1883 * @addtogroup DifferenceEngine
1885 class TableDiffFormatter
extends DiffFormatter
{
1886 function TableDiffFormatter() {
1887 $this->leading_context_lines
= 2;
1888 $this->trailing_context_lines
= 2;
1891 public static function escapeWhiteSpace( $msg ) {
1892 $msg = preg_replace( '/^ /m', ' ', $msg );
1893 $msg = preg_replace( '/ $/m', ' ', $msg );
1894 $msg = preg_replace( '/ /', ' ', $msg );
1898 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1899 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1900 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1904 function _start_block( $header ) {
1908 function _end_block() {
1911 function _lines( $lines, $prefix=' ', $color='white' ) {
1914 # HTML-escape parameter before calling this
1915 function addedLine( $line ) {
1916 return $this->wrapLine( '+', 'diff-addedline', $line );
1919 # HTML-escape parameter before calling this
1920 function deletedLine( $line ) {
1921 return $this->wrapLine( '-', 'diff-deletedline', $line );
1924 # HTML-escape parameter before calling this
1925 function contextLine( $line ) {
1926 return $this->wrapLine( ' ', 'diff-context', $line );
1929 private function wrapLine( $marker, $class, $line ) {
1930 if( $line !== '' ) {
1931 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1932 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1934 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1937 function emptyLine() {
1938 return '<td colspan="2"> </td>';
1941 function _added( $lines ) {
1942 foreach ($lines as $line) {
1943 echo '<tr>' . $this->emptyLine() .
1944 $this->addedLine( '<ins class="diffchange">' .
1945 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1949 function _deleted($lines) {
1950 foreach ($lines as $line) {
1951 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1952 htmlspecialchars ( $line ) . '</del>' ) .
1953 $this->emptyLine() . "</tr>\n";
1957 function _context( $lines ) {
1958 foreach ($lines as $line) {
1960 $this->contextLine( htmlspecialchars ( $line ) ) .
1961 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1965 function _changed( $orig, $closing ) {
1966 wfProfileIn( __METHOD__
);
1968 $diff = new WordLevelDiff( $orig, $closing );
1969 $del = $diff->orig();
1970 $add = $diff->closing();
1972 # Notice that WordLevelDiff returns HTML-escaped output.
1973 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1975 while ( $line = array_shift( $del ) ) {
1976 $aline = array_shift( $add );
1977 echo '<tr>' . $this->deletedLine( $line ) .
1978 $this->addedLine( $aline ) . "</tr>\n";
1980 foreach ($add as $line) { # If any leftovers
1981 echo '<tr>' . $this->emptyLine() .
1982 $this->addedLine( $line ) . "</tr>\n";
1984 wfProfileOut( __METHOD__
);