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;
76 * Show difference between revisions
77 * @param $diffOnly bool show the difference only, no preview
79 function showDiffPage( $diffOnly = false ) {
80 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
81 $fname = 'DifferenceEngine::showDiffPage';
82 wfProfileIn( $fname );
84 # If external diffs are enabled both globally and for the user,
85 # we'll use the application/x-external-editor interface to call
86 # an external diff tool like kompare, kdiff3, etc.
87 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
88 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
90 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
91 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
92 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
93 $special=$wgLang->getNsText(NS_SPECIAL
);
98 Script={$wgServer}{$wgScript}
99 Special namespace={$special}
113 $wgOut->setArticleFlag( false );
114 if ( ! $this->loadRevisionData() ) {
115 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
116 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
117 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
118 $wgOut->addWikitext( $mtext );
119 wfProfileOut( $fname );
123 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
125 if ( $this->mNewRev
->isCurrent() ) {
126 $wgOut->setArticleFlag( true );
129 # mOldid is false if the difference engine is called with a "vague" query for
130 # a diff between a version V and its previous version V' AND the version V
131 # is the first version of that article. In that case, V' does not exist.
132 if ( $this->mOldid
=== false ) {
133 $wgOut->setPageTitle( wfMsg( 'difference-title', $this->mTitle
->getPrefixedText() ) );
134 $this->showFirstRevision();
135 $this->renderNewRevision(); // should we respect $diffOnly here or not?
136 wfProfileOut( $fname );
140 $wgOut->suppressQuickbar();
142 $oldTitle = $this->mOldPage
->getPrefixedText();
143 $newTitle = $this->mNewPage
->getPrefixedText();
144 if( $oldTitle == $newTitle ) {
145 $wgOut->setPageTitle( wfMsg( 'difference-title', $newTitle ) );
147 $wgOut->setPageTitle( wfMsg( 'difference-title', $oldTitle . ', ' . $newTitle ) );
149 $wgOut->setRobotpolicy( 'noindex,nofollow' );
151 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
152 $wgOut->loginToUse();
154 wfProfileOut( $fname );
158 $sk = $wgUser->getSkin();
160 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
161 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
166 // Prepare a change patrol link, if applicable
167 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
168 // If we've been given an explicit change identifier, use it; saves time
169 if( $this->mRcidMarkPatrolled
) {
170 $rcid = $this->mRcidMarkPatrolled
;
172 // Look for an unpatrolled change corresponding to this diff
173 $db = wfGetDB( DB_SLAVE
);
174 $change = RecentChange
::newFromConds(
176 // Add redundant timestamp condition so we can use the
178 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
179 'rc_this_oldid' => $this->mNewid
,
180 'rc_last_oldid' => $this->mOldid
,
185 if( $change instanceof RecentChange
) {
186 $rcid = $change->mAttribs
['rc_id'];
194 $patrol = ' [' . $sk->makeKnownLinkObj(
196 wfMsgHtml( 'markaspatrolleddiff' ),
197 "action=markpatrolled&rcid={$rcid}"
206 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
207 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
208 if ( $this->mNewRev
->isCurrent() ) {
209 $nextlink = ' ';
211 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
212 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
218 if ($this->mOldRev
->mMinorEdit
== 1) {
219 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
220 wfMsg( 'minoreditletter') ) . ' ';
223 if ($this->mNewRev
->mMinorEdit
== 1) {
224 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
225 wfMsg( 'minoreditletter') ) . ' ';
228 $rdel = ''; $ldel = '';
229 if( $wgUser->isAllowed( 'deleterevision' ) ) {
230 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
231 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
232 // If revision was hidden from sysops
233 $ldel = wfMsgHtml('rev-delundel');
235 $ldel = $sk->makeKnownLinkObj( $revdel,
236 wfMsgHtml('rev-delundel'),
237 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
238 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
239 // Bolden oversighted content
240 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
241 $ldel = "<strong>$ldel</strong>";
243 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
244 // We don't currently handle well changing the top revision's settings
245 if( $this->mNewRev
->isCurrent() ) {
246 // If revision was hidden from sysops
247 $rdel = wfMsgHtml('rev-delundel');
248 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
249 // If revision was hidden from sysops
250 $rdel = wfMsgHtml('rev-delundel');
252 $rdel = $sk->makeKnownLinkObj( $revdel,
253 wfMsgHtml('rev-delundel'),
254 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
255 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
256 // Bolden oversighted content
257 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
258 $rdel = "<strong>$rdel</strong>";
260 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
263 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
264 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
265 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
266 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
267 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
268 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
269 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
270 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
272 $this->showDiff( $oldHeader, $newHeader );
275 $this->renderNewRevision();
277 wfProfileOut( $fname );
281 * Show the new revision of the page.
283 function renderNewRevision() {
285 $fname = 'DifferenceEngine::renderNewRevision';
286 wfProfileIn( $fname );
288 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
289 #add deleted rev tag if needed
290 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
291 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
292 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
293 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
296 if( !$this->mNewRev
->isCurrent() ) {
297 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
300 $this->loadNewText();
301 if( is_object( $this->mNewRev
) ) {
302 $wgOut->setRevisionId( $this->mNewRev
->getId() );
305 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
306 // Stolen from Article::view --AG 2007-10-11
308 // Give hooks a chance to customise the output
309 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
310 // Wrap the whole lot in a <pre> and don't parse
312 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
313 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
314 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
315 $wgOut->addHtml( "\n</pre>\n" );
318 $wgOut->addWikiTextTidy( $this->mNewtext
);
320 if( !$this->mNewRev
->isCurrent() ) {
321 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
324 wfProfileOut( $fname );
328 * Show the first revision of an article. Uses normal diff headers in
329 * contrast to normal "old revision" display style.
331 function showFirstRevision() {
332 global $wgOut, $wgUser;
334 $fname = 'DifferenceEngine::showFirstRevision';
335 wfProfileIn( $fname );
337 # Get article text from the DB
339 if ( ! $this->loadNewText() ) {
340 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
342 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
343 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
344 $wgOut->addWikitext( $mtext );
345 wfProfileOut( $fname );
348 if ( $this->mNewRev
->isCurrent() ) {
349 $wgOut->setArticleFlag( true );
352 # Check if user is allowed to look at this page. If not, bail out.
354 if ( !( $this->mTitle
->userCanRead() ) ) {
355 $wgOut->loginToUse();
357 wfProfileOut( $fname );
361 # Prepare the header box
363 $sk = $wgUser->getSkin();
365 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
366 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
367 $sk->revUserTools( $this->mNewRev
) . "<br />" .
368 $sk->revComment( $this->mNewRev
) . "<br />" .
369 $nextlink . "</div>\n";
371 $wgOut->addHTML( $header );
373 $wgOut->setRobotpolicy( 'noindex,nofollow' );
375 wfProfileOut( $fname );
379 * Get the diff text, send it to $wgOut
380 * Returns false if the diff could not be generated, otherwise returns true
382 function showDiff( $otitle, $ntitle ) {
384 $diff = $this->getDiff( $otitle, $ntitle );
385 if ( $diff === false ) {
386 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
389 $this->showDiffStyle();
390 $wgOut->addHTML( $diff );
396 * Add style sheets and supporting JS for diff display.
398 function showDiffStyle() {
399 global $wgStylePath, $wgStyleVersion, $wgOut;
400 $wgOut->addStyle( 'common/diff.css' );
402 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
403 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
407 * Get complete diff table, including header
409 * @param Title $otitle Old title
410 * @param Title $ntitle New title
413 function getDiff( $otitle, $ntitle ) {
414 $body = $this->getDiffBody();
415 if ( $body === false ) {
418 $multi = $this->getMultiNotice();
419 return $this->addHeader( $body, $otitle, $ntitle, $multi );
424 * Get the diff table body, without header
428 function getDiffBody() {
430 $fname = 'DifferenceEngine::getDiffBody';
431 wfProfileIn( $fname );
435 if ( $this->mOldid
&& $this->mNewid
) {
436 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
438 if ( !$this->mRefreshCache
) {
439 $difftext = $wgMemc->get( $key );
441 wfIncrStats( 'diff_cache_hit' );
442 $difftext = $this->localiseLineNumbers( $difftext );
443 $difftext .= "\n<!-- diff cache key $key -->\n";
444 wfProfileOut( $fname );
447 } // don't try to load but save the result
450 // Loadtext is permission safe, this just clears out the diff
451 if ( !$this->loadText() ) {
452 wfProfileOut( $fname );
454 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
456 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
460 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
462 // Save to cache for 7 days
463 // Only do this for public revs, otherwise an admin can view the diff and a non-admin can nab it!
464 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
465 wfIncrStats( 'diff_uncacheable' );
466 } else if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
467 wfIncrStats( 'diff_uncacheable' );
468 } else if ( $key !== false && $difftext !== false ) {
469 wfIncrStats( 'diff_cache_miss' );
470 $wgMemc->set( $key, $difftext, 7*86400 );
472 wfIncrStats( 'diff_uncacheable' );
474 // Replace line numbers with the text in the user's language
475 if ( $difftext !== false ) {
476 $difftext = $this->localiseLineNumbers( $difftext );
478 wfProfileOut( $fname );
483 * Generate a diff, no caching
484 * $otext and $ntext must be already segmented
486 function generateDiffBody( $otext, $ntext ) {
487 global $wgExternalDiffEngine, $wgContLang;
488 $fname = 'DifferenceEngine::generateDiffBody';
490 $otext = str_replace( "\r\n", "\n", $otext );
491 $ntext = str_replace( "\r\n", "\n", $ntext );
493 if ( $wgExternalDiffEngine == 'wikidiff' ) {
494 # For historical reasons, external diff engine expects
495 # input text to be HTML-escaped already
496 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
497 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
498 if( !function_exists( 'wikidiff_do_diff' ) ) {
499 dl('php_wikidiff.so');
501 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
504 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
505 # Better external diff engine, the 2 may some day be dropped
506 # This one does the escaping and segmenting itself
507 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
508 wfProfileIn( "$fname-dl" );
509 @dl
('php_wikidiff2.so');
510 wfProfileOut( "$fname-dl" );
512 if ( function_exists( 'wikidiff2_do_diff' ) ) {
513 wfProfileIn( 'wikidiff2_do_diff' );
514 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
515 wfProfileOut( 'wikidiff2_do_diff' );
519 if ( $wgExternalDiffEngine !== false ) {
521 global $wgTmpDirectory;
522 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
523 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
525 $tempFile1 = fopen( $tempName1, "w" );
527 wfProfileOut( $fname );
530 $tempFile2 = fopen( $tempName2, "w" );
532 wfProfileOut( $fname );
535 fwrite( $tempFile1, $otext );
536 fwrite( $tempFile2, $ntext );
537 fclose( $tempFile1 );
538 fclose( $tempFile2 );
539 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
540 wfProfileIn( "$fname-shellexec" );
541 $difftext = wfShellExec( $cmd );
542 wfProfileOut( "$fname-shellexec" );
543 unlink( $tempName1 );
544 unlink( $tempName2 );
549 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
550 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
551 $diffs = new Diff( $ota, $nta );
552 $formatter = new TableDiffFormatter();
553 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
558 * Replace line numbers with the text in the user's language
560 function localiseLineNumbers( $text ) {
561 return preg_replace_callback( '/<!--LINE (\d+)-->/',
562 array( &$this, 'localiseLineNumbersCb' ), $text );
565 function localiseLineNumbersCb( $matches ) {
567 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
572 * If there are revisions between the ones being compared, return a note saying so.
574 function getMultiNotice() {
575 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
578 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
579 // Comparing two different pages? Count would be meaningless.
583 $oldid = $this->mOldRev
->getId();
584 $newid = $this->mNewRev
->getId();
585 if ( $oldid > $newid ) {
586 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
589 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
593 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
598 * Add the header to a diff body
600 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
605 <col class='diff-marker' />
606 <col class='diff-content' />
607 <col class='diff-marker' />
608 <col class='diff-content' />
610 <td colspan='2' class='diff-otitle'>{$otitle}</td>
611 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
616 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
618 return $header . $diff . "</table>";
622 * Use specified text instead of loading from the database
624 function setText( $oldText, $newText ) {
625 $this->mOldtext
= $oldText;
626 $this->mNewtext
= $newText;
627 $this->mTextLoaded
= 2;
631 * Load revision metadata for the specified articles. If newid is 0, then compare
632 * the old article in oldid to the current article; if oldid is 0, then
633 * compare the current article to the immediately previous one (ignoring the
636 * If oldid is false, leave the corresponding revision object set
637 * to false. This is impossible via ordinary user input, and is provided for
640 function loadRevisionData() {
642 if ( $this->mRevisionsLoaded
) {
645 // Whether it succeeds or fails, we don't want to try again
646 $this->mRevisionsLoaded
= true;
649 // Load the new revision object
650 $this->mNewRev
= $this->mNewid
651 ? Revision
::newFromId( $this->mNewid
)
652 : Revision
::newFromTitle( $this->mTitle
);
653 if( !$this->mNewRev
instanceof Revision
)
656 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
657 $this->mNewid
= $this->mNewRev
->getId();
659 // Set assorted variables
660 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
661 $this->mNewPage
= $this->mNewRev
->getTitle();
662 if( $this->mNewRev
->isCurrent() ) {
663 $newLink = $this->mNewPage
->escapeLocalUrl();
664 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
665 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
667 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
668 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
671 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
672 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
673 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
675 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
676 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
678 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
679 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
680 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
681 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
684 // Load the old revision object
685 $this->mOldRev
= false;
686 if( $this->mOldid
) {
687 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
688 } elseif ( $this->mOldid
=== 0 ) {
689 $rev = $this->mNewRev
->getPrevious();
691 $this->mOldid
= $rev->getId();
692 $this->mOldRev
= $rev;
694 // No previous revision; mark to show as first-version only.
695 $this->mOldid
= false;
696 $this->mOldRev
= false;
698 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
700 if( is_null( $this->mOldRev
) ) {
704 if ( $this->mOldRev
) {
705 $this->mOldPage
= $this->mOldRev
->getTitle();
707 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
708 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
709 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
710 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
712 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
713 . "(<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
714 // Add an "undo" link
715 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
716 if ( $this->mNewRev
->userCan(Revision
::DELETED_TEXT
) )
717 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
719 if ( !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
720 $this->mOldtitle
= "<span class='history-deleted'>{$this->mOldPagetitle}</span>";
721 } else if ( $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
722 $this->mOldtitle
= '<span class="history-deleted">'.$this->mOldtitle
.'</span>';
730 * Load the text of the revisions, as well as revision data.
732 function loadText() {
733 if ( $this->mTextLoaded
== 2 ) {
736 // Whether it succeeds or fails, we don't want to try again
737 $this->mTextLoaded
= 2;
740 if ( !$this->loadRevisionData() ) {
743 if ( $this->mOldRev
) {
744 $this->mOldtext
= $this->mOldRev
->revText();
745 if ( $this->mOldtext
=== false ) {
749 if ( $this->mNewRev
) {
750 $this->mNewtext
= $this->mNewRev
->revText();
751 if ( $this->mNewtext
=== false ) {
759 * Load the text of the new revision, not the old one
761 function loadNewText() {
762 if ( $this->mTextLoaded
>= 1 ) {
765 $this->mTextLoaded
= 1;
767 if ( !$this->loadRevisionData() ) {
770 $this->mNewtext
= $this->mNewRev
->getText();
777 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
779 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
780 // You may copy this code freely under the conditions of the GPL.
783 define('USE_ASSERTS', function_exists('assert'));
788 * @addtogroup DifferenceEngine
796 trigger_error('pure virtual', E_USER_ERROR
);
800 return $this->orig ?
sizeof($this->orig
) : 0;
803 function nclosing() {
804 return $this->closing ?
sizeof($this->closing
) : 0;
811 * @addtogroup DifferenceEngine
813 class _DiffOp_Copy
extends _DiffOp
{
816 function _DiffOp_Copy ($orig, $closing = false) {
817 if (!is_array($closing))
820 $this->closing
= $closing;
824 return new _DiffOp_Copy($this->closing
, $this->orig
);
831 * @addtogroup DifferenceEngine
833 class _DiffOp_Delete
extends _DiffOp
{
834 var $type = 'delete';
836 function _DiffOp_Delete ($lines) {
837 $this->orig
= $lines;
838 $this->closing
= false;
842 return new _DiffOp_Add($this->orig
);
849 * @addtogroup DifferenceEngine
851 class _DiffOp_Add
extends _DiffOp
{
854 function _DiffOp_Add ($lines) {
855 $this->closing
= $lines;
860 return new _DiffOp_Delete($this->closing
);
867 * @addtogroup DifferenceEngine
869 class _DiffOp_Change
extends _DiffOp
{
870 var $type = 'change';
872 function _DiffOp_Change ($orig, $closing) {
874 $this->closing
= $closing;
878 return new _DiffOp_Change($this->closing
, $this->orig
);
884 * Class used internally by Diff to actually compute the diffs.
886 * The algorithm used here is mostly lifted from the perl module
887 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
888 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
890 * More ideas are taken from:
891 * http://www.ics.uci.edu/~eppstein/161/960229.html
893 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
894 * diffutils-2.7, which can be found at:
895 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
897 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
900 * Line length limits for robustness added by Tim Starling, 2005-08-31
902 * @author Geoffrey T. Dairiki, Tim Starling
904 * @addtogroup DifferenceEngine
908 const MAX_XREF_LENGTH
= 10000;
910 function diff ($from_lines, $to_lines) {
911 $fname = '_DiffEngine::diff';
912 wfProfileIn( $fname );
914 $n_from = sizeof($from_lines);
915 $n_to = sizeof($to_lines);
917 $this->xchanged
= $this->ychanged
= array();
918 $this->xv
= $this->yv
= array();
919 $this->xind
= $this->yind
= array();
921 unset($this->in_seq
);
924 // Skip leading common lines.
925 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
926 if ($from_lines[$skip] !== $to_lines[$skip])
928 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
930 // Skip trailing common lines.
931 $xi = $n_from; $yi = $n_to;
932 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
933 if ($from_lines[$xi] !== $to_lines[$yi])
935 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
938 // Ignore lines which do not exist in both files.
939 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
940 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
943 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
944 $line = $to_lines[$yi];
945 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
947 $yhash[$this->_line_hash($line)] = 1;
951 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
952 $line = $from_lines[$xi];
953 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
960 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
962 // Merge edits when possible
963 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
964 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
966 // Compute the edit operations.
969 while ($xi < $n_from ||
$yi < $n_to) {
970 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
971 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
973 // Skip matching "snake".
975 while ( $xi < $n_from && $yi < $n_to
976 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
977 $copy[] = $from_lines[$xi++
];
981 $edits[] = new _DiffOp_Copy($copy);
983 // Find deletes & adds.
985 while ($xi < $n_from && $this->xchanged
[$xi])
986 $delete[] = $from_lines[$xi++
];
989 while ($yi < $n_to && $this->ychanged
[$yi])
990 $add[] = $to_lines[$yi++
];
993 $edits[] = new _DiffOp_Change($delete, $add);
995 $edits[] = new _DiffOp_Delete($delete);
997 $edits[] = new _DiffOp_Add($add);
999 wfProfileOut( $fname );
1004 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1006 function _line_hash( $line ) {
1007 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1008 return md5( $line );
1015 /* Divide the Largest Common Subsequence (LCS) of the sequences
1016 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1019 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1020 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1021 * sub sequences. The first sub-sequence is contained in [X0, X1),
1022 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1023 * that (X0, Y0) == (XOFF, YOFF) and
1024 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1026 * This function assumes that the first lines of the specified portions
1027 * of the two files do not match, and likewise that the last lines do not
1028 * match. The caller must trim matching lines from the beginning and end
1029 * of the portions it is going to specify.
1031 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1032 $fname = '_DiffEngine::_diag';
1033 wfProfileIn( $fname );
1036 if ($xlim - $xoff > $ylim - $yoff) {
1037 // Things seems faster (I'm not sure I understand why)
1038 // when the shortest sequence in X.
1040 list ($xoff, $xlim, $yoff, $ylim)
1041 = array( $yoff, $ylim, $xoff, $xlim);
1045 for ($i = $ylim - 1; $i >= $yoff; $i--)
1046 $ymatches[$this->xv
[$i]][] = $i;
1048 for ($i = $ylim - 1; $i >= $yoff; $i--)
1049 $ymatches[$this->yv
[$i]][] = $i;
1052 $this->seq
[0]= $yoff - 1;
1053 $this->in_seq
= array();
1054 $ymids[0] = array();
1056 $numer = $xlim - $xoff +
$nchunks - 1;
1058 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1059 wfProfileIn( "$fname-chunk" );
1061 for ($i = 0; $i <= $this->lcs
; $i++
)
1062 $ymids[$i][$chunk-1] = $this->seq
[$i];
1064 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1065 for ( ; $x < $x1; $x++
) {
1066 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1067 if (empty($ymatches[$line]))
1069 $matches = $ymatches[$line];
1071 while (list ($junk, $y) = each($matches))
1072 if (empty($this->in_seq
[$y])) {
1073 $k = $this->_lcs_pos($y);
1074 USE_ASSERTS
&& assert($k > 0);
1075 $ymids[$k] = $ymids[$k-1];
1078 while (list ( /* $junk */, $y) = each($matches)) {
1079 if ($y > $this->seq
[$k-1]) {
1080 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1081 // Optimization: this is a common case:
1082 // next match is just replacing previous match.
1083 $this->in_seq
[$this->seq
[$k]] = false;
1084 $this->seq
[$k] = $y;
1085 $this->in_seq
[$y] = 1;
1086 } else if (empty($this->in_seq
[$y])) {
1087 $k = $this->_lcs_pos($y);
1088 USE_ASSERTS
&& assert($k > 0);
1089 $ymids[$k] = $ymids[$k-1];
1093 wfProfileOut( "$fname-chunk" );
1096 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1097 $ymid = $ymids[$this->lcs
];
1098 for ($n = 0; $n < $nchunks - 1; $n++
) {
1099 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1100 $y1 = $ymid[$n] +
1;
1101 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1103 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1105 wfProfileOut( $fname );
1106 return array($this->lcs
, $seps);
1109 function _lcs_pos ($ypos) {
1110 $fname = '_DiffEngine::_lcs_pos';
1111 wfProfileIn( $fname );
1114 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1115 $this->seq
[++
$this->lcs
] = $ypos;
1116 $this->in_seq
[$ypos] = 1;
1117 wfProfileOut( $fname );
1122 while ($beg < $end) {
1123 $mid = (int)(($beg +
$end) / 2);
1124 if ( $ypos > $this->seq
[$mid] )
1130 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1132 $this->in_seq
[$this->seq
[$end]] = false;
1133 $this->seq
[$end] = $ypos;
1134 $this->in_seq
[$ypos] = 1;
1135 wfProfileOut( $fname );
1139 /* Find LCS of two sequences.
1141 * The results are recorded in the vectors $this->{x,y}changed[], by
1142 * storing a 1 in the element for each line that is an insertion
1143 * or deletion (ie. is not in the LCS).
1145 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1147 * Note that XLIM, YLIM are exclusive bounds.
1148 * All line numbers are origin-0 and discarded lines are not counted.
1150 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1151 $fname = '_DiffEngine::_compareseq';
1152 wfProfileIn( $fname );
1154 // Slide down the bottom initial diagonal.
1155 while ($xoff < $xlim && $yoff < $ylim
1156 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1161 // Slide up the top initial diagonal.
1162 while ($xlim > $xoff && $ylim > $yoff
1163 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1168 if ($xoff == $xlim ||
$yoff == $ylim)
1171 // This is ad hoc but seems to work well.
1172 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1173 //$nchunks = max(2,min(8,(int)$nchunks));
1174 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1176 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1180 // X and Y sequences have no common subsequence:
1181 // mark all changed.
1182 while ($yoff < $ylim)
1183 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1184 while ($xoff < $xlim)
1185 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1187 // Use the partitions to split this problem into subproblems.
1190 while ($pt2 = next($seps)) {
1191 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1195 wfProfileOut( $fname );
1198 /* Adjust inserts/deletes of identical lines to join changes
1199 * as much as possible.
1201 * We do something when a run of changed lines include a
1202 * line at one end and has an excluded, identical line at the other.
1203 * We are free to choose which identical line is included.
1204 * `compareseq' usually chooses the one at the beginning,
1205 * but usually it is cleaner to consider the following identical line
1206 * to be the "change".
1208 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1210 function _shift_boundaries ($lines, &$changed, $other_changed) {
1211 $fname = '_DiffEngine::_shift_boundaries';
1212 wfProfileIn( $fname );
1216 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1217 $len = sizeof($lines);
1218 $other_len = sizeof($other_changed);
1222 * Scan forwards to find beginning of another run of changes.
1223 * Also keep track of the corresponding point in the other file.
1225 * Throughout this code, $i and $j are adjusted together so that
1226 * the first $i elements of $changed and the first $j elements
1227 * of $other_changed both contain the same number of zeros
1228 * (unchanged lines).
1229 * Furthermore, $j is always kept so that $j == $other_len or
1230 * $other_changed[$j] == false.
1232 while ($j < $other_len && $other_changed[$j])
1235 while ($i < $len && ! $changed[$i]) {
1236 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1238 while ($j < $other_len && $other_changed[$j])
1247 // Find the end of this run of changes.
1248 while (++
$i < $len && $changed[$i])
1253 * Record the length of this run of changes, so that
1254 * we can later determine whether the run has grown.
1256 $runlength = $i - $start;
1259 * Move the changed region back, so long as the
1260 * previous unchanged line matches the last changed one.
1261 * This merges with previous changed regions.
1263 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1264 $changed[--$start] = 1;
1265 $changed[--$i] = false;
1266 while ($start > 0 && $changed[$start - 1])
1268 USE_ASSERTS
&& assert('$j > 0');
1269 while ($other_changed[--$j])
1271 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1275 * Set CORRESPONDING to the end of the changed run, at the last
1276 * point where it corresponds to a changed run in the other file.
1277 * CORRESPONDING == LEN means no such point has been found.
1279 $corresponding = $j < $other_len ?
$i : $len;
1282 * Move the changed region forward, so long as the
1283 * first changed line matches the following unchanged one.
1284 * This merges with following changed regions.
1285 * Do this second, so that if there are no merges,
1286 * the changed region is moved forward as far as possible.
1288 while ($i < $len && $lines[$start] == $lines[$i]) {
1289 $changed[$start++
] = false;
1291 while ($i < $len && $changed[$i])
1294 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1296 if ($j < $other_len && $other_changed[$j]) {
1297 $corresponding = $i;
1298 while ($j < $other_len && $other_changed[$j])
1302 } while ($runlength != $i - $start);
1305 * If possible, move the fully-merged run of changes
1306 * back to a corresponding run in the other file.
1308 while ($corresponding < $i) {
1309 $changed[--$start] = 1;
1311 USE_ASSERTS
&& assert('$j > 0');
1312 while ($other_changed[--$j])
1314 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1317 wfProfileOut( $fname );
1322 * Class representing a 'diff' between two sequences of strings.
1325 * @addtogroup DifferenceEngine
1333 * Computes diff between sequences of strings.
1335 * @param $from_lines array An array of strings.
1336 * (Typically these are lines from a file.)
1337 * @param $to_lines array An array of strings.
1339 function Diff($from_lines, $to_lines) {
1340 $eng = new _DiffEngine
;
1341 $this->edits
= $eng->diff($from_lines, $to_lines);
1342 //$this->_check($from_lines, $to_lines);
1346 * Compute reversed Diff.
1350 * $diff = new Diff($lines1, $lines2);
1351 * $rev = $diff->reverse();
1352 * @return object A Diff object representing the inverse of the
1355 function reverse () {
1357 $rev->edits
= array();
1358 foreach ($this->edits
as $edit) {
1359 $rev->edits
[] = $edit->reverse();
1365 * Check for empty diff.
1367 * @return bool True iff two sequences were identical.
1369 function isEmpty () {
1370 foreach ($this->edits
as $edit) {
1371 if ($edit->type
!= 'copy')
1378 * Compute the length of the Longest Common Subsequence (LCS).
1380 * This is mostly for diagnostic purposed.
1382 * @return int The length of the LCS.
1386 foreach ($this->edits
as $edit) {
1387 if ($edit->type
== 'copy')
1388 $lcs +
= sizeof($edit->orig
);
1394 * Get the original set of lines.
1396 * This reconstructs the $from_lines parameter passed to the
1399 * @return array The original sequence of strings.
1404 foreach ($this->edits
as $edit) {
1406 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1412 * Get the closing set of lines.
1414 * This reconstructs the $to_lines parameter passed to the
1417 * @return array The sequence of strings.
1419 function closing() {
1422 foreach ($this->edits
as $edit) {
1424 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1430 * Check a Diff for validity.
1432 * This is here only for debugging purposes.
1434 function _check ($from_lines, $to_lines) {
1435 $fname = 'Diff::_check';
1436 wfProfileIn( $fname );
1437 if (serialize($from_lines) != serialize($this->orig()))
1438 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1439 if (serialize($to_lines) != serialize($this->closing()))
1440 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1442 $rev = $this->reverse();
1443 if (serialize($to_lines) != serialize($rev->orig()))
1444 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1445 if (serialize($from_lines) != serialize($rev->closing()))
1446 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1450 foreach ($this->edits
as $edit) {
1451 if ( $prevtype == $edit->type
)
1452 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1453 $prevtype = $edit->type
;
1456 $lcs = $this->lcs();
1457 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1458 wfProfileOut( $fname );
1463 * @todo document, bad name.
1465 * @addtogroup DifferenceEngine
1467 class MappedDiff
extends Diff
1472 * Computes diff between sequences of strings.
1474 * This can be used to compute things like
1475 * case-insensitve diffs, or diffs which ignore
1476 * changes in white-space.
1478 * @param $from_lines array An array of strings.
1479 * (Typically these are lines from a file.)
1481 * @param $to_lines array An array of strings.
1483 * @param $mapped_from_lines array This array should
1484 * have the same size number of elements as $from_lines.
1485 * The elements in $mapped_from_lines and
1486 * $mapped_to_lines are what is actually compared
1487 * when computing the diff.
1489 * @param $mapped_to_lines array This array should
1490 * have the same number of elements as $to_lines.
1492 function MappedDiff($from_lines, $to_lines,
1493 $mapped_from_lines, $mapped_to_lines) {
1494 $fname = 'MappedDiff::MappedDiff';
1495 wfProfileIn( $fname );
1497 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1498 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1500 $this->Diff($mapped_from_lines, $mapped_to_lines);
1503 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1504 $orig = &$this->edits
[$i]->orig
;
1505 if (is_array($orig)) {
1506 $orig = array_slice($from_lines, $xi, sizeof($orig));
1507 $xi +
= sizeof($orig);
1510 $closing = &$this->edits
[$i]->closing
;
1511 if (is_array($closing)) {
1512 $closing = array_slice($to_lines, $yi, sizeof($closing));
1513 $yi +
= sizeof($closing);
1516 wfProfileOut( $fname );
1521 * A class to format Diffs
1523 * This class formats the diff in classic diff format.
1524 * It is intended that this class be customized via inheritance,
1525 * to obtain fancier outputs.
1528 * @addtogroup DifferenceEngine
1533 * Number of leading context "lines" to preserve.
1535 * This should be left at zero for this class, but subclasses
1536 * may want to set this to other values.
1538 var $leading_context_lines = 0;
1541 * Number of trailing context "lines" to preserve.
1543 * This should be left at zero for this class, but subclasses
1544 * may want to set this to other values.
1546 var $trailing_context_lines = 0;
1551 * @param $diff object A Diff object.
1552 * @return string The formatted output.
1554 function format($diff) {
1555 $fname = 'DiffFormatter::format';
1556 wfProfileIn( $fname );
1562 $nlead = $this->leading_context_lines
;
1563 $ntrail = $this->trailing_context_lines
;
1565 $this->_start_diff();
1567 foreach ($diff->edits
as $edit) {
1568 if ($edit->type
== 'copy') {
1569 if (is_array($block)) {
1570 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1575 $context = array_slice($edit->orig
, 0, $ntrail);
1576 $block[] = new _DiffOp_Copy($context);
1578 $this->_block($x0, $ntrail +
$xi - $x0,
1579 $y0, $ntrail +
$yi - $y0,
1584 $context = $edit->orig
;
1587 if (! is_array($block)) {
1588 $context = array_slice($context, sizeof($context) - $nlead);
1589 $x0 = $xi - sizeof($context);
1590 $y0 = $yi - sizeof($context);
1593 $block[] = new _DiffOp_Copy($context);
1599 $xi +
= sizeof($edit->orig
);
1601 $yi +
= sizeof($edit->closing
);
1604 if (is_array($block))
1605 $this->_block($x0, $xi - $x0,
1609 $end = $this->_end_diff();
1610 wfProfileOut( $fname );
1614 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1615 $fname = 'DiffFormatter::_block';
1616 wfProfileIn( $fname );
1617 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1618 foreach ($edits as $edit) {
1619 if ($edit->type
== 'copy')
1620 $this->_context($edit->orig
);
1621 elseif ($edit->type
== 'add')
1622 $this->_added($edit->closing
);
1623 elseif ($edit->type
== 'delete')
1624 $this->_deleted($edit->orig
);
1625 elseif ($edit->type
== 'change')
1626 $this->_changed($edit->orig
, $edit->closing
);
1628 trigger_error('Unknown edit type', E_USER_ERROR
);
1630 $this->_end_block();
1631 wfProfileOut( $fname );
1634 function _start_diff() {
1638 function _end_diff() {
1639 $val = ob_get_contents();
1644 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1646 $xbeg .= "," . ($xbeg +
$xlen - 1);
1648 $ybeg .= "," . ($ybeg +
$ylen - 1);
1650 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1653 function _start_block($header) {
1654 echo $header . "\n";
1657 function _end_block() {
1660 function _lines($lines, $prefix = ' ') {
1661 foreach ($lines as $line)
1662 echo "$prefix $line\n";
1665 function _context($lines) {
1666 $this->_lines($lines);
1669 function _added($lines) {
1670 $this->_lines($lines, '>');
1672 function _deleted($lines) {
1673 $this->_lines($lines, '<');
1676 function _changed($orig, $closing) {
1677 $this->_deleted($orig);
1679 $this->_added($closing);
1684 * A formatter that outputs unified diffs
1685 * @addtogroup DifferenceEngine
1688 class UnifiedDiffFormatter
extends DiffFormatter
1690 var $leading_context_lines = 2;
1691 var $trailing_context_lines = 2;
1693 function _added($lines) {
1694 $this->_lines($lines, '+');
1696 function _deleted($lines) {
1697 $this->_lines($lines, '-');
1699 function _changed($orig, $closing) {
1700 $this->_deleted($orig);
1701 $this->_added($closing);
1703 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1704 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1709 * A pseudo-formatter that just passes along the Diff::$edits array
1710 * @addtogroup DifferenceEngine
1712 class ArrayDiffFormatter
extends DiffFormatter
1714 function format($diff)
1719 foreach($diff->edits
as $edit)
1723 foreach($edit->closing
as $l)
1728 'newline' => $newline++
1733 foreach($edit->orig
as $l)
1736 'action' => 'delete',
1738 'oldline' => $oldline++
,
1743 foreach($edit->orig
as $i => $l)
1746 'action' => 'change',
1748 'new' => @$edit->closing
[$i],
1749 'oldline' => $oldline++
,
1750 'newline' => $newline++
,
1755 $oldline +
= count($edit->orig
);
1756 $newline +
= count($edit->orig
);
1763 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1767 define('NBSP', ' '); // iso-8859-x non-breaking space.
1772 * @addtogroup DifferenceEngine
1774 class _HWLDF_WordAccumulator
{
1775 function _HWLDF_WordAccumulator () {
1776 $this->_lines
= array();
1782 function _flushGroup ($new_tag) {
1783 if ($this->_group
!== '') {
1784 if ($this->_tag
== 'ins')
1785 $this->_line
.= '<ins class="diffchange">' .
1786 htmlspecialchars ( $this->_group
) . '</ins>';
1787 elseif ($this->_tag
== 'del')
1788 $this->_line
.= '<del class="diffchange">' .
1789 htmlspecialchars ( $this->_group
) . '</del>';
1791 $this->_line
.= htmlspecialchars ( $this->_group
);
1794 $this->_tag
= $new_tag;
1797 function _flushLine ($new_tag) {
1798 $this->_flushGroup($new_tag);
1799 if ($this->_line
!= '')
1800 array_push ( $this->_lines
, $this->_line
);
1802 # make empty lines visible by inserting an NBSP
1803 array_push ( $this->_lines
, NBSP
);
1807 function addWords ($words, $tag = '') {
1808 if ($tag != $this->_tag
)
1809 $this->_flushGroup($tag);
1811 foreach ($words as $word) {
1812 // new-line should only come as first char of word.
1815 if ($word[0] == "\n") {
1816 $this->_flushLine($tag);
1817 $word = substr($word, 1);
1819 assert(!strstr($word, "\n"));
1820 $this->_group
.= $word;
1824 function getLines() {
1825 $this->_flushLine('~done');
1826 return $this->_lines
;
1833 * @addtogroup DifferenceEngine
1835 class WordLevelDiff
extends MappedDiff
1837 const MAX_LINE_LENGTH
= 10000;
1839 function WordLevelDiff ($orig_lines, $closing_lines) {
1840 $fname = 'WordLevelDiff::WordLevelDiff';
1841 wfProfileIn( $fname );
1843 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1844 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1846 $this->MappedDiff($orig_words, $closing_words,
1847 $orig_stripped, $closing_stripped);
1848 wfProfileOut( $fname );
1851 function _split($lines) {
1852 $fname = 'WordLevelDiff::_split';
1853 wfProfileIn( $fname );
1856 $stripped = array();
1858 foreach ( $lines as $line ) {
1859 # If the line is too long, just pretend the entire line is one big word
1860 # This prevents resource exhaustion problems
1867 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1869 $stripped[] = $line;
1872 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1875 $words = array_merge( $words, $m[0] );
1876 $stripped = array_merge( $stripped, $m[1] );
1880 wfProfileOut( $fname );
1881 return array($words, $stripped);
1885 $fname = 'WordLevelDiff::orig';
1886 wfProfileIn( $fname );
1887 $orig = new _HWLDF_WordAccumulator
;
1889 foreach ($this->edits
as $edit) {
1890 if ($edit->type
== 'copy')
1891 $orig->addWords($edit->orig
);
1892 elseif ($edit->orig
)
1893 $orig->addWords($edit->orig
, 'del');
1895 $lines = $orig->getLines();
1896 wfProfileOut( $fname );
1900 function closing () {
1901 $fname = 'WordLevelDiff::closing';
1902 wfProfileIn( $fname );
1903 $closing = new _HWLDF_WordAccumulator
;
1905 foreach ($this->edits
as $edit) {
1906 if ($edit->type
== 'copy')
1907 $closing->addWords($edit->closing
);
1908 elseif ($edit->closing
)
1909 $closing->addWords($edit->closing
, 'ins');
1911 $lines = $closing->getLines();
1912 wfProfileOut( $fname );
1918 * Wikipedia Table style diff formatter.
1921 * @addtogroup DifferenceEngine
1923 class TableDiffFormatter
extends DiffFormatter
1925 function TableDiffFormatter() {
1926 $this->leading_context_lines
= 2;
1927 $this->trailing_context_lines
= 2;
1930 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1931 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1932 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1936 function _start_block( $header ) {
1940 function _end_block() {
1943 function _lines( $lines, $prefix=' ', $color='white' ) {
1946 # HTML-escape parameter before calling this
1947 function addedLine( $line ) {
1948 return $this->wrapLine( '+', 'diff-addedline', $line );
1951 # HTML-escape parameter before calling this
1952 function deletedLine( $line ) {
1953 return $this->wrapLine( '-', 'diff-deletedline', $line );
1956 # HTML-escape parameter before calling this
1957 function contextLine( $line ) {
1958 return $this->wrapLine( ' ', 'diff-context', $line );
1961 private function wrapLine( $marker, $class, $line ) {
1962 if( $line !== '' ) {
1963 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1964 $line = "<div>$line</div>";
1966 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1969 function emptyLine() {
1970 return '<td colspan="2"> </td>';
1973 function _added( $lines ) {
1974 foreach ($lines as $line) {
1975 echo '<tr>' . $this->emptyLine() .
1976 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1980 function _deleted($lines) {
1981 foreach ($lines as $line) {
1982 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1983 $this->emptyLine() . "</tr>\n";
1987 function _context( $lines ) {
1988 foreach ($lines as $line) {
1990 $this->contextLine( htmlspecialchars ( $line ) ) .
1991 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1995 function _changed( $orig, $closing ) {
1996 $fname = 'TableDiffFormatter::_changed';
1997 wfProfileIn( $fname );
1999 $diff = new WordLevelDiff( $orig, $closing );
2000 $del = $diff->orig();
2001 $add = $diff->closing();
2003 # Notice that WordLevelDiff returns HTML-escaped output.
2004 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2006 while ( $line = array_shift( $del ) ) {
2007 $aline = array_shift( $add );
2008 echo '<tr>' . $this->deletedLine( $line ) .
2009 $this->addedLine( $aline ) . "</tr>\n";
2011 foreach ($add as $line) { # If any leftovers
2012 echo '<tr>' . $this->emptyLine() .
2013 $this->addedLine( $line ) . "</tr>\n";
2015 wfProfileOut( $fname );