3 * @defgroup DifferenceEngine DifferenceEngine
7 * @todo indicate where diff.doc can be found.
11 * Constant to indicate diff cache compatibility.
12 * Bump this when changing the diff formatting in a way that
13 * fixes important bugs or such to force cached diff views to
16 define( 'MW_DIFF_VERSION', '1.11a' );
20 * @ingroup DifferenceEngine
22 class DifferenceEngine
{
26 var $mOldid, $mNewid, $mTitle;
27 var $mOldtitle, $mNewtitle, $mPagetitle;
28 var $mOldtext, $mNewtext;
29 var $mOldPage, $mNewPage;
30 var $mRcidMarkPatrolled;
31 var $mOldRev, $mNewRev;
32 var $mRevisionsLoaded = false; // Have the revisions been loaded
33 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
38 * @param $titleObj Title object that the diff is associated with
39 * @param $old Integer: old ID we want to show and diff with.
40 * @param $new String: either 'prev' or 'next'.
41 * @param $rcid Integer: ??? FIXME (default 0)
42 * @param $refreshCache boolean If set, refreshes the diff cache
44 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false ) {
45 $this->mTitle
= $titleObj;
46 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
48 if ( 'prev' === $new ) {
49 # Show diff between revision $old and the previous one.
50 # Get previous one from DB.
52 $this->mNewid
= intval($old);
54 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
56 } elseif ( 'next' === $new ) {
57 # Show diff between revision $old and the previous one.
58 # Get previous one from DB.
60 $this->mOldid
= intval($old);
61 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
62 if ( false === $this->mNewid
) {
63 # if no result, NewId points to the newest old revision. The only newer
64 # revision is cur, which is "0".
69 $this->mOldid
= intval($old);
70 $this->mNewid
= intval($new);
72 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
73 $this->mRefreshCache
= $refreshCache;
80 function showDiffPage( $diffOnly = false ) {
81 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
82 wfProfileIn( __METHOD__
);
84 # If external diffs are enabled both globally and for the user,
85 # we'll use the application/x-external-editor interface to call
86 # an external diff tool like kompare, kdiff3, etc.
87 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
88 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
90 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
91 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
92 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
93 $special=$wgLang->getNsText(NS_SPECIAL
);
98 Script={$wgServer}{$wgScript}
99 Special namespace={$special}
113 $wgOut->setArticleFlag( false );
114 if ( ! $this->loadRevisionData() ) {
115 $t = $this->mTitle
->getPrefixedText() . ' ' . wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
116 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
117 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
118 wfProfileOut( __METHOD__
);
122 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
124 if ( $this->mNewRev
->isCurrent() ) {
125 $wgOut->setArticleFlag( true );
128 # mOldid is false if the difference engine is called with a "vague" query for
129 # a diff between a version V and its previous version V' AND the version V
130 # is the first version of that article. In that case, V' does not exist.
131 if ( $this->mOldid
=== false ) {
132 $this->showFirstRevision();
133 $this->renderNewRevision(); // should we respect $diffOnly here or not?
134 wfProfileOut( __METHOD__
);
138 $wgOut->suppressQuickbar();
140 $oldTitle = $this->mOldPage
->getPrefixedText();
141 $newTitle = $this->mNewPage
->getPrefixedText();
142 if( $oldTitle == $newTitle ) {
143 $wgOut->setPageTitle( $newTitle );
145 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
147 $wgOut->setSubtitle( wfMsg( 'difference' ) );
148 $wgOut->setRobotpolicy( 'noindex,nofollow' );
150 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
151 $wgOut->loginToUse();
153 wfProfileOut( __METHOD__
);
157 $sk = $wgUser->getSkin();
159 // Check if page is editable
160 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
161 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
162 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
167 // Prepare a change patrol link, if applicable
168 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
169 // If we've been given an explicit change identifier, use it; saves time
170 if( $this->mRcidMarkPatrolled
) {
171 $rcid = $this->mRcidMarkPatrolled
;
173 // Look for an unpatrolled change corresponding to this diff
174 $db = wfGetDB( DB_SLAVE
);
175 $change = RecentChange
::newFromConds(
177 // Add redundant user,timestamp condition so we can use the existing index
178 'rc_user_text' => $this->mNewRev
->getRawUserText(),
179 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
180 'rc_this_oldid' => $this->mNewid
,
181 'rc_last_oldid' => $this->mOldid
,
186 if( $change instanceof RecentChange
) {
187 $rcid = $change->mAttribs
['rc_id'];
195 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
197 wfMsgHtml( 'markaspatrolleddiff' ),
198 "action=markpatrolled&rcid={$rcid}"
207 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
208 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
209 if ( $this->mNewRev
->isCurrent() ) {
210 $nextlink = ' ';
212 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
213 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
219 if ($this->mOldRev
->mMinorEdit
== 1) {
220 $oldminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
223 if ($this->mNewRev
->mMinorEdit
== 1) {
224 $newminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
227 $rdel = ''; $ldel = '';
228 if( $wgUser->isAllowed( 'deleterevision' ) ) {
229 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
230 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
231 // If revision was hidden from sysops
232 $ldel = wfMsgHtml('rev-delundel');
234 $ldel = $sk->makeKnownLinkObj( $revdel,
235 wfMsgHtml('rev-delundel'),
236 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
237 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
238 // Bolden oversighted content
239 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
240 $ldel = "<strong>$ldel</strong>";
242 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
243 // We don't currently handle well changing the top revision's settings
244 if( $this->mNewRev
->isCurrent() ) {
245 // If revision was hidden from sysops
246 $rdel = wfMsgHtml('rev-delundel');
247 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
248 // If revision was hidden from sysops
249 $rdel = wfMsgHtml('rev-delundel');
251 $rdel = $sk->makeKnownLinkObj( $revdel,
252 wfMsgHtml('rev-delundel'),
253 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
254 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
255 // Bolden oversighted content
256 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
257 $rdel = "<strong>$rdel</strong>";
259 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
262 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
263 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
264 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
265 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
266 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
267 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
268 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
269 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
271 $this->showDiff( $oldHeader, $newHeader );
274 $this->renderNewRevision();
276 wfProfileOut( __METHOD__
);
280 * Show the new revision of the page.
282 function renderNewRevision() {
284 wfProfileIn( __METHOD__
);
286 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
287 #add deleted rev tag if needed
288 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
289 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
290 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
291 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
294 if( !$this->mNewRev
->isCurrent() ) {
295 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
298 $this->loadNewText();
299 if( is_object( $this->mNewRev
) ) {
300 $wgOut->setRevisionId( $this->mNewRev
->getId() );
303 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
304 // Stolen from Article::view --AG 2007-10-11
306 // Give hooks a chance to customise the output
307 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
308 // Wrap the whole lot in a <pre> and don't parse
310 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
311 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
312 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
313 $wgOut->addHtml( "\n</pre>\n" );
316 $wgOut->addWikiTextTidy( $this->mNewtext
);
318 if( !$this->mNewRev
->isCurrent() ) {
319 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
322 wfProfileOut( __METHOD__
);
326 * Show the first revision of an article. Uses normal diff headers in
327 * contrast to normal "old revision" display style.
329 function showFirstRevision() {
330 global $wgOut, $wgUser;
331 wfProfileIn( __METHOD__
);
333 # Get article text from the DB
335 if ( ! $this->loadNewText() ) {
336 $t = $this->mTitle
->getPrefixedText() . ' ' . wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
337 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
338 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
339 wfProfileOut( __METHOD__
);
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( __METHOD__
);
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( __METHOD__
);
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 wfProfileIn( __METHOD__
);
426 // Check if the diff should be hidden from this user
427 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
429 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
434 if ( $this->mOldid
&& $this->mNewid
) {
435 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
437 if ( !$this->mRefreshCache
) {
438 $difftext = $wgMemc->get( $key );
440 wfIncrStats( 'diff_cache_hit' );
441 $difftext = $this->localiseLineNumbers( $difftext );
442 $difftext .= "\n<!-- diff cache key $key -->\n";
443 wfProfileOut( __METHOD__
);
446 } // don't try to load but save the result
449 // Loadtext is permission safe, this just clears out the diff
450 if ( !$this->loadText() ) {
451 wfProfileOut( __METHOD__
);
455 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
457 // Save to cache for 7 days
458 if ( $key !== false && $difftext !== false ) {
459 wfIncrStats( 'diff_cache_miss' );
460 $wgMemc->set( $key, $difftext, 7*86400 );
462 wfIncrStats( 'diff_uncacheable' );
464 // Replace line numbers with the text in the user's language
465 if ( $difftext !== false ) {
466 $difftext = $this->localiseLineNumbers( $difftext );
468 wfProfileOut( __METHOD__
);
473 * Generate a diff, no caching
474 * $otext and $ntext must be already segmented
476 function generateDiffBody( $otext, $ntext ) {
477 global $wgExternalDiffEngine, $wgContLang;
479 $otext = str_replace( "\r\n", "\n", $otext );
480 $ntext = str_replace( "\r\n", "\n", $ntext );
482 if ( $wgExternalDiffEngine == 'wikidiff' ) {
483 # For historical reasons, external diff engine expects
484 # input text to be HTML-escaped already
485 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
486 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
487 if( !function_exists( 'wikidiff_do_diff' ) ) {
488 dl('php_wikidiff.so');
490 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
491 $this->debug( 'wikidiff1' );
494 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
495 # Better external diff engine, the 2 may some day be dropped
496 # This one does the escaping and segmenting itself
497 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
498 wfProfileIn( __METHOD__
. "-dl" );
499 @dl
('php_wikidiff2.so');
500 wfProfileOut( __METHOD__
. "-dl" );
502 if ( function_exists( 'wikidiff2_do_diff' ) ) {
503 wfProfileIn( 'wikidiff2_do_diff' );
504 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
505 $text .= $this->debug( 'wikidiff2' );
506 wfProfileOut( 'wikidiff2_do_diff' );
510 if ( $wgExternalDiffEngine !== false ) {
512 global $wgTmpDirectory;
513 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
514 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
516 $tempFile1 = fopen( $tempName1, "w" );
518 wfProfileOut( __METHOD__
);
521 $tempFile2 = fopen( $tempName2, "w" );
523 wfProfileOut( __METHOD__
);
526 fwrite( $tempFile1, $otext );
527 fwrite( $tempFile2, $ntext );
528 fclose( $tempFile1 );
529 fclose( $tempFile2 );
530 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
531 wfProfileIn( __METHOD__
. "-shellexec" );
532 $difftext = wfShellExec( $cmd );
533 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
534 wfProfileOut( __METHOD__
. "-shellexec" );
535 unlink( $tempName1 );
536 unlink( $tempName2 );
541 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
542 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
543 $diffs = new Diff( $ota, $nta );
544 $formatter = new TableDiffFormatter();
545 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
550 * Generate a debug comment indicating diff generating time,
551 * server node, and generator backend.
553 protected function debug( $generator="internal" ) {
554 global $wgShowHostnames, $wgNodeName;
555 $data = array( $generator );
556 if( $wgShowHostnames ) {
557 $data[] = $wgNodeName;
559 $data[] = wfTimestamp( TS_DB
);
560 return "<!-- diff generator: " .
569 * Replace line numbers with the text in the user's language
571 function localiseLineNumbers( $text ) {
572 return preg_replace_callback( '/<!--LINE (\d+)-->/',
573 array( &$this, 'localiseLineNumbersCb' ), $text );
576 function localiseLineNumbersCb( $matches ) {
578 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
583 * If there are revisions between the ones being compared, return a note saying so.
585 function getMultiNotice() {
586 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
589 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
590 // Comparing two different pages? Count would be meaningless.
594 $oldid = $this->mOldRev
->getId();
595 $newid = $this->mNewRev
->getId();
596 if ( $oldid > $newid ) {
597 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
600 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
604 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
609 * Add the header to a diff body
611 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
616 <col class='diff-marker' />
617 <col class='diff-content' />
618 <col class='diff-marker' />
619 <col class='diff-content' />
621 <td colspan='2' class='diff-otitle'>{$otitle}</td>
622 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
627 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
629 return $header . $diff . "</table>";
633 * Use specified text instead of loading from the database
635 function setText( $oldText, $newText ) {
636 $this->mOldtext
= $oldText;
637 $this->mNewtext
= $newText;
638 $this->mTextLoaded
= 2;
642 * Load revision metadata for the specified articles. If newid is 0, then compare
643 * the old article in oldid to the current article; if oldid is 0, then
644 * compare the current article to the immediately previous one (ignoring the
647 * If oldid is false, leave the corresponding revision object set
648 * to false. This is impossible via ordinary user input, and is provided for
651 function loadRevisionData() {
653 if ( $this->mRevisionsLoaded
) {
656 // Whether it succeeds or fails, we don't want to try again
657 $this->mRevisionsLoaded
= true;
660 // Load the new revision object
661 $this->mNewRev
= $this->mNewid
662 ? Revision
::newFromId( $this->mNewid
)
663 : Revision
::newFromTitle( $this->mTitle
);
664 if( !$this->mNewRev
instanceof Revision
)
667 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
668 $this->mNewid
= $this->mNewRev
->getId();
670 // Check if page is editable
671 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
673 // Set assorted variables
674 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
675 $this->mNewPage
= $this->mNewRev
->getTitle();
676 if( $this->mNewRev
->isCurrent() ) {
677 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
678 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
679 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
681 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
682 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
685 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
686 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
687 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
689 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
690 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
692 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
693 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
694 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
695 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
698 // Load the old revision object
699 $this->mOldRev
= false;
700 if( $this->mOldid
) {
701 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
702 } elseif ( $this->mOldid
=== 0 ) {
703 $rev = $this->mNewRev
->getPrevious();
705 $this->mOldid
= $rev->getId();
706 $this->mOldRev
= $rev;
708 // No previous revision; mark to show as first-version only.
709 $this->mOldid
= false;
710 $this->mOldRev
= false;
712 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
714 if( is_null( $this->mOldRev
) ) {
718 if ( $this->mOldRev
) {
719 $this->mOldPage
= $this->mOldRev
->getTitle();
721 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
722 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
723 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
724 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
726 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
727 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
728 // Add an "undo" link
729 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
730 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
731 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
734 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
735 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
736 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
737 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
745 * Load the text of the revisions, as well as revision data.
747 function loadText() {
748 if ( $this->mTextLoaded
== 2 ) {
751 // Whether it succeeds or fails, we don't want to try again
752 $this->mTextLoaded
= 2;
755 if ( !$this->loadRevisionData() ) {
758 if ( $this->mOldRev
) {
759 $this->mOldtext
= $this->mOldRev
->revText();
760 if ( $this->mOldtext
=== false ) {
764 if ( $this->mNewRev
) {
765 $this->mNewtext
= $this->mNewRev
->revText();
766 if ( $this->mNewtext
=== false ) {
774 * Load the text of the new revision, not the old one
776 function loadNewText() {
777 if ( $this->mTextLoaded
>= 1 ) {
780 $this->mTextLoaded
= 1;
782 if ( !$this->loadRevisionData() ) {
785 $this->mNewtext
= $this->mNewRev
->getText();
792 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
794 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
795 // You may copy this code freely under the conditions of the GPL.
798 define('USE_ASSERTS', function_exists('assert'));
803 * @ingroup DifferenceEngine
811 trigger_error('pure virtual', E_USER_ERROR
);
815 return $this->orig ?
sizeof($this->orig
) : 0;
818 function nclosing() {
819 return $this->closing ?
sizeof($this->closing
) : 0;
826 * @ingroup DifferenceEngine
828 class _DiffOp_Copy
extends _DiffOp
{
831 function _DiffOp_Copy ($orig, $closing = false) {
832 if (!is_array($closing))
835 $this->closing
= $closing;
839 return new _DiffOp_Copy($this->closing
, $this->orig
);
846 * @ingroup DifferenceEngine
848 class _DiffOp_Delete
extends _DiffOp
{
849 var $type = 'delete';
851 function _DiffOp_Delete ($lines) {
852 $this->orig
= $lines;
853 $this->closing
= false;
857 return new _DiffOp_Add($this->orig
);
864 * @ingroup DifferenceEngine
866 class _DiffOp_Add
extends _DiffOp
{
869 function _DiffOp_Add ($lines) {
870 $this->closing
= $lines;
875 return new _DiffOp_Delete($this->closing
);
882 * @ingroup DifferenceEngine
884 class _DiffOp_Change
extends _DiffOp
{
885 var $type = 'change';
887 function _DiffOp_Change ($orig, $closing) {
889 $this->closing
= $closing;
893 return new _DiffOp_Change($this->closing
, $this->orig
);
899 * Class used internally by Diff to actually compute the diffs.
901 * The algorithm used here is mostly lifted from the perl module
902 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
903 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
905 * More ideas are taken from:
906 * http://www.ics.uci.edu/~eppstein/161/960229.html
908 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
909 * diffutils-2.7, which can be found at:
910 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
912 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
915 * Line length limits for robustness added by Tim Starling, 2005-08-31
917 * @author Geoffrey T. Dairiki, Tim Starling
919 * @ingroup DifferenceEngine
922 const MAX_XREF_LENGTH
= 10000;
924 function diff ($from_lines, $to_lines) {
925 wfProfileIn( __METHOD__
);
927 $n_from = sizeof($from_lines);
928 $n_to = sizeof($to_lines);
930 $this->xchanged
= $this->ychanged
= array();
931 $this->xv
= $this->yv
= array();
932 $this->xind
= $this->yind
= array();
934 unset($this->in_seq
);
937 // Skip leading common lines.
938 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
939 if ($from_lines[$skip] !== $to_lines[$skip])
941 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
943 // Skip trailing common lines.
944 $xi = $n_from; $yi = $n_to;
945 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
946 if ($from_lines[$xi] !== $to_lines[$yi])
948 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
951 // Ignore lines which do not exist in both files.
952 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
953 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
956 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
957 $line = $to_lines[$yi];
958 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
960 $yhash[$this->_line_hash($line)] = 1;
964 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
965 $line = $from_lines[$xi];
966 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
973 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
975 // Merge edits when possible
976 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
977 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
979 // Compute the edit operations.
982 while ($xi < $n_from ||
$yi < $n_to) {
983 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
984 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
986 // Skip matching "snake".
988 while ( $xi < $n_from && $yi < $n_to
989 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
990 $copy[] = $from_lines[$xi++
];
994 $edits[] = new _DiffOp_Copy($copy);
996 // Find deletes & adds.
998 while ($xi < $n_from && $this->xchanged
[$xi])
999 $delete[] = $from_lines[$xi++
];
1002 while ($yi < $n_to && $this->ychanged
[$yi])
1003 $add[] = $to_lines[$yi++
];
1005 if ($delete && $add)
1006 $edits[] = new _DiffOp_Change($delete, $add);
1008 $edits[] = new _DiffOp_Delete($delete);
1010 $edits[] = new _DiffOp_Add($add);
1012 wfProfileOut( __METHOD__
);
1017 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1019 function _line_hash( $line ) {
1020 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1021 return md5( $line );
1028 /* Divide the Largest Common Subsequence (LCS) of the sequences
1029 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1032 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1033 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1034 * sub sequences. The first sub-sequence is contained in [X0, X1),
1035 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1036 * that (X0, Y0) == (XOFF, YOFF) and
1037 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1039 * This function assumes that the first lines of the specified portions
1040 * of the two files do not match, and likewise that the last lines do not
1041 * match. The caller must trim matching lines from the beginning and end
1042 * of the portions it is going to specify.
1044 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1045 wfProfileIn( __METHOD__
);
1048 if ($xlim - $xoff > $ylim - $yoff) {
1049 // Things seems faster (I'm not sure I understand why)
1050 // when the shortest sequence in X.
1052 list ($xoff, $xlim, $yoff, $ylim)
1053 = array( $yoff, $ylim, $xoff, $xlim);
1057 for ($i = $ylim - 1; $i >= $yoff; $i--)
1058 $ymatches[$this->xv
[$i]][] = $i;
1060 for ($i = $ylim - 1; $i >= $yoff; $i--)
1061 $ymatches[$this->yv
[$i]][] = $i;
1064 $this->seq
[0]= $yoff - 1;
1065 $this->in_seq
= array();
1066 $ymids[0] = array();
1068 $numer = $xlim - $xoff +
$nchunks - 1;
1070 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1071 wfProfileIn( __METHOD__
. "-chunk" );
1073 for ($i = 0; $i <= $this->lcs
; $i++
)
1074 $ymids[$i][$chunk-1] = $this->seq
[$i];
1076 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1077 for ( ; $x < $x1; $x++
) {
1078 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1079 if (empty($ymatches[$line]))
1081 $matches = $ymatches[$line];
1083 while (list ($junk, $y) = each($matches))
1084 if (empty($this->in_seq
[$y])) {
1085 $k = $this->_lcs_pos($y);
1086 USE_ASSERTS
&& assert($k > 0);
1087 $ymids[$k] = $ymids[$k-1];
1090 while (list ( /* $junk */, $y) = each($matches)) {
1091 if ($y > $this->seq
[$k-1]) {
1092 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1093 // Optimization: this is a common case:
1094 // next match is just replacing previous match.
1095 $this->in_seq
[$this->seq
[$k]] = false;
1096 $this->seq
[$k] = $y;
1097 $this->in_seq
[$y] = 1;
1098 } else if (empty($this->in_seq
[$y])) {
1099 $k = $this->_lcs_pos($y);
1100 USE_ASSERTS
&& assert($k > 0);
1101 $ymids[$k] = $ymids[$k-1];
1105 wfProfileOut( __METHOD__
. "-chunk" );
1108 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1109 $ymid = $ymids[$this->lcs
];
1110 for ($n = 0; $n < $nchunks - 1; $n++
) {
1111 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1112 $y1 = $ymid[$n] +
1;
1113 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1115 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1117 wfProfileOut( __METHOD__
);
1118 return array($this->lcs
, $seps);
1121 function _lcs_pos ($ypos) {
1122 wfProfileIn( __METHOD__
);
1125 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1126 $this->seq
[++
$this->lcs
] = $ypos;
1127 $this->in_seq
[$ypos] = 1;
1128 wfProfileOut( __METHOD__
);
1133 while ($beg < $end) {
1134 $mid = (int)(($beg +
$end) / 2);
1135 if ( $ypos > $this->seq
[$mid] )
1141 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1143 $this->in_seq
[$this->seq
[$end]] = false;
1144 $this->seq
[$end] = $ypos;
1145 $this->in_seq
[$ypos] = 1;
1146 wfProfileOut( __METHOD__
);
1150 /* Find LCS of two sequences.
1152 * The results are recorded in the vectors $this->{x,y}changed[], by
1153 * storing a 1 in the element for each line that is an insertion
1154 * or deletion (ie. is not in the LCS).
1156 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1158 * Note that XLIM, YLIM are exclusive bounds.
1159 * All line numbers are origin-0 and discarded lines are not counted.
1161 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1162 wfProfileIn( __METHOD__
);
1164 // Slide down the bottom initial diagonal.
1165 while ($xoff < $xlim && $yoff < $ylim
1166 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1171 // Slide up the top initial diagonal.
1172 while ($xlim > $xoff && $ylim > $yoff
1173 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1178 if ($xoff == $xlim ||
$yoff == $ylim)
1181 // This is ad hoc but seems to work well.
1182 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1183 //$nchunks = max(2,min(8,(int)$nchunks));
1184 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1186 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1190 // X and Y sequences have no common subsequence:
1191 // mark all changed.
1192 while ($yoff < $ylim)
1193 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1194 while ($xoff < $xlim)
1195 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1197 // Use the partitions to split this problem into subproblems.
1200 while ($pt2 = next($seps)) {
1201 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1205 wfProfileOut( __METHOD__
);
1208 /* Adjust inserts/deletes of identical lines to join changes
1209 * as much as possible.
1211 * We do something when a run of changed lines include a
1212 * line at one end and has an excluded, identical line at the other.
1213 * We are free to choose which identical line is included.
1214 * `compareseq' usually chooses the one at the beginning,
1215 * but usually it is cleaner to consider the following identical line
1216 * to be the "change".
1218 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1220 function _shift_boundaries ($lines, &$changed, $other_changed) {
1221 wfProfileIn( __METHOD__
);
1225 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1226 $len = sizeof($lines);
1227 $other_len = sizeof($other_changed);
1231 * Scan forwards to find beginning of another run of changes.
1232 * Also keep track of the corresponding point in the other file.
1234 * Throughout this code, $i and $j are adjusted together so that
1235 * the first $i elements of $changed and the first $j elements
1236 * of $other_changed both contain the same number of zeros
1237 * (unchanged lines).
1238 * Furthermore, $j is always kept so that $j == $other_len or
1239 * $other_changed[$j] == false.
1241 while ($j < $other_len && $other_changed[$j])
1244 while ($i < $len && ! $changed[$i]) {
1245 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1247 while ($j < $other_len && $other_changed[$j])
1256 // Find the end of this run of changes.
1257 while (++
$i < $len && $changed[$i])
1262 * Record the length of this run of changes, so that
1263 * we can later determine whether the run has grown.
1265 $runlength = $i - $start;
1268 * Move the changed region back, so long as the
1269 * previous unchanged line matches the last changed one.
1270 * This merges with previous changed regions.
1272 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1273 $changed[--$start] = 1;
1274 $changed[--$i] = false;
1275 while ($start > 0 && $changed[$start - 1])
1277 USE_ASSERTS
&& assert('$j > 0');
1278 while ($other_changed[--$j])
1280 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1284 * Set CORRESPONDING to the end of the changed run, at the last
1285 * point where it corresponds to a changed run in the other file.
1286 * CORRESPONDING == LEN means no such point has been found.
1288 $corresponding = $j < $other_len ?
$i : $len;
1291 * Move the changed region forward, so long as the
1292 * first changed line matches the following unchanged one.
1293 * This merges with following changed regions.
1294 * Do this second, so that if there are no merges,
1295 * the changed region is moved forward as far as possible.
1297 while ($i < $len && $lines[$start] == $lines[$i]) {
1298 $changed[$start++
] = false;
1300 while ($i < $len && $changed[$i])
1303 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1305 if ($j < $other_len && $other_changed[$j]) {
1306 $corresponding = $i;
1307 while ($j < $other_len && $other_changed[$j])
1311 } while ($runlength != $i - $start);
1314 * If possible, move the fully-merged run of changes
1315 * back to a corresponding run in the other file.
1317 while ($corresponding < $i) {
1318 $changed[--$start] = 1;
1320 USE_ASSERTS
&& assert('$j > 0');
1321 while ($other_changed[--$j])
1323 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1326 wfProfileOut( __METHOD__
);
1331 * Class representing a 'diff' between two sequences of strings.
1334 * @ingroup DifferenceEngine
1342 * Computes diff between sequences of strings.
1344 * @param $from_lines array An array of strings.
1345 * (Typically these are lines from a file.)
1346 * @param $to_lines array An array of strings.
1348 function Diff($from_lines, $to_lines) {
1349 $eng = new _DiffEngine
;
1350 $this->edits
= $eng->diff($from_lines, $to_lines);
1351 //$this->_check($from_lines, $to_lines);
1355 * Compute reversed Diff.
1359 * $diff = new Diff($lines1, $lines2);
1360 * $rev = $diff->reverse();
1361 * @return object A Diff object representing the inverse of the
1364 function reverse () {
1366 $rev->edits
= array();
1367 foreach ($this->edits
as $edit) {
1368 $rev->edits
[] = $edit->reverse();
1374 * Check for empty diff.
1376 * @return bool True iff two sequences were identical.
1378 function isEmpty () {
1379 foreach ($this->edits
as $edit) {
1380 if ($edit->type
!= 'copy')
1387 * Compute the length of the Longest Common Subsequence (LCS).
1389 * This is mostly for diagnostic purposed.
1391 * @return int The length of the LCS.
1395 foreach ($this->edits
as $edit) {
1396 if ($edit->type
== 'copy')
1397 $lcs +
= sizeof($edit->orig
);
1403 * Get the original set of lines.
1405 * This reconstructs the $from_lines parameter passed to the
1408 * @return array The original sequence of strings.
1413 foreach ($this->edits
as $edit) {
1415 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1421 * Get the closing set of lines.
1423 * This reconstructs the $to_lines parameter passed to the
1426 * @return array The sequence of strings.
1428 function closing() {
1431 foreach ($this->edits
as $edit) {
1433 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1439 * Check a Diff for validity.
1441 * This is here only for debugging purposes.
1443 function _check ($from_lines, $to_lines) {
1444 wfProfileIn( __METHOD__
);
1445 if (serialize($from_lines) != serialize($this->orig()))
1446 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1447 if (serialize($to_lines) != serialize($this->closing()))
1448 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1450 $rev = $this->reverse();
1451 if (serialize($to_lines) != serialize($rev->orig()))
1452 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1453 if (serialize($from_lines) != serialize($rev->closing()))
1454 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1458 foreach ($this->edits
as $edit) {
1459 if ( $prevtype == $edit->type
)
1460 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1461 $prevtype = $edit->type
;
1464 $lcs = $this->lcs();
1465 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1466 wfProfileOut( __METHOD__
);
1471 * @todo document, bad name.
1473 * @ingroup DifferenceEngine
1475 class MappedDiff
extends Diff
1480 * Computes diff between sequences of strings.
1482 * This can be used to compute things like
1483 * case-insensitve diffs, or diffs which ignore
1484 * changes in white-space.
1486 * @param $from_lines array An array of strings.
1487 * (Typically these are lines from a file.)
1489 * @param $to_lines array An array of strings.
1491 * @param $mapped_from_lines array This array should
1492 * have the same size number of elements as $from_lines.
1493 * The elements in $mapped_from_lines and
1494 * $mapped_to_lines are what is actually compared
1495 * when computing the diff.
1497 * @param $mapped_to_lines array This array should
1498 * have the same number of elements as $to_lines.
1500 function MappedDiff($from_lines, $to_lines,
1501 $mapped_from_lines, $mapped_to_lines) {
1502 wfProfileIn( __METHOD__
);
1504 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1505 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1507 $this->Diff($mapped_from_lines, $mapped_to_lines);
1510 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1511 $orig = &$this->edits
[$i]->orig
;
1512 if (is_array($orig)) {
1513 $orig = array_slice($from_lines, $xi, sizeof($orig));
1514 $xi +
= sizeof($orig);
1517 $closing = &$this->edits
[$i]->closing
;
1518 if (is_array($closing)) {
1519 $closing = array_slice($to_lines, $yi, sizeof($closing));
1520 $yi +
= sizeof($closing);
1523 wfProfileOut( __METHOD__
);
1528 * A class to format Diffs
1530 * This class formats the diff in classic diff format.
1531 * It is intended that this class be customized via inheritance,
1532 * to obtain fancier outputs.
1535 * @ingroup DifferenceEngine
1537 class DiffFormatter
{
1539 * Number of leading context "lines" to preserve.
1541 * This should be left at zero for this class, but subclasses
1542 * may want to set this to other values.
1544 var $leading_context_lines = 0;
1547 * Number of trailing context "lines" to preserve.
1549 * This should be left at zero for this class, but subclasses
1550 * may want to set this to other values.
1552 var $trailing_context_lines = 0;
1557 * @param $diff object A Diff object.
1558 * @return string The formatted output.
1560 function format($diff) {
1561 wfProfileIn( __METHOD__
);
1567 $nlead = $this->leading_context_lines
;
1568 $ntrail = $this->trailing_context_lines
;
1570 $this->_start_diff();
1572 foreach ($diff->edits
as $edit) {
1573 if ($edit->type
== 'copy') {
1574 if (is_array($block)) {
1575 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1580 $context = array_slice($edit->orig
, 0, $ntrail);
1581 $block[] = new _DiffOp_Copy($context);
1583 $this->_block($x0, $ntrail +
$xi - $x0,
1584 $y0, $ntrail +
$yi - $y0,
1589 $context = $edit->orig
;
1592 if (! is_array($block)) {
1593 $context = array_slice($context, sizeof($context) - $nlead);
1594 $x0 = $xi - sizeof($context);
1595 $y0 = $yi - sizeof($context);
1598 $block[] = new _DiffOp_Copy($context);
1604 $xi +
= sizeof($edit->orig
);
1606 $yi +
= sizeof($edit->closing
);
1609 if (is_array($block))
1610 $this->_block($x0, $xi - $x0,
1614 $end = $this->_end_diff();
1615 wfProfileOut( __METHOD__
);
1619 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1620 wfProfileIn( __METHOD__
);
1621 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1622 foreach ($edits as $edit) {
1623 if ($edit->type
== 'copy')
1624 $this->_context($edit->orig
);
1625 elseif ($edit->type
== 'add')
1626 $this->_added($edit->closing
);
1627 elseif ($edit->type
== 'delete')
1628 $this->_deleted($edit->orig
);
1629 elseif ($edit->type
== 'change')
1630 $this->_changed($edit->orig
, $edit->closing
);
1632 trigger_error('Unknown edit type', E_USER_ERROR
);
1634 $this->_end_block();
1635 wfProfileOut( __METHOD__
);
1638 function _start_diff() {
1642 function _end_diff() {
1643 $val = ob_get_contents();
1648 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1650 $xbeg .= "," . ($xbeg +
$xlen - 1);
1652 $ybeg .= "," . ($ybeg +
$ylen - 1);
1654 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1657 function _start_block($header) {
1658 echo $header . "\n";
1661 function _end_block() {
1664 function _lines($lines, $prefix = ' ') {
1665 foreach ($lines as $line)
1666 echo "$prefix $line\n";
1669 function _context($lines) {
1670 $this->_lines($lines);
1673 function _added($lines) {
1674 $this->_lines($lines, '>');
1676 function _deleted($lines) {
1677 $this->_lines($lines, '<');
1680 function _changed($orig, $closing) {
1681 $this->_deleted($orig);
1683 $this->_added($closing);
1688 * A formatter that outputs unified diffs
1689 * @ingroup DifferenceEngine
1692 class UnifiedDiffFormatter
extends DiffFormatter
{
1693 var $leading_context_lines = 2;
1694 var $trailing_context_lines = 2;
1696 function _added($lines) {
1697 $this->_lines($lines, '+');
1699 function _deleted($lines) {
1700 $this->_lines($lines, '-');
1702 function _changed($orig, $closing) {
1703 $this->_deleted($orig);
1704 $this->_added($closing);
1706 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1707 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1712 * A pseudo-formatter that just passes along the Diff::$edits array
1713 * @ingroup DifferenceEngine
1715 class ArrayDiffFormatter
extends DiffFormatter
{
1716 function format($diff) {
1720 foreach($diff->edits
as $edit)
1721 switch($edit->type
) {
1723 foreach($edit->closing
as $l) {
1727 'newline' => $newline++
1732 foreach($edit->orig
as $l) {
1734 'action' => 'delete',
1736 'oldline' => $oldline++
,
1741 foreach($edit->orig
as $i => $l) {
1743 'action' => 'change',
1745 'new' => @$edit->closing
[$i],
1746 'oldline' => $oldline++
,
1747 'newline' => $newline++
,
1752 $oldline +
= count($edit->orig
);
1753 $newline +
= count($edit->orig
);
1760 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1764 define('NBSP', ' '); // iso-8859-x non-breaking space.
1769 * @ingroup DifferenceEngine
1771 class _HWLDF_WordAccumulator
{
1772 function _HWLDF_WordAccumulator () {
1773 $this->_lines
= array();
1779 function _flushGroup ($new_tag) {
1780 if ($this->_group
!== '') {
1781 if ($this->_tag
== 'ins')
1782 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1783 htmlspecialchars ( $this->_group
) . '</ins>';
1784 elseif ($this->_tag
== 'del')
1785 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1786 htmlspecialchars ( $this->_group
) . '</del>';
1788 $this->_line
.= htmlspecialchars ( $this->_group
);
1791 $this->_tag
= $new_tag;
1794 function _flushLine ($new_tag) {
1795 $this->_flushGroup($new_tag);
1796 if ($this->_line
!= '')
1797 array_push ( $this->_lines
, $this->_line
);
1799 # make empty lines visible by inserting an NBSP
1800 array_push ( $this->_lines
, NBSP
);
1804 function addWords ($words, $tag = '') {
1805 if ($tag != $this->_tag
)
1806 $this->_flushGroup($tag);
1808 foreach ($words as $word) {
1809 // new-line should only come as first char of word.
1812 if ($word[0] == "\n") {
1813 $this->_flushLine($tag);
1814 $word = substr($word, 1);
1816 assert(!strstr($word, "\n"));
1817 $this->_group
.= $word;
1821 function getLines() {
1822 $this->_flushLine('~done');
1823 return $this->_lines
;
1830 * @ingroup DifferenceEngine
1832 class WordLevelDiff
extends MappedDiff
{
1833 const MAX_LINE_LENGTH
= 10000;
1835 function WordLevelDiff ($orig_lines, $closing_lines) {
1836 wfProfileIn( __METHOD__
);
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( __METHOD__
);
1846 function _split($lines) {
1847 wfProfileIn( __METHOD__
);
1850 $stripped = array();
1852 foreach ( $lines as $line ) {
1853 # If the line is too long, just pretend the entire line is one big word
1854 # This prevents resource exhaustion problems
1861 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1863 $stripped[] = $line;
1866 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1869 $words = array_merge( $words, $m[0] );
1870 $stripped = array_merge( $stripped, $m[1] );
1874 wfProfileOut( __METHOD__
);
1875 return array($words, $stripped);
1879 wfProfileIn( __METHOD__
);
1880 $orig = new _HWLDF_WordAccumulator
;
1882 foreach ($this->edits
as $edit) {
1883 if ($edit->type
== 'copy')
1884 $orig->addWords($edit->orig
);
1885 elseif ($edit->orig
)
1886 $orig->addWords($edit->orig
, 'del');
1888 $lines = $orig->getLines();
1889 wfProfileOut( __METHOD__
);
1893 function closing () {
1894 wfProfileIn( __METHOD__
);
1895 $closing = new _HWLDF_WordAccumulator
;
1897 foreach ($this->edits
as $edit) {
1898 if ($edit->type
== 'copy')
1899 $closing->addWords($edit->closing
);
1900 elseif ($edit->closing
)
1901 $closing->addWords($edit->closing
, 'ins');
1903 $lines = $closing->getLines();
1904 wfProfileOut( __METHOD__
);
1910 * Wikipedia Table style diff formatter.
1913 * @ingroup DifferenceEngine
1915 class TableDiffFormatter
extends DiffFormatter
{
1916 function TableDiffFormatter() {
1917 $this->leading_context_lines
= 2;
1918 $this->trailing_context_lines
= 2;
1921 public static function escapeWhiteSpace( $msg ) {
1922 $msg = preg_replace( '/^ /m', ' ', $msg );
1923 $msg = preg_replace( '/ $/m', ' ', $msg );
1924 $msg = preg_replace( '/ /', ' ', $msg );
1928 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1929 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1930 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1934 function _start_block( $header ) {
1938 function _end_block() {
1941 function _lines( $lines, $prefix=' ', $color='white' ) {
1944 # HTML-escape parameter before calling this
1945 function addedLine( $line ) {
1946 return $this->wrapLine( '+', 'diff-addedline', $line );
1949 # HTML-escape parameter before calling this
1950 function deletedLine( $line ) {
1951 return $this->wrapLine( '-', 'diff-deletedline', $line );
1954 # HTML-escape parameter before calling this
1955 function contextLine( $line ) {
1956 return $this->wrapLine( ' ', 'diff-context', $line );
1959 private function wrapLine( $marker, $class, $line ) {
1960 if( $line !== '' ) {
1961 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1962 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1964 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1967 function emptyLine() {
1968 return '<td colspan="2"> </td>';
1971 function _added( $lines ) {
1972 foreach ($lines as $line) {
1973 echo '<tr>' . $this->emptyLine() .
1974 $this->addedLine( '<ins class="diffchange">' .
1975 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1979 function _deleted($lines) {
1980 foreach ($lines as $line) {
1981 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1982 htmlspecialchars ( $line ) . '</del>' ) .
1983 $this->emptyLine() . "</tr>\n";
1987 function _context( $lines ) {
1988 foreach ($lines as $line) {
1990 $this->contextLine( htmlspecialchars ( $line ) ) .
1991 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1995 function _changed( $orig, $closing ) {
1996 wfProfileIn( __METHOD__
);
1998 $diff = new WordLevelDiff( $orig, $closing );
1999 $del = $diff->orig();
2000 $add = $diff->closing();
2002 # Notice that WordLevelDiff returns HTML-escaped output.
2003 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2005 while ( $line = array_shift( $del ) ) {
2006 $aline = array_shift( $add );
2007 echo '<tr>' . $this->deletedLine( $line ) .
2008 $this->addedLine( $aline ) . "</tr>\n";
2010 foreach ($add as $line) { # If any leftovers
2011 echo '<tr>' . $this->emptyLine() .
2012 $this->addedLine( $line ) . "</tr>\n";
2014 wfProfileOut( __METHOD__
);