4 * @todo indicate where diff.doc can be found.
5 * @addtogroup DifferenceEngine
9 * Constant to indicate diff cache compatibility.
10 * Bump this when changing the diff formatting in a way that
11 * fixes important bugs or such to force cached diff views to
14 define( 'MW_DIFF_VERSION', '1.11a' );
19 * @addtogroup DifferenceEngine
21 class DifferenceEngine
{
25 var $mOldid, $mNewid, $mTitle;
26 var $mOldtitle, $mNewtitle, $mPagetitle;
27 var $mOldtext, $mNewtext;
28 var $mOldPage, $mNewPage;
29 var $mRcidMarkPatrolled;
30 var $mOldRev, $mNewRev;
31 var $mRevisionsLoaded = false; // Have the revisions been loaded
32 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
37 * @param $titleObj Title object that the diff is associated with
38 * @param $old Integer: old ID we want to show and diff with.
39 * @param $new String: either 'prev' or 'next'.
40 * @param $rcid Integer: ??? FIXME (default 0)
41 * @param $refreshCache boolean If set, refreshes the diff cache
43 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false ) {
44 $this->mTitle
= $titleObj;
45 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
47 if ( 'prev' === $new ) {
48 # Show diff between revision $old and the previous one.
49 # Get previous one from DB.
51 $this->mNewid
= intval($old);
53 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
55 } elseif ( 'next' === $new ) {
56 # Show diff between revision $old and the previous one.
57 # Get previous one from DB.
59 $this->mOldid
= intval($old);
60 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
61 if ( false === $this->mNewid
) {
62 # if no result, NewId points to the newest old revision. The only newer
63 # revision is cur, which is "0".
68 $this->mOldid
= intval($old);
69 $this->mNewid
= intval($new);
71 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
72 $this->mRefreshCache
= $refreshCache;
75 function showDiffPage( $diffOnly = false ) {
76 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
77 $fname = 'DifferenceEngine::showDiffPage';
78 wfProfileIn( $fname );
80 # If external diffs are enabled both globally and for the user,
81 # we'll use the application/x-external-editor interface to call
82 # an external diff tool like kompare, kdiff3, etc.
83 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
84 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
86 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
87 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
88 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
89 $special=$wgLang->getNsText(NS_SPECIAL
);
94 Script={$wgServer}{$wgScript}
95 Special namespace={$special}
109 $wgOut->setArticleFlag( false );
110 if ( ! $this->loadRevisionData() ) {
111 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
112 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
113 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
114 wfProfileOut( $fname );
118 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
120 if ( $this->mNewRev
->isCurrent() ) {
121 $wgOut->setArticleFlag( true );
124 # mOldid is false if the difference engine is called with a "vague" query for
125 # a diff between a version V and its previous version V' AND the version V
126 # is the first version of that article. In that case, V' does not exist.
127 if ( $this->mOldid
=== false ) {
128 $this->showFirstRevision();
129 $this->renderNewRevision(); // should we respect $diffOnly here or not?
130 wfProfileOut( $fname );
134 $wgOut->suppressQuickbar();
136 $oldTitle = $this->mOldPage
->getPrefixedText();
137 $newTitle = $this->mNewPage
->getPrefixedText();
138 if( $oldTitle == $newTitle ) {
139 $wgOut->setPageTitle( $newTitle );
141 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
143 $wgOut->setSubtitle( wfMsg( 'difference' ) );
144 $wgOut->setRobotpolicy( 'noindex,nofollow' );
146 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
147 $wgOut->loginToUse();
149 wfProfileOut( $fname );
153 $sk = $wgUser->getSkin();
155 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
156 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
161 // Prepare a change patrol link, if applicable
162 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
163 // If we've been given an explicit change identifier, use it; saves time
164 if( $this->mRcidMarkPatrolled
) {
165 $rcid = $this->mRcidMarkPatrolled
;
167 // Look for an unpatrolled change corresponding to this diff
168 $db = wfGetDB( DB_SLAVE
);
169 $change = RecentChange
::newFromConds(
171 // Add redundant user,timestamp condition so we can use the existing index
172 'rc_user_text' => $this->mNewRev
->getRawUserText(),
173 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
174 'rc_this_oldid' => $this->mNewid
,
175 'rc_last_oldid' => $this->mOldid
,
180 if( $change instanceof RecentChange
) {
181 $rcid = $change->mAttribs
['rc_id'];
189 $patrol = ' [' . $sk->makeKnownLinkObj(
191 wfMsgHtml( 'markaspatrolleddiff' ),
192 "action=markpatrolled&rcid={$rcid}"
201 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
202 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
203 if ( $this->mNewRev
->isCurrent() ) {
204 $nextlink = ' ';
206 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
207 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
213 if ($this->mOldRev
->mMinorEdit
== 1) {
214 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
215 wfMsg( 'minoreditletter') ) . ' ';
218 if ($this->mNewRev
->mMinorEdit
== 1) {
219 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
220 wfMsg( 'minoreditletter') ) . ' ';
223 $rdel = ''; $ldel = '';
224 if( $wgUser->isAllowed( 'deleterevision' ) ) {
225 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
226 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
227 // If revision was hidden from sysops
228 $ldel = wfMsgHtml('rev-delundel');
230 $ldel = $sk->makeKnownLinkObj( $revdel,
231 wfMsgHtml('rev-delundel'),
232 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
233 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
234 // Bolden oversighted content
235 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
236 $ldel = "<strong>$ldel</strong>";
238 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
239 // We don't currently handle well changing the top revision's settings
240 if( $this->mNewRev
->isCurrent() ) {
241 // If revision was hidden from sysops
242 $rdel = wfMsgHtml('rev-delundel');
243 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
244 // If revision was hidden from sysops
245 $rdel = wfMsgHtml('rev-delundel');
247 $rdel = $sk->makeKnownLinkObj( $revdel,
248 wfMsgHtml('rev-delundel'),
249 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
250 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
251 // Bolden oversighted content
252 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
253 $rdel = "<strong>$rdel</strong>";
255 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
258 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
259 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
260 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
261 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
262 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
263 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
264 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
265 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
267 $this->showDiff( $oldHeader, $newHeader );
270 $this->renderNewRevision();
272 wfProfileOut( $fname );
276 * Show the new revision of the page.
278 function renderNewRevision() {
280 $fname = 'DifferenceEngine::renderNewRevision';
281 wfProfileIn( $fname );
283 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
284 #add deleted rev tag if needed
285 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
286 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
287 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
288 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
291 if( !$this->mNewRev
->isCurrent() ) {
292 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
295 $this->loadNewText();
296 if( is_object( $this->mNewRev
) ) {
297 $wgOut->setRevisionId( $this->mNewRev
->getId() );
300 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
301 // Stolen from Article::view --AG 2007-10-11
303 // Give hooks a chance to customise the output
304 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
305 // Wrap the whole lot in a <pre> and don't parse
307 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
308 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
309 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
310 $wgOut->addHtml( "\n</pre>\n" );
313 $wgOut->addWikiTextTidy( $this->mNewtext
);
315 if( !$this->mNewRev
->isCurrent() ) {
316 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
319 wfProfileOut( $fname );
323 * Show the first revision of an article. Uses normal diff headers in
324 * contrast to normal "old revision" display style.
326 function showFirstRevision() {
327 global $wgOut, $wgUser;
329 $fname = 'DifferenceEngine::showFirstRevision';
330 wfProfileIn( $fname );
332 # Get article text from the DB
334 if ( ! $this->loadNewText() ) {
335 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
337 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
338 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
339 wfProfileOut( $fname );
342 if ( $this->mNewRev
->isCurrent() ) {
343 $wgOut->setArticleFlag( true );
346 # Check if user is allowed to look at this page. If not, bail out.
348 if ( !( $this->mTitle
->userCanRead() ) ) {
349 $wgOut->loginToUse();
351 wfProfileOut( $fname );
355 # Prepare the header box
357 $sk = $wgUser->getSkin();
359 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
360 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
361 $sk->revUserTools( $this->mNewRev
) . "<br />" .
362 $sk->revComment( $this->mNewRev
) . "<br />" .
363 $nextlink . "</div>\n";
365 $wgOut->addHTML( $header );
367 $wgOut->setSubtitle( wfMsg( 'difference' ) );
368 $wgOut->setRobotpolicy( 'noindex,nofollow' );
370 wfProfileOut( $fname );
374 * Get the diff text, send it to $wgOut
375 * Returns false if the diff could not be generated, otherwise returns true
377 function showDiff( $otitle, $ntitle ) {
379 $diff = $this->getDiff( $otitle, $ntitle );
380 if ( $diff === false ) {
381 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" );
384 $this->showDiffStyle();
385 $wgOut->addHTML( $diff );
391 * Add style sheets and supporting JS for diff display.
393 function showDiffStyle() {
394 global $wgStylePath, $wgStyleVersion, $wgOut;
395 $wgOut->addStyle( 'common/diff.css' );
397 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
398 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
402 * Get complete diff table, including header
404 * @param Title $otitle Old title
405 * @param Title $ntitle New title
408 function getDiff( $otitle, $ntitle ) {
409 $body = $this->getDiffBody();
410 if ( $body === false ) {
413 $multi = $this->getMultiNotice();
414 return $this->addHeader( $body, $otitle, $ntitle, $multi );
419 * Get the diff table body, without header
423 function getDiffBody() {
425 $fname = 'DifferenceEngine::getDiffBody';
426 wfProfileIn( $fname );
430 if ( $this->mOldid
&& $this->mNewid
) {
431 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
433 if ( !$this->mRefreshCache
) {
434 $difftext = $wgMemc->get( $key );
436 wfIncrStats( 'diff_cache_hit' );
437 $difftext = $this->localiseLineNumbers( $difftext );
438 $difftext .= "\n<!-- diff cache key $key -->\n";
439 wfProfileOut( $fname );
442 } // don't try to load but save the result
445 // Loadtext is permission safe, this just clears out the diff
446 if ( !$this->loadText() ) {
447 wfProfileOut( $fname );
449 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
451 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
455 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
457 // Save to cache for 7 days
458 // Only do this for public revs, otherwise an admin can view the diff and a non-admin can nab it!
459 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
460 wfIncrStats( 'diff_uncacheable' );
461 } else if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
462 wfIncrStats( 'diff_uncacheable' );
463 } else if ( $key !== false && $difftext !== false ) {
464 wfIncrStats( 'diff_cache_miss' );
465 $wgMemc->set( $key, $difftext, 7*86400 );
467 wfIncrStats( 'diff_uncacheable' );
469 // Replace line numbers with the text in the user's language
470 if ( $difftext !== false ) {
471 $difftext = $this->localiseLineNumbers( $difftext );
473 wfProfileOut( $fname );
478 * Generate a diff, no caching
479 * $otext and $ntext must be already segmented
481 function generateDiffBody( $otext, $ntext ) {
482 global $wgExternalDiffEngine, $wgContLang;
483 $fname = 'DifferenceEngine::generateDiffBody';
485 $otext = str_replace( "\r\n", "\n", $otext );
486 $ntext = str_replace( "\r\n", "\n", $ntext );
488 if ( $wgExternalDiffEngine == 'wikidiff' ) {
489 # For historical reasons, external diff engine expects
490 # input text to be HTML-escaped already
491 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
492 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
493 if( !function_exists( 'wikidiff_do_diff' ) ) {
494 dl('php_wikidiff.so');
496 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
499 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
500 # Better external diff engine, the 2 may some day be dropped
501 # This one does the escaping and segmenting itself
502 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
503 wfProfileIn( "$fname-dl" );
504 @dl
('php_wikidiff2.so');
505 wfProfileOut( "$fname-dl" );
507 if ( function_exists( 'wikidiff2_do_diff' ) ) {
508 wfProfileIn( 'wikidiff2_do_diff' );
509 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
510 wfProfileOut( 'wikidiff2_do_diff' );
514 if ( $wgExternalDiffEngine !== false ) {
516 global $wgTmpDirectory;
517 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
518 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
520 $tempFile1 = fopen( $tempName1, "w" );
522 wfProfileOut( $fname );
525 $tempFile2 = fopen( $tempName2, "w" );
527 wfProfileOut( $fname );
530 fwrite( $tempFile1, $otext );
531 fwrite( $tempFile2, $ntext );
532 fclose( $tempFile1 );
533 fclose( $tempFile2 );
534 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
535 wfProfileIn( "$fname-shellexec" );
536 $difftext = wfShellExec( $cmd );
537 wfProfileOut( "$fname-shellexec" );
538 unlink( $tempName1 );
539 unlink( $tempName2 );
544 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
545 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
546 $diffs = new Diff( $ota, $nta );
547 $formatter = new TableDiffFormatter();
548 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
553 * Replace line numbers with the text in the user's language
555 function localiseLineNumbers( $text ) {
556 return preg_replace_callback( '/<!--LINE (\d+)-->/',
557 array( &$this, 'localiseLineNumbersCb' ), $text );
560 function localiseLineNumbersCb( $matches ) {
562 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
567 * If there are revisions between the ones being compared, return a note saying so.
569 function getMultiNotice() {
570 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
573 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
574 // Comparing two different pages? Count would be meaningless.
578 $oldid = $this->mOldRev
->getId();
579 $newid = $this->mNewRev
->getId();
580 if ( $oldid > $newid ) {
581 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
584 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
588 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
593 * Add the header to a diff body
595 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
600 <col class='diff-marker' />
601 <col class='diff-content' />
602 <col class='diff-marker' />
603 <col class='diff-content' />
605 <td colspan='2' class='diff-otitle'>{$otitle}</td>
606 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
611 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
613 return $header . $diff . "</table>";
617 * Use specified text instead of loading from the database
619 function setText( $oldText, $newText ) {
620 $this->mOldtext
= $oldText;
621 $this->mNewtext
= $newText;
622 $this->mTextLoaded
= 2;
626 * Load revision metadata for the specified articles. If newid is 0, then compare
627 * the old article in oldid to the current article; if oldid is 0, then
628 * compare the current article to the immediately previous one (ignoring the
631 * If oldid is false, leave the corresponding revision object set
632 * to false. This is impossible via ordinary user input, and is provided for
635 function loadRevisionData() {
637 if ( $this->mRevisionsLoaded
) {
640 // Whether it succeeds or fails, we don't want to try again
641 $this->mRevisionsLoaded
= true;
644 // Load the new revision object
645 $this->mNewRev
= $this->mNewid
646 ? Revision
::newFromId( $this->mNewid
)
647 : Revision
::newFromTitle( $this->mTitle
);
648 if( !$this->mNewRev
instanceof Revision
)
651 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
652 $this->mNewid
= $this->mNewRev
->getId();
654 // Set assorted variables
655 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
656 $this->mNewPage
= $this->mNewRev
->getTitle();
657 if( $this->mNewRev
->isCurrent() ) {
658 $newLink = $this->mNewPage
->escapeLocalUrl();
659 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
660 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
662 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
663 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
666 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
667 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
668 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
670 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
671 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
673 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
674 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
675 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
676 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
679 // Load the old revision object
680 $this->mOldRev
= false;
681 if( $this->mOldid
) {
682 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
683 } elseif ( $this->mOldid
=== 0 ) {
684 $rev = $this->mNewRev
->getPrevious();
686 $this->mOldid
= $rev->getId();
687 $this->mOldRev
= $rev;
689 // No previous revision; mark to show as first-version only.
690 $this->mOldid
= false;
691 $this->mOldRev
= false;
693 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
695 if( is_null( $this->mOldRev
) ) {
699 if ( $this->mOldRev
) {
700 $this->mOldPage
= $this->mOldRev
->getTitle();
702 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
703 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
704 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
705 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
707 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
708 . " (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
709 // Add an "undo" link
710 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
711 if ( $this->mNewRev
->userCan(Revision
::DELETED_TEXT
) )
712 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
714 if ( !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
715 $this->mOldtitle
= "<span class='history-deleted'>{$this->mOldPagetitle}</span>";
716 } else if ( $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
717 $this->mOldtitle
= '<span class="history-deleted">'.$this->mOldtitle
.'</span>';
725 * Load the text of the revisions, as well as revision data.
727 function loadText() {
728 if ( $this->mTextLoaded
== 2 ) {
731 // Whether it succeeds or fails, we don't want to try again
732 $this->mTextLoaded
= 2;
735 if ( !$this->loadRevisionData() ) {
738 if ( $this->mOldRev
) {
739 $this->mOldtext
= $this->mOldRev
->revText();
740 if ( $this->mOldtext
=== false ) {
744 if ( $this->mNewRev
) {
745 $this->mNewtext
= $this->mNewRev
->revText();
746 if ( $this->mNewtext
=== false ) {
754 * Load the text of the new revision, not the old one
756 function loadNewText() {
757 if ( $this->mTextLoaded
>= 1 ) {
760 $this->mTextLoaded
= 1;
762 if ( !$this->loadRevisionData() ) {
765 $this->mNewtext
= $this->mNewRev
->getText();
772 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
774 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
775 // You may copy this code freely under the conditions of the GPL.
778 define('USE_ASSERTS', function_exists('assert'));
783 * @addtogroup DifferenceEngine
791 trigger_error('pure virtual', E_USER_ERROR
);
795 return $this->orig ?
sizeof($this->orig
) : 0;
798 function nclosing() {
799 return $this->closing ?
sizeof($this->closing
) : 0;
806 * @addtogroup DifferenceEngine
808 class _DiffOp_Copy
extends _DiffOp
{
811 function _DiffOp_Copy ($orig, $closing = false) {
812 if (!is_array($closing))
815 $this->closing
= $closing;
819 return new _DiffOp_Copy($this->closing
, $this->orig
);
826 * @addtogroup DifferenceEngine
828 class _DiffOp_Delete
extends _DiffOp
{
829 var $type = 'delete';
831 function _DiffOp_Delete ($lines) {
832 $this->orig
= $lines;
833 $this->closing
= false;
837 return new _DiffOp_Add($this->orig
);
844 * @addtogroup DifferenceEngine
846 class _DiffOp_Add
extends _DiffOp
{
849 function _DiffOp_Add ($lines) {
850 $this->closing
= $lines;
855 return new _DiffOp_Delete($this->closing
);
862 * @addtogroup DifferenceEngine
864 class _DiffOp_Change
extends _DiffOp
{
865 var $type = 'change';
867 function _DiffOp_Change ($orig, $closing) {
869 $this->closing
= $closing;
873 return new _DiffOp_Change($this->closing
, $this->orig
);
879 * Class used internally by Diff to actually compute the diffs.
881 * The algorithm used here is mostly lifted from the perl module
882 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
883 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
885 * More ideas are taken from:
886 * http://www.ics.uci.edu/~eppstein/161/960229.html
888 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
889 * diffutils-2.7, which can be found at:
890 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
892 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
895 * Line length limits for robustness added by Tim Starling, 2005-08-31
897 * @author Geoffrey T. Dairiki, Tim Starling
899 * @addtogroup DifferenceEngine
903 const MAX_XREF_LENGTH
= 10000;
905 function diff ($from_lines, $to_lines) {
906 $fname = '_DiffEngine::diff';
907 wfProfileIn( $fname );
909 $n_from = sizeof($from_lines);
910 $n_to = sizeof($to_lines);
912 $this->xchanged
= $this->ychanged
= array();
913 $this->xv
= $this->yv
= array();
914 $this->xind
= $this->yind
= array();
916 unset($this->in_seq
);
919 // Skip leading common lines.
920 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
921 if ($from_lines[$skip] !== $to_lines[$skip])
923 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
925 // Skip trailing common lines.
926 $xi = $n_from; $yi = $n_to;
927 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
928 if ($from_lines[$xi] !== $to_lines[$yi])
930 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
933 // Ignore lines which do not exist in both files.
934 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
935 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
938 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
939 $line = $to_lines[$yi];
940 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
942 $yhash[$this->_line_hash($line)] = 1;
946 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
947 $line = $from_lines[$xi];
948 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
955 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
957 // Merge edits when possible
958 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
959 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
961 // Compute the edit operations.
964 while ($xi < $n_from ||
$yi < $n_to) {
965 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
966 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
968 // Skip matching "snake".
970 while ( $xi < $n_from && $yi < $n_to
971 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
972 $copy[] = $from_lines[$xi++
];
976 $edits[] = new _DiffOp_Copy($copy);
978 // Find deletes & adds.
980 while ($xi < $n_from && $this->xchanged
[$xi])
981 $delete[] = $from_lines[$xi++
];
984 while ($yi < $n_to && $this->ychanged
[$yi])
985 $add[] = $to_lines[$yi++
];
988 $edits[] = new _DiffOp_Change($delete, $add);
990 $edits[] = new _DiffOp_Delete($delete);
992 $edits[] = new _DiffOp_Add($add);
994 wfProfileOut( $fname );
999 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1001 function _line_hash( $line ) {
1002 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1003 return md5( $line );
1010 /* Divide the Largest Common Subsequence (LCS) of the sequences
1011 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1014 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1015 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1016 * sub sequences. The first sub-sequence is contained in [X0, X1),
1017 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1018 * that (X0, Y0) == (XOFF, YOFF) and
1019 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1021 * This function assumes that the first lines of the specified portions
1022 * of the two files do not match, and likewise that the last lines do not
1023 * match. The caller must trim matching lines from the beginning and end
1024 * of the portions it is going to specify.
1026 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1027 $fname = '_DiffEngine::_diag';
1028 wfProfileIn( $fname );
1031 if ($xlim - $xoff > $ylim - $yoff) {
1032 // Things seems faster (I'm not sure I understand why)
1033 // when the shortest sequence in X.
1035 list ($xoff, $xlim, $yoff, $ylim)
1036 = array( $yoff, $ylim, $xoff, $xlim);
1040 for ($i = $ylim - 1; $i >= $yoff; $i--)
1041 $ymatches[$this->xv
[$i]][] = $i;
1043 for ($i = $ylim - 1; $i >= $yoff; $i--)
1044 $ymatches[$this->yv
[$i]][] = $i;
1047 $this->seq
[0]= $yoff - 1;
1048 $this->in_seq
= array();
1049 $ymids[0] = array();
1051 $numer = $xlim - $xoff +
$nchunks - 1;
1053 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1054 wfProfileIn( "$fname-chunk" );
1056 for ($i = 0; $i <= $this->lcs
; $i++
)
1057 $ymids[$i][$chunk-1] = $this->seq
[$i];
1059 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1060 for ( ; $x < $x1; $x++
) {
1061 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1062 if (empty($ymatches[$line]))
1064 $matches = $ymatches[$line];
1066 while (list ($junk, $y) = each($matches))
1067 if (empty($this->in_seq
[$y])) {
1068 $k = $this->_lcs_pos($y);
1069 USE_ASSERTS
&& assert($k > 0);
1070 $ymids[$k] = $ymids[$k-1];
1073 while (list ( /* $junk */, $y) = each($matches)) {
1074 if ($y > $this->seq
[$k-1]) {
1075 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1076 // Optimization: this is a common case:
1077 // next match is just replacing previous match.
1078 $this->in_seq
[$this->seq
[$k]] = false;
1079 $this->seq
[$k] = $y;
1080 $this->in_seq
[$y] = 1;
1081 } else if (empty($this->in_seq
[$y])) {
1082 $k = $this->_lcs_pos($y);
1083 USE_ASSERTS
&& assert($k > 0);
1084 $ymids[$k] = $ymids[$k-1];
1088 wfProfileOut( "$fname-chunk" );
1091 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1092 $ymid = $ymids[$this->lcs
];
1093 for ($n = 0; $n < $nchunks - 1; $n++
) {
1094 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1095 $y1 = $ymid[$n] +
1;
1096 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1098 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1100 wfProfileOut( $fname );
1101 return array($this->lcs
, $seps);
1104 function _lcs_pos ($ypos) {
1105 $fname = '_DiffEngine::_lcs_pos';
1106 wfProfileIn( $fname );
1109 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1110 $this->seq
[++
$this->lcs
] = $ypos;
1111 $this->in_seq
[$ypos] = 1;
1112 wfProfileOut( $fname );
1117 while ($beg < $end) {
1118 $mid = (int)(($beg +
$end) / 2);
1119 if ( $ypos > $this->seq
[$mid] )
1125 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1127 $this->in_seq
[$this->seq
[$end]] = false;
1128 $this->seq
[$end] = $ypos;
1129 $this->in_seq
[$ypos] = 1;
1130 wfProfileOut( $fname );
1134 /* Find LCS of two sequences.
1136 * The results are recorded in the vectors $this->{x,y}changed[], by
1137 * storing a 1 in the element for each line that is an insertion
1138 * or deletion (ie. is not in the LCS).
1140 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1142 * Note that XLIM, YLIM are exclusive bounds.
1143 * All line numbers are origin-0 and discarded lines are not counted.
1145 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1146 $fname = '_DiffEngine::_compareseq';
1147 wfProfileIn( $fname );
1149 // Slide down the bottom initial diagonal.
1150 while ($xoff < $xlim && $yoff < $ylim
1151 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1156 // Slide up the top initial diagonal.
1157 while ($xlim > $xoff && $ylim > $yoff
1158 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1163 if ($xoff == $xlim ||
$yoff == $ylim)
1166 // This is ad hoc but seems to work well.
1167 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1168 //$nchunks = max(2,min(8,(int)$nchunks));
1169 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1171 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1175 // X and Y sequences have no common subsequence:
1176 // mark all changed.
1177 while ($yoff < $ylim)
1178 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1179 while ($xoff < $xlim)
1180 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1182 // Use the partitions to split this problem into subproblems.
1185 while ($pt2 = next($seps)) {
1186 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1190 wfProfileOut( $fname );
1193 /* Adjust inserts/deletes of identical lines to join changes
1194 * as much as possible.
1196 * We do something when a run of changed lines include a
1197 * line at one end and has an excluded, identical line at the other.
1198 * We are free to choose which identical line is included.
1199 * `compareseq' usually chooses the one at the beginning,
1200 * but usually it is cleaner to consider the following identical line
1201 * to be the "change".
1203 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1205 function _shift_boundaries ($lines, &$changed, $other_changed) {
1206 $fname = '_DiffEngine::_shift_boundaries';
1207 wfProfileIn( $fname );
1211 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1212 $len = sizeof($lines);
1213 $other_len = sizeof($other_changed);
1217 * Scan forwards to find beginning of another run of changes.
1218 * Also keep track of the corresponding point in the other file.
1220 * Throughout this code, $i and $j are adjusted together so that
1221 * the first $i elements of $changed and the first $j elements
1222 * of $other_changed both contain the same number of zeros
1223 * (unchanged lines).
1224 * Furthermore, $j is always kept so that $j == $other_len or
1225 * $other_changed[$j] == false.
1227 while ($j < $other_len && $other_changed[$j])
1230 while ($i < $len && ! $changed[$i]) {
1231 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1233 while ($j < $other_len && $other_changed[$j])
1242 // Find the end of this run of changes.
1243 while (++
$i < $len && $changed[$i])
1248 * Record the length of this run of changes, so that
1249 * we can later determine whether the run has grown.
1251 $runlength = $i - $start;
1254 * Move the changed region back, so long as the
1255 * previous unchanged line matches the last changed one.
1256 * This merges with previous changed regions.
1258 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1259 $changed[--$start] = 1;
1260 $changed[--$i] = false;
1261 while ($start > 0 && $changed[$start - 1])
1263 USE_ASSERTS
&& assert('$j > 0');
1264 while ($other_changed[--$j])
1266 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1270 * Set CORRESPONDING to the end of the changed run, at the last
1271 * point where it corresponds to a changed run in the other file.
1272 * CORRESPONDING == LEN means no such point has been found.
1274 $corresponding = $j < $other_len ?
$i : $len;
1277 * Move the changed region forward, so long as the
1278 * first changed line matches the following unchanged one.
1279 * This merges with following changed regions.
1280 * Do this second, so that if there are no merges,
1281 * the changed region is moved forward as far as possible.
1283 while ($i < $len && $lines[$start] == $lines[$i]) {
1284 $changed[$start++
] = false;
1286 while ($i < $len && $changed[$i])
1289 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1291 if ($j < $other_len && $other_changed[$j]) {
1292 $corresponding = $i;
1293 while ($j < $other_len && $other_changed[$j])
1297 } while ($runlength != $i - $start);
1300 * If possible, move the fully-merged run of changes
1301 * back to a corresponding run in the other file.
1303 while ($corresponding < $i) {
1304 $changed[--$start] = 1;
1306 USE_ASSERTS
&& assert('$j > 0');
1307 while ($other_changed[--$j])
1309 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1312 wfProfileOut( $fname );
1317 * Class representing a 'diff' between two sequences of strings.
1320 * @addtogroup DifferenceEngine
1328 * Computes diff between sequences of strings.
1330 * @param $from_lines array An array of strings.
1331 * (Typically these are lines from a file.)
1332 * @param $to_lines array An array of strings.
1334 function Diff($from_lines, $to_lines) {
1335 $eng = new _DiffEngine
;
1336 $this->edits
= $eng->diff($from_lines, $to_lines);
1337 //$this->_check($from_lines, $to_lines);
1341 * Compute reversed Diff.
1345 * $diff = new Diff($lines1, $lines2);
1346 * $rev = $diff->reverse();
1347 * @return object A Diff object representing the inverse of the
1350 function reverse () {
1352 $rev->edits
= array();
1353 foreach ($this->edits
as $edit) {
1354 $rev->edits
[] = $edit->reverse();
1360 * Check for empty diff.
1362 * @return bool True iff two sequences were identical.
1364 function isEmpty () {
1365 foreach ($this->edits
as $edit) {
1366 if ($edit->type
!= 'copy')
1373 * Compute the length of the Longest Common Subsequence (LCS).
1375 * This is mostly for diagnostic purposed.
1377 * @return int The length of the LCS.
1381 foreach ($this->edits
as $edit) {
1382 if ($edit->type
== 'copy')
1383 $lcs +
= sizeof($edit->orig
);
1389 * Get the original set of lines.
1391 * This reconstructs the $from_lines parameter passed to the
1394 * @return array The original sequence of strings.
1399 foreach ($this->edits
as $edit) {
1401 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1407 * Get the closing set of lines.
1409 * This reconstructs the $to_lines parameter passed to the
1412 * @return array The sequence of strings.
1414 function closing() {
1417 foreach ($this->edits
as $edit) {
1419 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1425 * Check a Diff for validity.
1427 * This is here only for debugging purposes.
1429 function _check ($from_lines, $to_lines) {
1430 $fname = 'Diff::_check';
1431 wfProfileIn( $fname );
1432 if (serialize($from_lines) != serialize($this->orig()))
1433 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1434 if (serialize($to_lines) != serialize($this->closing()))
1435 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1437 $rev = $this->reverse();
1438 if (serialize($to_lines) != serialize($rev->orig()))
1439 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1440 if (serialize($from_lines) != serialize($rev->closing()))
1441 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1445 foreach ($this->edits
as $edit) {
1446 if ( $prevtype == $edit->type
)
1447 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1448 $prevtype = $edit->type
;
1451 $lcs = $this->lcs();
1452 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1453 wfProfileOut( $fname );
1458 * @todo document, bad name.
1460 * @addtogroup DifferenceEngine
1462 class MappedDiff
extends Diff
1467 * Computes diff between sequences of strings.
1469 * This can be used to compute things like
1470 * case-insensitve diffs, or diffs which ignore
1471 * changes in white-space.
1473 * @param $from_lines array An array of strings.
1474 * (Typically these are lines from a file.)
1476 * @param $to_lines array An array of strings.
1478 * @param $mapped_from_lines array This array should
1479 * have the same size number of elements as $from_lines.
1480 * The elements in $mapped_from_lines and
1481 * $mapped_to_lines are what is actually compared
1482 * when computing the diff.
1484 * @param $mapped_to_lines array This array should
1485 * have the same number of elements as $to_lines.
1487 function MappedDiff($from_lines, $to_lines,
1488 $mapped_from_lines, $mapped_to_lines) {
1489 $fname = 'MappedDiff::MappedDiff';
1490 wfProfileIn( $fname );
1492 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1493 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1495 $this->Diff($mapped_from_lines, $mapped_to_lines);
1498 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1499 $orig = &$this->edits
[$i]->orig
;
1500 if (is_array($orig)) {
1501 $orig = array_slice($from_lines, $xi, sizeof($orig));
1502 $xi +
= sizeof($orig);
1505 $closing = &$this->edits
[$i]->closing
;
1506 if (is_array($closing)) {
1507 $closing = array_slice($to_lines, $yi, sizeof($closing));
1508 $yi +
= sizeof($closing);
1511 wfProfileOut( $fname );
1516 * A class to format Diffs
1518 * This class formats the diff in classic diff format.
1519 * It is intended that this class be customized via inheritance,
1520 * to obtain fancier outputs.
1523 * @addtogroup DifferenceEngine
1528 * Number of leading context "lines" to preserve.
1530 * This should be left at zero for this class, but subclasses
1531 * may want to set this to other values.
1533 var $leading_context_lines = 0;
1536 * Number of trailing context "lines" to preserve.
1538 * This should be left at zero for this class, but subclasses
1539 * may want to set this to other values.
1541 var $trailing_context_lines = 0;
1546 * @param $diff object A Diff object.
1547 * @return string The formatted output.
1549 function format($diff) {
1550 $fname = 'DiffFormatter::format';
1551 wfProfileIn( $fname );
1557 $nlead = $this->leading_context_lines
;
1558 $ntrail = $this->trailing_context_lines
;
1560 $this->_start_diff();
1562 foreach ($diff->edits
as $edit) {
1563 if ($edit->type
== 'copy') {
1564 if (is_array($block)) {
1565 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1570 $context = array_slice($edit->orig
, 0, $ntrail);
1571 $block[] = new _DiffOp_Copy($context);
1573 $this->_block($x0, $ntrail +
$xi - $x0,
1574 $y0, $ntrail +
$yi - $y0,
1579 $context = $edit->orig
;
1582 if (! is_array($block)) {
1583 $context = array_slice($context, sizeof($context) - $nlead);
1584 $x0 = $xi - sizeof($context);
1585 $y0 = $yi - sizeof($context);
1588 $block[] = new _DiffOp_Copy($context);
1594 $xi +
= sizeof($edit->orig
);
1596 $yi +
= sizeof($edit->closing
);
1599 if (is_array($block))
1600 $this->_block($x0, $xi - $x0,
1604 $end = $this->_end_diff();
1605 wfProfileOut( $fname );
1609 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1610 $fname = 'DiffFormatter::_block';
1611 wfProfileIn( $fname );
1612 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1613 foreach ($edits as $edit) {
1614 if ($edit->type
== 'copy')
1615 $this->_context($edit->orig
);
1616 elseif ($edit->type
== 'add')
1617 $this->_added($edit->closing
);
1618 elseif ($edit->type
== 'delete')
1619 $this->_deleted($edit->orig
);
1620 elseif ($edit->type
== 'change')
1621 $this->_changed($edit->orig
, $edit->closing
);
1623 trigger_error('Unknown edit type', E_USER_ERROR
);
1625 $this->_end_block();
1626 wfProfileOut( $fname );
1629 function _start_diff() {
1633 function _end_diff() {
1634 $val = ob_get_contents();
1639 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1641 $xbeg .= "," . ($xbeg +
$xlen - 1);
1643 $ybeg .= "," . ($ybeg +
$ylen - 1);
1645 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1648 function _start_block($header) {
1649 echo $header . "\n";
1652 function _end_block() {
1655 function _lines($lines, $prefix = ' ') {
1656 foreach ($lines as $line)
1657 echo "$prefix $line\n";
1660 function _context($lines) {
1661 $this->_lines($lines);
1664 function _added($lines) {
1665 $this->_lines($lines, '>');
1667 function _deleted($lines) {
1668 $this->_lines($lines, '<');
1671 function _changed($orig, $closing) {
1672 $this->_deleted($orig);
1674 $this->_added($closing);
1679 * A formatter that outputs unified diffs
1680 * @addtogroup DifferenceEngine
1683 class UnifiedDiffFormatter
extends DiffFormatter
1685 var $leading_context_lines = 2;
1686 var $trailing_context_lines = 2;
1688 function _added($lines) {
1689 $this->_lines($lines, '+');
1691 function _deleted($lines) {
1692 $this->_lines($lines, '-');
1694 function _changed($orig, $closing) {
1695 $this->_deleted($orig);
1696 $this->_added($closing);
1698 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1699 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1704 * A pseudo-formatter that just passes along the Diff::$edits array
1705 * @addtogroup DifferenceEngine
1707 class ArrayDiffFormatter
extends DiffFormatter
1709 function format($diff)
1714 foreach($diff->edits
as $edit)
1718 foreach($edit->closing
as $l)
1723 'newline' => $newline++
1728 foreach($edit->orig
as $l)
1731 'action' => 'delete',
1733 'oldline' => $oldline++
,
1738 foreach($edit->orig
as $i => $l)
1741 'action' => 'change',
1743 'new' => @$edit->closing
[$i],
1744 'oldline' => $oldline++
,
1745 'newline' => $newline++
,
1750 $oldline +
= count($edit->orig
);
1751 $newline +
= count($edit->orig
);
1758 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1762 define('NBSP', ' '); // iso-8859-x non-breaking space.
1767 * @addtogroup DifferenceEngine
1769 class _HWLDF_WordAccumulator
{
1770 function _HWLDF_WordAccumulator () {
1771 $this->_lines
= array();
1777 function _flushGroup ($new_tag) {
1778 if ($this->_group
!== '') {
1779 if ($this->_tag
== 'ins')
1780 $this->_line
.= '<ins class="diffchange">' .
1781 htmlspecialchars ( $this->_group
) . '</ins>';
1782 elseif ($this->_tag
== 'del')
1783 $this->_line
.= '<del class="diffchange">' .
1784 htmlspecialchars ( $this->_group
) . '</del>';
1786 $this->_line
.= htmlspecialchars ( $this->_group
);
1789 $this->_tag
= $new_tag;
1792 function _flushLine ($new_tag) {
1793 $this->_flushGroup($new_tag);
1794 if ($this->_line
!= '')
1795 array_push ( $this->_lines
, $this->_line
);
1797 # make empty lines visible by inserting an NBSP
1798 array_push ( $this->_lines
, NBSP
);
1802 function addWords ($words, $tag = '') {
1803 if ($tag != $this->_tag
)
1804 $this->_flushGroup($tag);
1806 foreach ($words as $word) {
1807 // new-line should only come as first char of word.
1810 if ($word[0] == "\n") {
1811 $this->_flushLine($tag);
1812 $word = substr($word, 1);
1814 assert(!strstr($word, "\n"));
1815 $this->_group
.= $word;
1819 function getLines() {
1820 $this->_flushLine('~done');
1821 return $this->_lines
;
1828 * @addtogroup DifferenceEngine
1830 class WordLevelDiff
extends MappedDiff
1832 const MAX_LINE_LENGTH
= 10000;
1834 function WordLevelDiff ($orig_lines, $closing_lines) {
1835 $fname = 'WordLevelDiff::WordLevelDiff';
1836 wfProfileIn( $fname );
1838 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1839 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1841 $this->MappedDiff($orig_words, $closing_words,
1842 $orig_stripped, $closing_stripped);
1843 wfProfileOut( $fname );
1846 function _split($lines) {
1847 $fname = 'WordLevelDiff::_split';
1848 wfProfileIn( $fname );
1851 $stripped = array();
1853 foreach ( $lines as $line ) {
1854 # If the line is too long, just pretend the entire line is one big word
1855 # This prevents resource exhaustion problems
1862 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1864 $stripped[] = $line;
1867 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1870 $words = array_merge( $words, $m[0] );
1871 $stripped = array_merge( $stripped, $m[1] );
1875 wfProfileOut( $fname );
1876 return array($words, $stripped);
1880 $fname = 'WordLevelDiff::orig';
1881 wfProfileIn( $fname );
1882 $orig = new _HWLDF_WordAccumulator
;
1884 foreach ($this->edits
as $edit) {
1885 if ($edit->type
== 'copy')
1886 $orig->addWords($edit->orig
);
1887 elseif ($edit->orig
)
1888 $orig->addWords($edit->orig
, 'del');
1890 $lines = $orig->getLines();
1891 wfProfileOut( $fname );
1895 function closing () {
1896 $fname = 'WordLevelDiff::closing';
1897 wfProfileIn( $fname );
1898 $closing = new _HWLDF_WordAccumulator
;
1900 foreach ($this->edits
as $edit) {
1901 if ($edit->type
== 'copy')
1902 $closing->addWords($edit->closing
);
1903 elseif ($edit->closing
)
1904 $closing->addWords($edit->closing
, 'ins');
1906 $lines = $closing->getLines();
1907 wfProfileOut( $fname );
1913 * Wikipedia Table style diff formatter.
1916 * @addtogroup DifferenceEngine
1918 class TableDiffFormatter
extends DiffFormatter
1920 function TableDiffFormatter() {
1921 $this->leading_context_lines
= 2;
1922 $this->trailing_context_lines
= 2;
1925 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1926 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1927 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1931 function _start_block( $header ) {
1935 function _end_block() {
1938 function _lines( $lines, $prefix=' ', $color='white' ) {
1941 # HTML-escape parameter before calling this
1942 function addedLine( $line ) {
1943 return $this->wrapLine( '+', 'diff-addedline', $line );
1946 # HTML-escape parameter before calling this
1947 function deletedLine( $line ) {
1948 return $this->wrapLine( '-', 'diff-deletedline', $line );
1951 # HTML-escape parameter before calling this
1952 function contextLine( $line ) {
1953 return $this->wrapLine( ' ', 'diff-context', $line );
1956 private function wrapLine( $marker, $class, $line ) {
1957 if( $line !== '' ) {
1958 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1959 $line = "<div>$line</div>";
1961 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1964 function emptyLine() {
1965 return '<td colspan="2"> </td>';
1968 function _added( $lines ) {
1969 foreach ($lines as $line) {
1970 echo '<tr>' . $this->emptyLine() .
1971 $this->addedLine( '<ins class="diffchange">' .
1972 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1976 function _deleted($lines) {
1977 foreach ($lines as $line) {
1978 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1979 htmlspecialchars ( $line ) . '</del>' ) .
1980 $this->emptyLine() . "</tr>\n";
1984 function _context( $lines ) {
1985 foreach ($lines as $line) {
1987 $this->contextLine( htmlspecialchars ( $line ) ) .
1988 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1992 function _changed( $orig, $closing ) {
1993 $fname = 'TableDiffFormatter::_changed';
1994 wfProfileIn( $fname );
1996 $diff = new WordLevelDiff( $orig, $closing );
1997 $del = $diff->orig();
1998 $add = $diff->closing();
2000 # Notice that WordLevelDiff returns HTML-escaped output.
2001 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2003 while ( $line = array_shift( $del ) ) {
2004 $aline = array_shift( $add );
2005 echo '<tr>' . $this->deletedLine( $line ) .
2006 $this->addedLine( $aline ) . "</tr>\n";
2008 foreach ($add as $line) { # If any leftovers
2009 echo '<tr>' . $this->emptyLine() .
2010 $this->addedLine( $line ) . "</tr>\n";
2012 wfProfileOut( $fname );