3 * @defgroup DifferenceEngine DifferenceEngine
7 * Constant to indicate diff cache compatibility.
8 * Bump this when changing the diff formatting in a way that
9 * fixes important bugs or such to force cached diff views to
12 define( 'MW_DIFF_VERSION', '1.11a' );
16 * @ingroup DifferenceEngine
18 class DifferenceEngine
{
22 var $mOldid, $mNewid, $mTitle;
23 var $mOldtitle, $mNewtitle, $mPagetitle;
24 var $mOldtext, $mNewtext;
25 var $mOldPage, $mNewPage;
26 var $mRcidMarkPatrolled;
27 var $mOldRev, $mNewRev;
28 var $mRevisionsLoaded = false; // Have the revisions been loaded
29 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
34 * @param $titleObj Title object that the diff is associated with
35 * @param $old Integer: old ID we want to show and diff with.
36 * @param $new String: either 'prev' or 'next'.
37 * @param $rcid Integer: ??? FIXME (default 0)
38 * @param $refreshCache boolean If set, refreshes the diff cache
40 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false ) {
41 $this->mTitle
= $titleObj;
42 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
44 if ( 'prev' === $new ) {
45 # Show diff between revision $old and the previous one.
46 # Get previous one from DB.
48 $this->mNewid
= intval($old);
50 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
52 } elseif ( 'next' === $new ) {
53 # Show diff between revision $old and the previous one.
54 # Get previous one from DB.
56 $this->mOldid
= intval($old);
57 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
58 if ( false === $this->mNewid
) {
59 # if no result, NewId points to the newest old revision. The only newer
60 # revision is cur, which is "0".
65 $this->mOldid
= intval($old);
66 $this->mNewid
= intval($new);
68 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
69 $this->mRefreshCache
= $refreshCache;
76 function showDiffPage( $diffOnly = false ) {
77 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
78 wfProfileIn( __METHOD__
);
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();
112 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
113 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
114 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
115 wfProfileOut( __METHOD__
);
119 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
121 if ( $this->mNewRev
->isCurrent() ) {
122 $wgOut->setArticleFlag( true );
125 # mOldid is false if the difference engine is called with a "vague" query for
126 # a diff between a version V and its previous version V' AND the version V
127 # is the first version of that article. In that case, V' does not exist.
128 if ( $this->mOldid
=== false ) {
129 $this->showFirstRevision();
130 $this->renderNewRevision(); // should we respect $diffOnly here or not?
131 wfProfileOut( __METHOD__
);
135 $wgOut->suppressQuickbar();
137 $oldTitle = $this->mOldPage
->getPrefixedText();
138 $newTitle = $this->mNewPage
->getPrefixedText();
139 if( $oldTitle == $newTitle ) {
140 $wgOut->setPageTitle( $newTitle );
142 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
144 $wgOut->setSubtitle( wfMsg( 'difference' ) );
145 $wgOut->setRobotpolicy( 'noindex,nofollow' );
147 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
148 $wgOut->loginToUse();
150 wfProfileOut( __METHOD__
);
154 $sk = $wgUser->getSkin();
156 // Check if page is editable
157 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
158 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
159 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
164 // Prepare a change patrol link, if applicable
165 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
166 // If we've been given an explicit change identifier, use it; saves time
167 if( $this->mRcidMarkPatrolled
) {
168 $rcid = $this->mRcidMarkPatrolled
;
170 // Look for an unpatrolled change corresponding to this diff
171 $db = wfGetDB( DB_SLAVE
);
172 $change = RecentChange
::newFromConds(
174 // Add redundant user,timestamp condition so we can use the existing index
175 'rc_user_text' => $this->mNewRev
->getRawUserText(),
176 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
177 'rc_this_oldid' => $this->mNewid
,
178 'rc_last_oldid' => $this->mOldid
,
183 if( $change instanceof RecentChange
) {
184 $rcid = $change->mAttribs
['rc_id'];
192 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
194 wfMsgHtml( 'markaspatrolleddiff' ),
195 "action=markpatrolled&rcid={$rcid}"
204 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
205 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
206 if ( $this->mNewRev
->isCurrent() ) {
207 $nextlink = ' ';
209 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
210 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
216 if ($this->mOldRev
->mMinorEdit
== 1) {
217 $oldminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
220 if ($this->mNewRev
->mMinorEdit
== 1) {
221 $newminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
224 $rdel = ''; $ldel = '';
225 if( $wgUser->isAllowed( 'deleterevision' ) ) {
226 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
227 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
228 // If revision was hidden from sysops
229 $ldel = wfMsgHtml('rev-delundel');
231 $ldel = $sk->makeKnownLinkObj( $revdel,
232 wfMsgHtml('rev-delundel'),
233 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
234 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
235 // Bolden oversighted content
236 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
237 $ldel = "<strong>$ldel</strong>";
239 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
240 // We don't currently handle well changing the top revision's settings
241 if( $this->mNewRev
->isCurrent() ) {
242 // If revision was hidden from sysops
243 $rdel = wfMsgHtml('rev-delundel');
244 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
245 // If revision was hidden from sysops
246 $rdel = wfMsgHtml('rev-delundel');
248 $rdel = $sk->makeKnownLinkObj( $revdel,
249 wfMsgHtml('rev-delundel'),
250 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
251 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
252 // Bolden oversighted content
253 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
254 $rdel = "<strong>$rdel</strong>";
256 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
259 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
260 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
261 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
262 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
263 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
264 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
265 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
266 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
268 $this->showDiff( $oldHeader, $newHeader );
271 $this->renderNewRevision();
273 wfProfileOut( __METHOD__
);
277 * Show the new revision of the page.
279 function renderNewRevision() {
281 wfProfileIn( __METHOD__
);
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( __METHOD__
);
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;
328 wfProfileIn( __METHOD__
);
330 # Get article text from the DB
332 if ( ! $this->loadNewText() ) {
333 $t = $this->mTitle
->getPrefixedText();
334 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
335 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
336 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
337 wfProfileOut( __METHOD__
);
340 if ( $this->mNewRev
->isCurrent() ) {
341 $wgOut->setArticleFlag( true );
344 # Check if user is allowed to look at this page. If not, bail out.
346 if ( !( $this->mTitle
->userCanRead() ) ) {
347 $wgOut->loginToUse();
349 wfProfileOut( __METHOD__
);
353 # Prepare the header box
355 $sk = $wgUser->getSkin();
357 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
358 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
359 $sk->revUserTools( $this->mNewRev
) . "<br />" .
360 $sk->revComment( $this->mNewRev
) . "<br />" .
361 $nextlink . "</div>\n";
363 $wgOut->addHTML( $header );
365 $wgOut->setSubtitle( wfMsg( 'difference' ) );
366 $wgOut->setRobotpolicy( 'noindex,nofollow' );
368 wfProfileOut( __METHOD__
);
372 * Get the diff text, send it to $wgOut
373 * Returns false if the diff could not be generated, otherwise returns true
375 function showDiff( $otitle, $ntitle ) {
377 $diff = $this->getDiff( $otitle, $ntitle );
378 if ( $diff === false ) {
379 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
382 $this->showDiffStyle();
383 $wgOut->addHTML( $diff );
389 * Add style sheets and supporting JS for diff display.
391 function showDiffStyle() {
392 global $wgStylePath, $wgStyleVersion, $wgOut;
393 $wgOut->addStyle( 'common/diff.css' );
395 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
396 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
400 * Get complete diff table, including header
402 * @param Title $otitle Old title
403 * @param Title $ntitle New title
406 function getDiff( $otitle, $ntitle ) {
407 $body = $this->getDiffBody();
408 if ( $body === false ) {
411 $multi = $this->getMultiNotice();
412 return $this->addHeader( $body, $otitle, $ntitle, $multi );
417 * Get the diff table body, without header
421 function getDiffBody() {
423 wfProfileIn( __METHOD__
);
424 // Check if the diff should be hidden from this user
425 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
427 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
432 if ( $this->mOldid
&& $this->mNewid
) {
433 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
435 if ( !$this->mRefreshCache
) {
436 $difftext = $wgMemc->get( $key );
438 wfIncrStats( 'diff_cache_hit' );
439 $difftext = $this->localiseLineNumbers( $difftext );
440 $difftext .= "\n<!-- diff cache key $key -->\n";
441 wfProfileOut( __METHOD__
);
444 } // don't try to load but save the result
447 // Loadtext is permission safe, this just clears out the diff
448 if ( !$this->loadText() ) {
449 wfProfileOut( __METHOD__
);
453 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
455 // Save to cache for 7 days
456 if ( $key !== false && $difftext !== false ) {
457 wfIncrStats( 'diff_cache_miss' );
458 $wgMemc->set( $key, $difftext, 7*86400 );
460 wfIncrStats( 'diff_uncacheable' );
462 // Replace line numbers with the text in the user's language
463 if ( $difftext !== false ) {
464 $difftext = $this->localiseLineNumbers( $difftext );
466 wfProfileOut( __METHOD__
);
471 * Generate a diff, no caching
472 * $otext and $ntext must be already segmented
474 function generateDiffBody( $otext, $ntext ) {
475 global $wgExternalDiffEngine, $wgContLang;
477 $otext = str_replace( "\r\n", "\n", $otext );
478 $ntext = str_replace( "\r\n", "\n", $ntext );
480 if ( $wgExternalDiffEngine == 'wikidiff' ) {
481 # For historical reasons, external diff engine expects
482 # input text to be HTML-escaped already
483 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
484 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
485 if( !function_exists( 'wikidiff_do_diff' ) ) {
486 dl('php_wikidiff.so');
488 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
489 $this->debug( 'wikidiff1' );
492 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
493 # Better external diff engine, the 2 may some day be dropped
494 # This one does the escaping and segmenting itself
495 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
496 wfProfileIn( __METHOD__
. "-dl" );
497 @dl
('php_wikidiff2.so');
498 wfProfileOut( __METHOD__
. "-dl" );
500 if ( function_exists( 'wikidiff2_do_diff' ) ) {
501 wfProfileIn( 'wikidiff2_do_diff' );
502 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
503 $text .= $this->debug( 'wikidiff2' );
504 wfProfileOut( 'wikidiff2_do_diff' );
508 if ( $wgExternalDiffEngine !== false ) {
510 global $wgTmpDirectory;
511 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
512 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
514 $tempFile1 = fopen( $tempName1, "w" );
516 wfProfileOut( __METHOD__
);
519 $tempFile2 = fopen( $tempName2, "w" );
521 wfProfileOut( __METHOD__
);
524 fwrite( $tempFile1, $otext );
525 fwrite( $tempFile2, $ntext );
526 fclose( $tempFile1 );
527 fclose( $tempFile2 );
528 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
529 wfProfileIn( __METHOD__
. "-shellexec" );
530 $difftext = wfShellExec( $cmd );
531 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
532 wfProfileOut( __METHOD__
. "-shellexec" );
533 unlink( $tempName1 );
534 unlink( $tempName2 );
539 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
540 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
541 $diffs = new Diff( $ota, $nta );
542 $formatter = new TableDiffFormatter();
543 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
548 * Generate a debug comment indicating diff generating time,
549 * server node, and generator backend.
551 protected function debug( $generator="internal" ) {
552 global $wgShowHostnames, $wgNodeName;
553 $data = array( $generator );
554 if( $wgShowHostnames ) {
555 $data[] = $wgNodeName;
557 $data[] = wfTimestamp( TS_DB
);
558 return "<!-- diff generator: " .
567 * Replace line numbers with the text in the user's language
569 function localiseLineNumbers( $text ) {
570 return preg_replace_callback( '/<!--LINE (\d+)-->/',
571 array( &$this, 'localiseLineNumbersCb' ), $text );
574 function localiseLineNumbersCb( $matches ) {
576 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
581 * If there are revisions between the ones being compared, return a note saying so.
583 function getMultiNotice() {
584 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
587 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
588 // Comparing two different pages? Count would be meaningless.
592 $oldid = $this->mOldRev
->getId();
593 $newid = $this->mNewRev
->getId();
594 if ( $oldid > $newid ) {
595 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
598 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
602 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
607 * Add the header to a diff body
609 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
614 <col class='diff-marker' />
615 <col class='diff-content' />
616 <col class='diff-marker' />
617 <col class='diff-content' />
619 <td colspan='2' class='diff-otitle'>{$otitle}</td>
620 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
625 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
627 return $header . $diff . "</table>";
631 * Use specified text instead of loading from the database
633 function setText( $oldText, $newText ) {
634 $this->mOldtext
= $oldText;
635 $this->mNewtext
= $newText;
636 $this->mTextLoaded
= 2;
640 * Load revision metadata for the specified articles. If newid is 0, then compare
641 * the old article in oldid to the current article; if oldid is 0, then
642 * compare the current article to the immediately previous one (ignoring the
645 * If oldid is false, leave the corresponding revision object set
646 * to false. This is impossible via ordinary user input, and is provided for
649 function loadRevisionData() {
651 if ( $this->mRevisionsLoaded
) {
654 // Whether it succeeds or fails, we don't want to try again
655 $this->mRevisionsLoaded
= true;
658 // Load the new revision object
659 $this->mNewRev
= $this->mNewid
660 ? Revision
::newFromId( $this->mNewid
)
661 : Revision
::newFromTitle( $this->mTitle
);
662 if( !$this->mNewRev
instanceof Revision
)
665 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
666 $this->mNewid
= $this->mNewRev
->getId();
668 // Check if page is editable
669 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
671 // Set assorted variables
672 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
673 $this->mNewPage
= $this->mNewRev
->getTitle();
674 if( $this->mNewRev
->isCurrent() ) {
675 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
676 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
677 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
679 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
680 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
683 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
684 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
685 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
687 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
688 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
690 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
691 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
692 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
693 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
696 // Load the old revision object
697 $this->mOldRev
= false;
698 if( $this->mOldid
) {
699 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
700 } elseif ( $this->mOldid
=== 0 ) {
701 $rev = $this->mNewRev
->getPrevious();
703 $this->mOldid
= $rev->getId();
704 $this->mOldRev
= $rev;
706 // No previous revision; mark to show as first-version only.
707 $this->mOldid
= false;
708 $this->mOldRev
= false;
710 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
712 if( is_null( $this->mOldRev
) ) {
716 if ( $this->mOldRev
) {
717 $this->mOldPage
= $this->mOldRev
->getTitle();
719 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
720 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
721 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
722 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
724 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
725 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
726 // Add an "undo" link
727 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
728 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
729 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
732 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
733 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
734 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
735 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
743 * Load the text of the revisions, as well as revision data.
745 function loadText() {
746 if ( $this->mTextLoaded
== 2 ) {
749 // Whether it succeeds or fails, we don't want to try again
750 $this->mTextLoaded
= 2;
753 if ( !$this->loadRevisionData() ) {
756 if ( $this->mOldRev
) {
757 $this->mOldtext
= $this->mOldRev
->revText();
758 if ( $this->mOldtext
=== false ) {
762 if ( $this->mNewRev
) {
763 $this->mNewtext
= $this->mNewRev
->revText();
764 if ( $this->mNewtext
=== false ) {
772 * Load the text of the new revision, not the old one
774 function loadNewText() {
775 if ( $this->mTextLoaded
>= 1 ) {
778 $this->mTextLoaded
= 1;
780 if ( !$this->loadRevisionData() ) {
783 $this->mNewtext
= $this->mNewRev
->getText();
790 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
792 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
793 // You may copy this code freely under the conditions of the GPL.
796 define('USE_ASSERTS', function_exists('assert'));
801 * @ingroup DifferenceEngine
809 trigger_error('pure virtual', E_USER_ERROR
);
813 return $this->orig ?
sizeof($this->orig
) : 0;
816 function nclosing() {
817 return $this->closing ?
sizeof($this->closing
) : 0;
824 * @ingroup DifferenceEngine
826 class _DiffOp_Copy
extends _DiffOp
{
829 function _DiffOp_Copy ($orig, $closing = false) {
830 if (!is_array($closing))
833 $this->closing
= $closing;
837 return new _DiffOp_Copy($this->closing
, $this->orig
);
844 * @ingroup DifferenceEngine
846 class _DiffOp_Delete
extends _DiffOp
{
847 var $type = 'delete';
849 function _DiffOp_Delete ($lines) {
850 $this->orig
= $lines;
851 $this->closing
= false;
855 return new _DiffOp_Add($this->orig
);
862 * @ingroup DifferenceEngine
864 class _DiffOp_Add
extends _DiffOp
{
867 function _DiffOp_Add ($lines) {
868 $this->closing
= $lines;
873 return new _DiffOp_Delete($this->closing
);
880 * @ingroup DifferenceEngine
882 class _DiffOp_Change
extends _DiffOp
{
883 var $type = 'change';
885 function _DiffOp_Change ($orig, $closing) {
887 $this->closing
= $closing;
891 return new _DiffOp_Change($this->closing
, $this->orig
);
897 * Class used internally by Diff to actually compute the diffs.
899 * The algorithm used here is mostly lifted from the perl module
900 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
901 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
903 * More ideas are taken from:
904 * http://www.ics.uci.edu/~eppstein/161/960229.html
906 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
907 * diffutils-2.7, which can be found at:
908 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
910 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
913 * Line length limits for robustness added by Tim Starling, 2005-08-31
915 * @author Geoffrey T. Dairiki, Tim Starling
917 * @ingroup DifferenceEngine
920 const MAX_XREF_LENGTH
= 10000;
922 function diff ($from_lines, $to_lines) {
923 wfProfileIn( __METHOD__
);
925 $n_from = sizeof($from_lines);
926 $n_to = sizeof($to_lines);
928 $this->xchanged
= $this->ychanged
= array();
929 $this->xv
= $this->yv
= array();
930 $this->xind
= $this->yind
= array();
932 unset($this->in_seq
);
935 // Skip leading common lines.
936 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
937 if ($from_lines[$skip] !== $to_lines[$skip])
939 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
941 // Skip trailing common lines.
942 $xi = $n_from; $yi = $n_to;
943 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
944 if ($from_lines[$xi] !== $to_lines[$yi])
946 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
949 // Ignore lines which do not exist in both files.
950 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
951 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
954 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
955 $line = $to_lines[$yi];
956 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
958 $yhash[$this->_line_hash($line)] = 1;
962 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
963 $line = $from_lines[$xi];
964 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
971 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
973 // Merge edits when possible
974 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
975 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
977 // Compute the edit operations.
980 while ($xi < $n_from ||
$yi < $n_to) {
981 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
982 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
984 // Skip matching "snake".
986 while ( $xi < $n_from && $yi < $n_to
987 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
988 $copy[] = $from_lines[$xi++
];
992 $edits[] = new _DiffOp_Copy($copy);
994 // Find deletes & adds.
996 while ($xi < $n_from && $this->xchanged
[$xi])
997 $delete[] = $from_lines[$xi++
];
1000 while ($yi < $n_to && $this->ychanged
[$yi])
1001 $add[] = $to_lines[$yi++
];
1003 if ($delete && $add)
1004 $edits[] = new _DiffOp_Change($delete, $add);
1006 $edits[] = new _DiffOp_Delete($delete);
1008 $edits[] = new _DiffOp_Add($add);
1010 wfProfileOut( __METHOD__
);
1015 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1017 function _line_hash( $line ) {
1018 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1019 return md5( $line );
1026 /* Divide the Largest Common Subsequence (LCS) of the sequences
1027 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1030 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1031 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1032 * sub sequences. The first sub-sequence is contained in [X0, X1),
1033 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1034 * that (X0, Y0) == (XOFF, YOFF) and
1035 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1037 * This function assumes that the first lines of the specified portions
1038 * of the two files do not match, and likewise that the last lines do not
1039 * match. The caller must trim matching lines from the beginning and end
1040 * of the portions it is going to specify.
1042 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1043 wfProfileIn( __METHOD__
);
1046 if ($xlim - $xoff > $ylim - $yoff) {
1047 // Things seems faster (I'm not sure I understand why)
1048 // when the shortest sequence in X.
1050 list ($xoff, $xlim, $yoff, $ylim)
1051 = array( $yoff, $ylim, $xoff, $xlim);
1055 for ($i = $ylim - 1; $i >= $yoff; $i--)
1056 $ymatches[$this->xv
[$i]][] = $i;
1058 for ($i = $ylim - 1; $i >= $yoff; $i--)
1059 $ymatches[$this->yv
[$i]][] = $i;
1062 $this->seq
[0]= $yoff - 1;
1063 $this->in_seq
= array();
1064 $ymids[0] = array();
1066 $numer = $xlim - $xoff +
$nchunks - 1;
1068 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1069 wfProfileIn( __METHOD__
. "-chunk" );
1071 for ($i = 0; $i <= $this->lcs
; $i++
)
1072 $ymids[$i][$chunk-1] = $this->seq
[$i];
1074 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1075 for ( ; $x < $x1; $x++
) {
1076 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1077 if (empty($ymatches[$line]))
1079 $matches = $ymatches[$line];
1081 while (list ($junk, $y) = each($matches))
1082 if (empty($this->in_seq
[$y])) {
1083 $k = $this->_lcs_pos($y);
1084 USE_ASSERTS
&& assert($k > 0);
1085 $ymids[$k] = $ymids[$k-1];
1088 while (list ( /* $junk */, $y) = each($matches)) {
1089 if ($y > $this->seq
[$k-1]) {
1090 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1091 // Optimization: this is a common case:
1092 // next match is just replacing previous match.
1093 $this->in_seq
[$this->seq
[$k]] = false;
1094 $this->seq
[$k] = $y;
1095 $this->in_seq
[$y] = 1;
1096 } else if (empty($this->in_seq
[$y])) {
1097 $k = $this->_lcs_pos($y);
1098 USE_ASSERTS
&& assert($k > 0);
1099 $ymids[$k] = $ymids[$k-1];
1103 wfProfileOut( __METHOD__
. "-chunk" );
1106 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1107 $ymid = $ymids[$this->lcs
];
1108 for ($n = 0; $n < $nchunks - 1; $n++
) {
1109 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1110 $y1 = $ymid[$n] +
1;
1111 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1113 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1115 wfProfileOut( __METHOD__
);
1116 return array($this->lcs
, $seps);
1119 function _lcs_pos ($ypos) {
1120 wfProfileIn( __METHOD__
);
1123 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1124 $this->seq
[++
$this->lcs
] = $ypos;
1125 $this->in_seq
[$ypos] = 1;
1126 wfProfileOut( __METHOD__
);
1131 while ($beg < $end) {
1132 $mid = (int)(($beg +
$end) / 2);
1133 if ( $ypos > $this->seq
[$mid] )
1139 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1141 $this->in_seq
[$this->seq
[$end]] = false;
1142 $this->seq
[$end] = $ypos;
1143 $this->in_seq
[$ypos] = 1;
1144 wfProfileOut( __METHOD__
);
1148 /* Find LCS of two sequences.
1150 * The results are recorded in the vectors $this->{x,y}changed[], by
1151 * storing a 1 in the element for each line that is an insertion
1152 * or deletion (ie. is not in the LCS).
1154 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1156 * Note that XLIM, YLIM are exclusive bounds.
1157 * All line numbers are origin-0 and discarded lines are not counted.
1159 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1160 wfProfileIn( __METHOD__
);
1162 // Slide down the bottom initial diagonal.
1163 while ($xoff < $xlim && $yoff < $ylim
1164 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1169 // Slide up the top initial diagonal.
1170 while ($xlim > $xoff && $ylim > $yoff
1171 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1176 if ($xoff == $xlim ||
$yoff == $ylim)
1179 // This is ad hoc but seems to work well.
1180 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1181 //$nchunks = max(2,min(8,(int)$nchunks));
1182 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1184 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1188 // X and Y sequences have no common subsequence:
1189 // mark all changed.
1190 while ($yoff < $ylim)
1191 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1192 while ($xoff < $xlim)
1193 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1195 // Use the partitions to split this problem into subproblems.
1198 while ($pt2 = next($seps)) {
1199 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1203 wfProfileOut( __METHOD__
);
1206 /* Adjust inserts/deletes of identical lines to join changes
1207 * as much as possible.
1209 * We do something when a run of changed lines include a
1210 * line at one end and has an excluded, identical line at the other.
1211 * We are free to choose which identical line is included.
1212 * `compareseq' usually chooses the one at the beginning,
1213 * but usually it is cleaner to consider the following identical line
1214 * to be the "change".
1216 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1218 function _shift_boundaries ($lines, &$changed, $other_changed) {
1219 wfProfileIn( __METHOD__
);
1223 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1224 $len = sizeof($lines);
1225 $other_len = sizeof($other_changed);
1229 * Scan forwards to find beginning of another run of changes.
1230 * Also keep track of the corresponding point in the other file.
1232 * Throughout this code, $i and $j are adjusted together so that
1233 * the first $i elements of $changed and the first $j elements
1234 * of $other_changed both contain the same number of zeros
1235 * (unchanged lines).
1236 * Furthermore, $j is always kept so that $j == $other_len or
1237 * $other_changed[$j] == false.
1239 while ($j < $other_len && $other_changed[$j])
1242 while ($i < $len && ! $changed[$i]) {
1243 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1245 while ($j < $other_len && $other_changed[$j])
1254 // Find the end of this run of changes.
1255 while (++
$i < $len && $changed[$i])
1260 * Record the length of this run of changes, so that
1261 * we can later determine whether the run has grown.
1263 $runlength = $i - $start;
1266 * Move the changed region back, so long as the
1267 * previous unchanged line matches the last changed one.
1268 * This merges with previous changed regions.
1270 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1271 $changed[--$start] = 1;
1272 $changed[--$i] = false;
1273 while ($start > 0 && $changed[$start - 1])
1275 USE_ASSERTS
&& assert('$j > 0');
1276 while ($other_changed[--$j])
1278 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1282 * Set CORRESPONDING to the end of the changed run, at the last
1283 * point where it corresponds to a changed run in the other file.
1284 * CORRESPONDING == LEN means no such point has been found.
1286 $corresponding = $j < $other_len ?
$i : $len;
1289 * Move the changed region forward, so long as the
1290 * first changed line matches the following unchanged one.
1291 * This merges with following changed regions.
1292 * Do this second, so that if there are no merges,
1293 * the changed region is moved forward as far as possible.
1295 while ($i < $len && $lines[$start] == $lines[$i]) {
1296 $changed[$start++
] = false;
1298 while ($i < $len && $changed[$i])
1301 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1303 if ($j < $other_len && $other_changed[$j]) {
1304 $corresponding = $i;
1305 while ($j < $other_len && $other_changed[$j])
1309 } while ($runlength != $i - $start);
1312 * If possible, move the fully-merged run of changes
1313 * back to a corresponding run in the other file.
1315 while ($corresponding < $i) {
1316 $changed[--$start] = 1;
1318 USE_ASSERTS
&& assert('$j > 0');
1319 while ($other_changed[--$j])
1321 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1324 wfProfileOut( __METHOD__
);
1329 * Class representing a 'diff' between two sequences of strings.
1332 * @ingroup DifferenceEngine
1340 * Computes diff between sequences of strings.
1342 * @param $from_lines array An array of strings.
1343 * (Typically these are lines from a file.)
1344 * @param $to_lines array An array of strings.
1346 function Diff($from_lines, $to_lines) {
1347 $eng = new _DiffEngine
;
1348 $this->edits
= $eng->diff($from_lines, $to_lines);
1349 //$this->_check($from_lines, $to_lines);
1353 * Compute reversed Diff.
1357 * $diff = new Diff($lines1, $lines2);
1358 * $rev = $diff->reverse();
1359 * @return object A Diff object representing the inverse of the
1362 function reverse () {
1364 $rev->edits
= array();
1365 foreach ($this->edits
as $edit) {
1366 $rev->edits
[] = $edit->reverse();
1372 * Check for empty diff.
1374 * @return bool True iff two sequences were identical.
1376 function isEmpty () {
1377 foreach ($this->edits
as $edit) {
1378 if ($edit->type
!= 'copy')
1385 * Compute the length of the Longest Common Subsequence (LCS).
1387 * This is mostly for diagnostic purposed.
1389 * @return int The length of the LCS.
1393 foreach ($this->edits
as $edit) {
1394 if ($edit->type
== 'copy')
1395 $lcs +
= sizeof($edit->orig
);
1401 * Get the original set of lines.
1403 * This reconstructs the $from_lines parameter passed to the
1406 * @return array The original sequence of strings.
1411 foreach ($this->edits
as $edit) {
1413 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1419 * Get the closing set of lines.
1421 * This reconstructs the $to_lines parameter passed to the
1424 * @return array The sequence of strings.
1426 function closing() {
1429 foreach ($this->edits
as $edit) {
1431 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1437 * Check a Diff for validity.
1439 * This is here only for debugging purposes.
1441 function _check ($from_lines, $to_lines) {
1442 wfProfileIn( __METHOD__
);
1443 if (serialize($from_lines) != serialize($this->orig()))
1444 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1445 if (serialize($to_lines) != serialize($this->closing()))
1446 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1448 $rev = $this->reverse();
1449 if (serialize($to_lines) != serialize($rev->orig()))
1450 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1451 if (serialize($from_lines) != serialize($rev->closing()))
1452 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1456 foreach ($this->edits
as $edit) {
1457 if ( $prevtype == $edit->type
)
1458 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1459 $prevtype = $edit->type
;
1462 $lcs = $this->lcs();
1463 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1464 wfProfileOut( __METHOD__
);
1469 * @todo document, bad name.
1471 * @ingroup DifferenceEngine
1473 class MappedDiff
extends Diff
1478 * Computes diff between sequences of strings.
1480 * This can be used to compute things like
1481 * case-insensitve diffs, or diffs which ignore
1482 * changes in white-space.
1484 * @param $from_lines array An array of strings.
1485 * (Typically these are lines from a file.)
1487 * @param $to_lines array An array of strings.
1489 * @param $mapped_from_lines array This array should
1490 * have the same size number of elements as $from_lines.
1491 * The elements in $mapped_from_lines and
1492 * $mapped_to_lines are what is actually compared
1493 * when computing the diff.
1495 * @param $mapped_to_lines array This array should
1496 * have the same number of elements as $to_lines.
1498 function MappedDiff($from_lines, $to_lines,
1499 $mapped_from_lines, $mapped_to_lines) {
1500 wfProfileIn( __METHOD__
);
1502 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1503 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1505 $this->Diff($mapped_from_lines, $mapped_to_lines);
1508 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1509 $orig = &$this->edits
[$i]->orig
;
1510 if (is_array($orig)) {
1511 $orig = array_slice($from_lines, $xi, sizeof($orig));
1512 $xi +
= sizeof($orig);
1515 $closing = &$this->edits
[$i]->closing
;
1516 if (is_array($closing)) {
1517 $closing = array_slice($to_lines, $yi, sizeof($closing));
1518 $yi +
= sizeof($closing);
1521 wfProfileOut( __METHOD__
);
1526 * A class to format Diffs
1528 * This class formats the diff in classic diff format.
1529 * It is intended that this class be customized via inheritance,
1530 * to obtain fancier outputs.
1533 * @ingroup DifferenceEngine
1535 class DiffFormatter
{
1537 * Number of leading context "lines" to preserve.
1539 * This should be left at zero for this class, but subclasses
1540 * may want to set this to other values.
1542 var $leading_context_lines = 0;
1545 * Number of trailing context "lines" to preserve.
1547 * This should be left at zero for this class, but subclasses
1548 * may want to set this to other values.
1550 var $trailing_context_lines = 0;
1555 * @param $diff object A Diff object.
1556 * @return string The formatted output.
1558 function format($diff) {
1559 wfProfileIn( __METHOD__
);
1565 $nlead = $this->leading_context_lines
;
1566 $ntrail = $this->trailing_context_lines
;
1568 $this->_start_diff();
1570 foreach ($diff->edits
as $edit) {
1571 if ($edit->type
== 'copy') {
1572 if (is_array($block)) {
1573 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1578 $context = array_slice($edit->orig
, 0, $ntrail);
1579 $block[] = new _DiffOp_Copy($context);
1581 $this->_block($x0, $ntrail +
$xi - $x0,
1582 $y0, $ntrail +
$yi - $y0,
1587 $context = $edit->orig
;
1590 if (! is_array($block)) {
1591 $context = array_slice($context, sizeof($context) - $nlead);
1592 $x0 = $xi - sizeof($context);
1593 $y0 = $yi - sizeof($context);
1596 $block[] = new _DiffOp_Copy($context);
1602 $xi +
= sizeof($edit->orig
);
1604 $yi +
= sizeof($edit->closing
);
1607 if (is_array($block))
1608 $this->_block($x0, $xi - $x0,
1612 $end = $this->_end_diff();
1613 wfProfileOut( __METHOD__
);
1617 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1618 wfProfileIn( __METHOD__
);
1619 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1620 foreach ($edits as $edit) {
1621 if ($edit->type
== 'copy')
1622 $this->_context($edit->orig
);
1623 elseif ($edit->type
== 'add')
1624 $this->_added($edit->closing
);
1625 elseif ($edit->type
== 'delete')
1626 $this->_deleted($edit->orig
);
1627 elseif ($edit->type
== 'change')
1628 $this->_changed($edit->orig
, $edit->closing
);
1630 trigger_error('Unknown edit type', E_USER_ERROR
);
1632 $this->_end_block();
1633 wfProfileOut( __METHOD__
);
1636 function _start_diff() {
1640 function _end_diff() {
1641 $val = ob_get_contents();
1646 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1648 $xbeg .= "," . ($xbeg +
$xlen - 1);
1650 $ybeg .= "," . ($ybeg +
$ylen - 1);
1652 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1655 function _start_block($header) {
1656 echo $header . "\n";
1659 function _end_block() {
1662 function _lines($lines, $prefix = ' ') {
1663 foreach ($lines as $line)
1664 echo "$prefix $line\n";
1667 function _context($lines) {
1668 $this->_lines($lines);
1671 function _added($lines) {
1672 $this->_lines($lines, '>');
1674 function _deleted($lines) {
1675 $this->_lines($lines, '<');
1678 function _changed($orig, $closing) {
1679 $this->_deleted($orig);
1681 $this->_added($closing);
1686 * A formatter that outputs unified diffs
1687 * @ingroup DifferenceEngine
1690 class UnifiedDiffFormatter
extends DiffFormatter
{
1691 var $leading_context_lines = 2;
1692 var $trailing_context_lines = 2;
1694 function _added($lines) {
1695 $this->_lines($lines, '+');
1697 function _deleted($lines) {
1698 $this->_lines($lines, '-');
1700 function _changed($orig, $closing) {
1701 $this->_deleted($orig);
1702 $this->_added($closing);
1704 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1705 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1710 * A pseudo-formatter that just passes along the Diff::$edits array
1711 * @ingroup DifferenceEngine
1713 class ArrayDiffFormatter
extends DiffFormatter
{
1714 function format($diff) {
1718 foreach($diff->edits
as $edit)
1719 switch($edit->type
) {
1721 foreach($edit->closing
as $l) {
1725 'newline' => $newline++
1730 foreach($edit->orig
as $l) {
1732 'action' => 'delete',
1734 'oldline' => $oldline++
,
1739 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 * @ingroup 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 diffchange-inline">' .
1781 htmlspecialchars ( $this->_group
) . '</ins>';
1782 elseif ($this->_tag
== 'del')
1783 $this->_line
.= '<del class="diffchange diffchange-inline">' .
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 * @ingroup DifferenceEngine
1830 class WordLevelDiff
extends MappedDiff
{
1831 const MAX_LINE_LENGTH
= 10000;
1833 function WordLevelDiff ($orig_lines, $closing_lines) {
1834 wfProfileIn( __METHOD__
);
1836 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1837 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1839 $this->MappedDiff($orig_words, $closing_words,
1840 $orig_stripped, $closing_stripped);
1841 wfProfileOut( __METHOD__
);
1844 function _split($lines) {
1845 wfProfileIn( __METHOD__
);
1848 $stripped = array();
1850 foreach ( $lines as $line ) {
1851 # If the line is too long, just pretend the entire line is one big word
1852 # This prevents resource exhaustion problems
1859 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1861 $stripped[] = $line;
1864 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1867 $words = array_merge( $words, $m[0] );
1868 $stripped = array_merge( $stripped, $m[1] );
1872 wfProfileOut( __METHOD__
);
1873 return array($words, $stripped);
1877 wfProfileIn( __METHOD__
);
1878 $orig = new _HWLDF_WordAccumulator
;
1880 foreach ($this->edits
as $edit) {
1881 if ($edit->type
== 'copy')
1882 $orig->addWords($edit->orig
);
1883 elseif ($edit->orig
)
1884 $orig->addWords($edit->orig
, 'del');
1886 $lines = $orig->getLines();
1887 wfProfileOut( __METHOD__
);
1891 function closing () {
1892 wfProfileIn( __METHOD__
);
1893 $closing = new _HWLDF_WordAccumulator
;
1895 foreach ($this->edits
as $edit) {
1896 if ($edit->type
== 'copy')
1897 $closing->addWords($edit->closing
);
1898 elseif ($edit->closing
)
1899 $closing->addWords($edit->closing
, 'ins');
1901 $lines = $closing->getLines();
1902 wfProfileOut( __METHOD__
);
1908 * Wikipedia Table style diff formatter.
1911 * @ingroup DifferenceEngine
1913 class TableDiffFormatter
extends DiffFormatter
{
1914 function TableDiffFormatter() {
1915 $this->leading_context_lines
= 2;
1916 $this->trailing_context_lines
= 2;
1919 public static function escapeWhiteSpace( $msg ) {
1920 $msg = preg_replace( '/^ /m', ' ', $msg );
1921 $msg = preg_replace( '/ $/m', ' ', $msg );
1922 $msg = preg_replace( '/ /', ' ', $msg );
1926 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1927 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1928 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1932 function _start_block( $header ) {
1936 function _end_block() {
1939 function _lines( $lines, $prefix=' ', $color='white' ) {
1942 # HTML-escape parameter before calling this
1943 function addedLine( $line ) {
1944 return $this->wrapLine( '+', 'diff-addedline', $line );
1947 # HTML-escape parameter before calling this
1948 function deletedLine( $line ) {
1949 return $this->wrapLine( '-', 'diff-deletedline', $line );
1952 # HTML-escape parameter before calling this
1953 function contextLine( $line ) {
1954 return $this->wrapLine( ' ', 'diff-context', $line );
1957 private function wrapLine( $marker, $class, $line ) {
1958 if( $line !== '' ) {
1959 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1960 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1962 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1965 function emptyLine() {
1966 return '<td colspan="2"> </td>';
1969 function _added( $lines ) {
1970 foreach ($lines as $line) {
1971 echo '<tr>' . $this->emptyLine() .
1972 $this->addedLine( '<ins class="diffchange">' .
1973 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1977 function _deleted($lines) {
1978 foreach ($lines as $line) {
1979 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1980 htmlspecialchars ( $line ) . '</del>' ) .
1981 $this->emptyLine() . "</tr>\n";
1985 function _context( $lines ) {
1986 foreach ($lines as $line) {
1988 $this->contextLine( htmlspecialchars ( $line ) ) .
1989 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1993 function _changed( $orig, $closing ) {
1994 wfProfileIn( __METHOD__
);
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( __METHOD__
);