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?
32 protected $unhide = false;
37 * @param $titleObj Title object that the diff is associated with
38 * @param $old Integer: old ID we want to show and diff with.
39 * @param $new String: either 'prev' or 'next'.
40 * @param $rcid Integer: ??? FIXME (default 0)
41 * @param $refreshCache boolean If set, refreshes the diff cache
42 * @param $htmldiff boolean If set, output using HTMLDiff instead of raw wikicode diff
43 * @param $unhide boolean If set, allow viewing deleted revs
45 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false , $htmldiff = false, $unhide = false ) {
46 $this->mTitle
= $titleObj;
47 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
49 if ( 'prev' === $new ) {
50 # Show diff between revision $old and the previous one.
51 # Get previous one from DB.
52 $this->mNewid
= intval($old);
53 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
54 } elseif ( 'next' === $new ) {
55 # Show diff between revision $old and the previous one.
56 # Get previous one from DB.
58 $this->mOldid
= intval($old);
59 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
60 if ( false === $this->mNewid
) {
61 # if no result, NewId points to the newest old revision. The only newer
62 # revision is cur, which is "0".
66 $this->mOldid
= intval($old);
67 $this->mNewid
= intval($new);
68 wfRunHooks( 'NewDifferenceEngine', array(&$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new) );
70 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
71 $this->mRefreshCache
= $refreshCache;
72 $this->htmldiff
= $htmldiff;
73 $this->unhide
= $unhide;
80 function showDiffPage( $diffOnly = false ) {
81 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
82 wfProfileIn( __METHOD__
);
85 # If external diffs are enabled both globally and for the user,
86 # we'll use the application/x-external-editor interface to call
87 # an external diff tool like kompare, kdiff3, etc.
88 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
89 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
91 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
92 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
93 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
94 $special=$wgLang->getNsText(NS_SPECIAL
);
99 Script={$wgServer}{$wgScript}
100 Special namespace={$special}
114 $wgOut->setArticleFlag( false );
115 if ( !$this->loadRevisionData() ) {
116 $t = $this->mTitle
->getPrefixedText();
117 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
118 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
119 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
120 wfProfileOut( __METHOD__
);
124 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
126 if ( $this->mNewRev
->isCurrent() ) {
127 $wgOut->setArticleFlag( true );
130 # mOldid is false if the difference engine is called with a "vague" query for
131 # a diff between a version V and its previous version V' AND the version V
132 # is the first version of that article. In that case, V' does not exist.
133 if ( $this->mOldid
=== false ) {
134 $this->showFirstRevision();
135 $this->renderNewRevision(); // should we respect $diffOnly here or not?
136 wfProfileOut( __METHOD__
);
140 $wgOut->suppressQuickbar();
142 $oldTitle = $this->mOldPage
->getPrefixedText();
143 $newTitle = $this->mNewPage
->getPrefixedText();
144 if( $oldTitle == $newTitle ) {
145 $wgOut->setPageTitle( $newTitle );
147 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
149 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
150 $wgOut->setRobotPolicy( 'noindex,nofollow' );
152 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
153 $wgOut->loginToUse();
156 wfProfileOut( __METHOD__
);
160 $sk = $wgUser->getSkin();
162 // Check if page is editable
163 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
164 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
165 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
170 // Prepare a change patrol link, if applicable
171 if( $wgUseRCPatrol && $this->mTitle
->userCan('patrol') ) {
172 // If we've been given an explicit change identifier, use it; saves time
173 if( $this->mRcidMarkPatrolled
) {
174 $rcid = $this->mRcidMarkPatrolled
;
175 $rc = RecentChange
::newFromId( $rcid );
176 // Already patrolled?
177 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ?
$rcid : 0;
179 // Look for an unpatrolled change corresponding to this diff
180 $db = wfGetDB( DB_SLAVE
);
181 $change = RecentChange
::newFromConds(
183 // Add redundant user,timestamp condition so we can use the existing index
184 'rc_user_text' => $this->mNewRev
->getRawUserText(),
185 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
186 'rc_this_oldid' => $this->mNewid
,
187 'rc_last_oldid' => $this->mOldid
,
192 if( $change instanceof RecentChange
) {
193 $rcid = $change->mAttribs
['rc_id'];
201 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
203 wfMsgHtml( 'markaspatrolleddiff' ),
204 "action=markpatrolled&rcid={$rcid}"
213 $htmldiffarg = $this->htmlDiffArgument();
214 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
215 'diff=prev&oldid='.$this->mOldid
.$htmldiffarg, '', '', 'id="differences-prevlink"' );
216 if ( $this->mNewRev
->isCurrent() ) {
217 $nextlink = ' ';
219 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
220 'diff=next&oldid='.$this->mNewid
.$htmldiffarg, '', '', 'id="differences-nextlink"' );
226 if( $this->mOldRev
->isMinor() ) {
227 $oldminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
229 if( $this->mNewRev
->isMinor() ) {
230 $newminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
233 $rdel = ''; $ldel = '';
234 if( $wgUser->isAllowed( 'deleterevision' ) ) {
235 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
236 // If revision was hidden from sysops
237 $ldel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
239 $query = array( 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
240 'oldid' => $this->mOldRev
->getId()
242 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
244 $ldel = " $ldel ";
245 // We don't currently handle well changing the top revision's settings
246 if( $this->mNewRev
->isCurrent() ) {
247 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
248 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
249 // If revision was hidden from sysops
250 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
252 $query = array( 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
253 'oldid' => $this->mNewRev
->getId()
255 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
257 $rdel = " $rdel ";
260 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
261 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
262 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
263 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
264 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
265 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
266 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
267 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
269 # Output the diff if allowed
270 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
) && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
271 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
272 if( $deleted && (!$this->unhide ||
!$allowed) ) {
273 $this->showDiffStyle();
274 $multi = $this->getMultiNotice();
275 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
276 $wgOut->addWikiMsg( 'rev-deleted-no-diff' );
277 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
278 $multi = $this->getMultiNotice();
279 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
280 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
281 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
282 $this->renderHtmlDiff();
284 if( $wgEnableHtmlDiff ) {
285 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
286 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
288 $this->showDiff( $oldHeader, $newHeader );
290 $this->renderNewRevision();
293 wfProfileOut( __METHOD__
);
297 * Show the new revision of the page.
299 function renderNewRevision() {
301 wfProfileIn( __METHOD__
);
303 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
304 # Add deleted rev tag if needed
305 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
306 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
307 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
308 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
311 if( !$this->mNewRev
->isCurrent() ) {
312 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
315 $this->loadNewText();
316 if( is_object( $this->mNewRev
) ) {
317 $wgOut->setRevisionId( $this->mNewRev
->getId() );
320 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
321 // Stolen from Article::view --AG 2007-10-11
322 // Give hooks a chance to customise the output
323 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
324 // Wrap the whole lot in a <pre> and don't parse
326 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
327 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
328 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
329 $wgOut->addHTML( "\n</pre>\n" );
332 $wgOut->addWikiTextTidy( $this->mNewtext
);
335 if( !$this->mNewRev
->isCurrent() ) {
336 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
339 wfProfileOut( __METHOD__
);
343 function renderHtmlDiff() {
344 global $wgOut, $wgTitle, $wgParser, $wgDebugComments;
345 wfProfileIn( __METHOD__
);
347 $this->showDiffStyle();
349 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
350 #add deleted rev tag if needed
351 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
352 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
353 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
354 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
357 if( !$this->mNewRev
->isCurrent() ) {
358 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
364 if( is_object( $this->mOldRev
) ) {
365 $wgOut->setRevisionId( $this->mOldRev
->getId() );
368 $popts = $wgOut->parserOptions();
369 $oldTidy = $popts->setTidy( true );
370 $popts->setEditSection( false );
372 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
373 $popts->setTidy( $oldTidy );
376 //$wgOut->addParserOutputNoText( $parserOutput );
377 $oldHtml = $parserOutput->getText();
378 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
381 if( is_object( $this->mNewRev
) ) {
382 $wgOut->setRevisionId( $this->mNewRev
->getId() );
385 $popts = $wgOut->parserOptions();
386 $oldTidy = $popts->setTidy( true );
388 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
389 $popts->setTidy( $oldTidy );
391 $wgOut->addParserOutputNoText( $parserOutput );
392 $newHtml = $parserOutput->getText();
393 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
395 unset($parserOutput, $popts);
397 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
398 $differ->htmlDiff($oldHtml, $newHtml);
399 if ( $wgDebugComments ) {
400 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
403 wfProfileOut( __METHOD__
);
407 * Show the first revision of an article. Uses normal diff headers in
408 * contrast to normal "old revision" display style.
410 function showFirstRevision() {
411 global $wgOut, $wgUser;
412 wfProfileIn( __METHOD__
);
414 # Get article text from the DB
416 if ( ! $this->loadNewText() ) {
417 $t = $this->mTitle
->getPrefixedText();
418 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
419 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
420 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
421 wfProfileOut( __METHOD__
);
424 if ( $this->mNewRev
->isCurrent() ) {
425 $wgOut->setArticleFlag( true );
428 # Check if user is allowed to look at this page. If not, bail out.
430 if ( !$this->mTitle
->userCanRead() ) {
431 $wgOut->loginToUse();
433 wfProfileOut( __METHOD__
);
434 throw new MWException("Permission Error: you do not have access to view this page");
437 # Prepare the header box
439 $sk = $wgUser->getSkin();
441 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
445 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
446 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
448 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
449 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
451 $wgOut->addHTML( $header );
453 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
454 $wgOut->setRobotPolicy( 'noindex,nofollow' );
456 wfProfileOut( __METHOD__
);
459 function htmlDiffArgument(){
460 global $wgEnableHtmlDiff;
461 if($wgEnableHtmlDiff){
463 return '&htmldiff=1';
465 return '&htmldiff=0';
473 * Get the diff text, send it to $wgOut
474 * Returns false if the diff could not be generated, otherwise returns true
476 function showDiff( $otitle, $ntitle ) {
478 $diff = $this->getDiff( $otitle, $ntitle );
479 if ( $diff === false ) {
480 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
483 $this->showDiffStyle();
484 $wgOut->addHTML( $diff );
490 * Add style sheets and supporting JS for diff display.
492 function showDiffStyle() {
493 global $wgStylePath, $wgStyleVersion, $wgOut;
494 $wgOut->addStyle( 'common/diff.css' );
496 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
497 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
501 * Get complete diff table, including header
503 * @param Title $otitle Old title
504 * @param Title $ntitle New title
507 function getDiff( $otitle, $ntitle ) {
508 $body = $this->getDiffBody();
509 if ( $body === false ) {
512 $multi = $this->getMultiNotice();
513 return $this->addHeader( $body, $otitle, $ntitle, $multi );
518 * Get the diff table body, without header
522 function getDiffBody() {
524 wfProfileIn( __METHOD__
);
525 // Check if the diff should be hidden from this user
526 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
528 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
533 if ( $this->mOldid
&& $this->mNewid
) {
534 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
536 if ( !$this->mRefreshCache
) {
537 $difftext = $wgMemc->get( $key );
539 wfIncrStats( 'diff_cache_hit' );
540 $difftext = $this->localiseLineNumbers( $difftext );
541 $difftext .= "\n<!-- diff cache key $key -->\n";
542 wfProfileOut( __METHOD__
);
545 } // don't try to load but save the result
548 // Loadtext is permission safe, this just clears out the diff
549 if ( !$this->loadText() ) {
550 wfProfileOut( __METHOD__
);
554 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
556 // Save to cache for 7 days
557 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
558 wfIncrStats( 'diff_uncacheable' );
559 } else if ( $key !== false && $difftext !== false ) {
560 wfIncrStats( 'diff_cache_miss' );
561 $wgMemc->set( $key, $difftext, 7*86400 );
563 wfIncrStats( 'diff_uncacheable' );
565 // Replace line numbers with the text in the user's language
566 if ( $difftext !== false ) {
567 $difftext = $this->localiseLineNumbers( $difftext );
569 wfProfileOut( __METHOD__
);
574 * Generate a diff, no caching
575 * $otext and $ntext must be already segmented
577 function generateDiffBody( $otext, $ntext ) {
578 global $wgExternalDiffEngine, $wgContLang;
580 $otext = str_replace( "\r\n", "\n", $otext );
581 $ntext = str_replace( "\r\n", "\n", $ntext );
583 if ( $wgExternalDiffEngine == 'wikidiff' ) {
584 # For historical reasons, external diff engine expects
585 # input text to be HTML-escaped already
586 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
587 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
588 if( !function_exists( 'wikidiff_do_diff' ) ) {
589 dl('php_wikidiff.so');
591 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
592 $this->debug( 'wikidiff1' );
595 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
596 # Better external diff engine, the 2 may some day be dropped
597 # This one does the escaping and segmenting itself
598 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
599 wfProfileIn( __METHOD__
. "-dl" );
600 @dl
('php_wikidiff2.so');
601 wfProfileOut( __METHOD__
. "-dl" );
603 if ( function_exists( 'wikidiff2_do_diff' ) ) {
604 wfProfileIn( 'wikidiff2_do_diff' );
605 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
606 $text .= $this->debug( 'wikidiff2' );
607 wfProfileOut( 'wikidiff2_do_diff' );
611 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
613 global $wgTmpDirectory;
614 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
615 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
617 $tempFile1 = fopen( $tempName1, "w" );
619 wfProfileOut( __METHOD__
);
622 $tempFile2 = fopen( $tempName2, "w" );
624 wfProfileOut( __METHOD__
);
627 fwrite( $tempFile1, $otext );
628 fwrite( $tempFile2, $ntext );
629 fclose( $tempFile1 );
630 fclose( $tempFile2 );
631 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
632 wfProfileIn( __METHOD__
. "-shellexec" );
633 $difftext = wfShellExec( $cmd );
634 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
635 wfProfileOut( __METHOD__
. "-shellexec" );
636 unlink( $tempName1 );
637 unlink( $tempName2 );
642 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
643 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
644 $diffs = new Diff( $ota, $nta );
645 $formatter = new TableDiffFormatter();
646 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
651 * Generate a debug comment indicating diff generating time,
652 * server node, and generator backend.
654 protected function debug( $generator="internal" ) {
655 global $wgShowHostnames;
656 $data = array( $generator );
657 if( $wgShowHostnames ) {
658 $data[] = wfHostname();
660 $data[] = wfTimestamp( TS_DB
);
661 return "<!-- diff generator: " .
670 * Replace line numbers with the text in the user's language
672 function localiseLineNumbers( $text ) {
673 return preg_replace_callback( '/<!--LINE (\d+)-->/',
674 array( &$this, 'localiseLineNumbersCb' ), $text );
677 function localiseLineNumbersCb( $matches ) {
679 return wfMsgExt( 'lineno', array( 'parseinline' ), $wgLang->formatNum( $matches[1] ) );
684 * If there are revisions between the ones being compared, return a note saying so.
686 function getMultiNotice() {
687 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
690 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
691 // Comparing two different pages? Count would be meaningless.
695 $oldid = $this->mOldRev
->getId();
696 $newid = $this->mNewRev
->getId();
697 if ( $oldid > $newid ) {
698 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
701 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
705 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
710 * Add the header to a diff body
712 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
715 <col class='diff-marker' />
716 <col class='diff-content' />
717 <col class='diff-marker' />
718 <col class='diff-content' />
720 <td colspan='2' class='diff-otitle'>{$otitle}</td>
721 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
726 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
728 return $header . $diff . "</table>";
732 * Use specified text instead of loading from the database
734 function setText( $oldText, $newText ) {
735 $this->mOldtext
= $oldText;
736 $this->mNewtext
= $newText;
737 $this->mTextLoaded
= 2;
741 * Load revision metadata for the specified articles. If newid is 0, then compare
742 * the old article in oldid to the current article; if oldid is 0, then
743 * compare the current article to the immediately previous one (ignoring the
746 * If oldid is false, leave the corresponding revision object set
747 * to false. This is impossible via ordinary user input, and is provided for
750 function loadRevisionData() {
751 global $wgLang, $wgUser;
752 if ( $this->mRevisionsLoaded
) {
755 // Whether it succeeds or fails, we don't want to try again
756 $this->mRevisionsLoaded
= true;
759 // Load the new revision object
760 $this->mNewRev
= $this->mNewid
761 ? Revision
::newFromId( $this->mNewid
)
762 : Revision
::newFromTitle( $this->mTitle
);
763 if( !$this->mNewRev
instanceof Revision
)
766 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
767 $this->mNewid
= $this->mNewRev
->getId();
769 // Check if page is editable
770 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
772 // Set assorted variables
773 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
774 $this->mNewPage
= $this->mNewRev
->getTitle();
775 if( $this->mNewRev
->isCurrent() ) {
776 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
777 $this->mPagetitle
= wfMsgHTML( 'currentrev-asof', $timestamp );
778 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
780 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
781 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
784 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
785 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
786 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
788 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
789 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
791 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
792 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
793 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
794 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
797 // Load the old revision object
798 $this->mOldRev
= false;
799 if( $this->mOldid
) {
800 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
801 } elseif ( $this->mOldid
=== 0 ) {
802 $rev = $this->mNewRev
->getPrevious();
804 $this->mOldid
= $rev->getId();
805 $this->mOldRev
= $rev;
807 // No previous revision; mark to show as first-version only.
808 $this->mOldid
= false;
809 $this->mOldRev
= false;
811 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
813 if( is_null( $this->mOldRev
) ) {
817 if ( $this->mOldRev
) {
818 $this->mOldPage
= $this->mOldRev
->getTitle();
820 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
821 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
822 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
823 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
825 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
826 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
827 // Add an "undo" link
828 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
829 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
830 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
831 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
832 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
835 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
836 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
837 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
838 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
846 * Load the text of the revisions, as well as revision data.
848 function loadText() {
849 if ( $this->mTextLoaded
== 2 ) {
852 // Whether it succeeds or fails, we don't want to try again
853 $this->mTextLoaded
= 2;
856 if ( !$this->loadRevisionData() ) {
859 if ( $this->mOldRev
) {
860 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
861 if ( $this->mOldtext
=== false ) {
865 if ( $this->mNewRev
) {
866 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
867 if ( $this->mNewtext
=== false ) {
875 * Load the text of the new revision, not the old one
877 function loadNewText() {
878 if ( $this->mTextLoaded
>= 1 ) {
881 $this->mTextLoaded
= 1;
883 if ( !$this->loadRevisionData() ) {
886 $this->mNewtext
= $this->mNewRev
->getText();
893 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
895 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
896 // You may copy this code freely under the conditions of the GPL.
899 define('USE_ASSERTS', function_exists('assert'));
904 * @ingroup DifferenceEngine
912 trigger_error('pure virtual', E_USER_ERROR
);
916 return $this->orig ?
sizeof($this->orig
) : 0;
919 function nclosing() {
920 return $this->closing ?
sizeof($this->closing
) : 0;
927 * @ingroup DifferenceEngine
929 class _DiffOp_Copy
extends _DiffOp
{
932 function _DiffOp_Copy ($orig, $closing = false) {
933 if (!is_array($closing))
936 $this->closing
= $closing;
940 return new _DiffOp_Copy($this->closing
, $this->orig
);
947 * @ingroup DifferenceEngine
949 class _DiffOp_Delete
extends _DiffOp
{
950 var $type = 'delete';
952 function _DiffOp_Delete ($lines) {
953 $this->orig
= $lines;
954 $this->closing
= false;
958 return new _DiffOp_Add($this->orig
);
965 * @ingroup DifferenceEngine
967 class _DiffOp_Add
extends _DiffOp
{
970 function _DiffOp_Add ($lines) {
971 $this->closing
= $lines;
976 return new _DiffOp_Delete($this->closing
);
983 * @ingroup DifferenceEngine
985 class _DiffOp_Change
extends _DiffOp
{
986 var $type = 'change';
988 function _DiffOp_Change ($orig, $closing) {
990 $this->closing
= $closing;
994 return new _DiffOp_Change($this->closing
, $this->orig
);
999 * Class used internally by Diff to actually compute the diffs.
1001 * The algorithm used here is mostly lifted from the perl module
1002 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1003 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1005 * More ideas are taken from:
1006 * http://www.ics.uci.edu/~eppstein/161/960229.html
1008 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1009 * diffutils-2.7, which can be found at:
1010 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1012 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1015 * Line length limits for robustness added by Tim Starling, 2005-08-31
1016 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1018 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1020 * @ingroup DifferenceEngine
1024 const MAX_XREF_LENGTH
= 10000;
1026 function diff ($from_lines, $to_lines){
1027 wfProfileIn( __METHOD__
);
1029 // Diff and store locally
1030 $this->diff_local($from_lines, $to_lines);
1032 // Merge edits when possible
1033 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1034 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1036 // Compute the edit operations.
1037 $n_from = sizeof($from_lines);
1038 $n_to = sizeof($to_lines);
1042 while ($xi < $n_from ||
$yi < $n_to) {
1043 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1044 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1046 // Skip matching "snake".
1048 while ( $xi < $n_from && $yi < $n_to
1049 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1050 $copy[] = $from_lines[$xi++
];
1054 $edits[] = new _DiffOp_Copy($copy);
1056 // Find deletes & adds.
1058 while ($xi < $n_from && $this->xchanged
[$xi])
1059 $delete[] = $from_lines[$xi++
];
1062 while ($yi < $n_to && $this->ychanged
[$yi])
1063 $add[] = $to_lines[$yi++
];
1065 if ($delete && $add)
1066 $edits[] = new _DiffOp_Change($delete, $add);
1068 $edits[] = new _DiffOp_Delete($delete);
1070 $edits[] = new _DiffOp_Add($add);
1072 wfProfileOut( __METHOD__
);
1076 function diff_local ($from_lines, $to_lines) {
1077 global $wgExternalDiffEngine;
1078 wfProfileIn( __METHOD__
);
1080 if($wgExternalDiffEngine == 'wikidiff3'){
1082 $wikidiff3 = new WikiDiff3();
1083 $wikidiff3->diff($from_lines, $to_lines);
1084 $this->xchanged
= $wikidiff3->removed
;
1085 $this->ychanged
= $wikidiff3->added
;
1089 $n_from = sizeof($from_lines);
1090 $n_to = sizeof($to_lines);
1091 $this->xchanged
= $this->ychanged
= array();
1092 $this->xv
= $this->yv
= array();
1093 $this->xind
= $this->yind
= array();
1095 unset($this->in_seq
);
1098 // Skip leading common lines.
1099 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1100 if ($from_lines[$skip] !== $to_lines[$skip])
1102 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1104 // Skip trailing common lines.
1105 $xi = $n_from; $yi = $n_to;
1106 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1107 if ($from_lines[$xi] !== $to_lines[$yi])
1109 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1112 // Ignore lines which do not exist in both files.
1113 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1114 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1117 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1118 $line = $to_lines[$yi];
1119 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1121 $yhash[$this->_line_hash($line)] = 1;
1122 $this->yv
[] = $line;
1123 $this->yind
[] = $yi;
1125 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1126 $line = $from_lines[$xi];
1127 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1129 $this->xv
[] = $line;
1130 $this->xind
[] = $xi;
1134 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1136 wfProfileOut( __METHOD__
);
1140 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1142 function _line_hash( $line ) {
1143 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1144 return md5( $line );
1150 /* Divide the Largest Common Subsequence (LCS) of the sequences
1151 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1154 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1155 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1156 * sub sequences. The first sub-sequence is contained in [X0, X1),
1157 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1158 * that (X0, Y0) == (XOFF, YOFF) and
1159 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1161 * This function assumes that the first lines of the specified portions
1162 * of the two files do not match, and likewise that the last lines do not
1163 * match. The caller must trim matching lines from the beginning and end
1164 * of the portions it is going to specify.
1166 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1169 if ($xlim - $xoff > $ylim - $yoff) {
1170 // Things seems faster (I'm not sure I understand why)
1171 // when the shortest sequence in X.
1173 list ($xoff, $xlim, $yoff, $ylim)
1174 = array( $yoff, $ylim, $xoff, $xlim);
1178 for ($i = $ylim - 1; $i >= $yoff; $i--)
1179 $ymatches[$this->xv
[$i]][] = $i;
1181 for ($i = $ylim - 1; $i >= $yoff; $i--)
1182 $ymatches[$this->yv
[$i]][] = $i;
1185 $this->seq
[0]= $yoff - 1;
1186 $this->in_seq
= array();
1187 $ymids[0] = array();
1189 $numer = $xlim - $xoff +
$nchunks - 1;
1191 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1193 for ($i = 0; $i <= $this->lcs
; $i++
)
1194 $ymids[$i][$chunk-1] = $this->seq
[$i];
1196 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1197 for ( ; $x < $x1; $x++
) {
1198 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1199 if (empty($ymatches[$line]))
1201 $matches = $ymatches[$line];
1203 while (list ($junk, $y) = each($matches))
1204 if (empty($this->in_seq
[$y])) {
1205 $k = $this->_lcs_pos($y);
1206 USE_ASSERTS
&& assert($k > 0);
1207 $ymids[$k] = $ymids[$k-1];
1210 while (list ( /* $junk */, $y) = each($matches)) {
1211 if ($y > $this->seq
[$k-1]) {
1212 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1213 // Optimization: this is a common case:
1214 // next match is just replacing previous match.
1215 $this->in_seq
[$this->seq
[$k]] = false;
1216 $this->seq
[$k] = $y;
1217 $this->in_seq
[$y] = 1;
1218 } else if (empty($this->in_seq
[$y])) {
1219 $k = $this->_lcs_pos($y);
1220 USE_ASSERTS
&& assert($k > 0);
1221 $ymids[$k] = $ymids[$k-1];
1227 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1228 $ymid = $ymids[$this->lcs
];
1229 for ($n = 0; $n < $nchunks - 1; $n++
) {
1230 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1231 $y1 = $ymid[$n] +
1;
1232 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1234 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1236 return array($this->lcs
, $seps);
1239 function _lcs_pos ($ypos) {
1241 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1242 $this->seq
[++
$this->lcs
] = $ypos;
1243 $this->in_seq
[$ypos] = 1;
1248 while ($beg < $end) {
1249 $mid = (int)(($beg +
$end) / 2);
1250 if ( $ypos > $this->seq
[$mid] )
1256 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1258 $this->in_seq
[$this->seq
[$end]] = false;
1259 $this->seq
[$end] = $ypos;
1260 $this->in_seq
[$ypos] = 1;
1264 /* Find LCS of two sequences.
1266 * The results are recorded in the vectors $this->{x,y}changed[], by
1267 * storing a 1 in the element for each line that is an insertion
1268 * or deletion (ie. is not in the LCS).
1270 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1272 * Note that XLIM, YLIM are exclusive bounds.
1273 * All line numbers are origin-0 and discarded lines are not counted.
1275 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1276 // Slide down the bottom initial diagonal.
1277 while ($xoff < $xlim && $yoff < $ylim
1278 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1283 // Slide up the top initial diagonal.
1284 while ($xlim > $xoff && $ylim > $yoff
1285 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1290 if ($xoff == $xlim ||
$yoff == $ylim)
1293 // This is ad hoc but seems to work well.
1294 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1295 //$nchunks = max(2,min(8,(int)$nchunks));
1296 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1298 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1302 // X and Y sequences have no common subsequence:
1303 // mark all changed.
1304 while ($yoff < $ylim)
1305 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1306 while ($xoff < $xlim)
1307 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1309 // Use the partitions to split this problem into subproblems.
1312 while ($pt2 = next($seps)) {
1313 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1319 /* Adjust inserts/deletes of identical lines to join changes
1320 * as much as possible.
1322 * We do something when a run of changed lines include a
1323 * line at one end and has an excluded, identical line at the other.
1324 * We are free to choose which identical line is included.
1325 * `compareseq' usually chooses the one at the beginning,
1326 * but usually it is cleaner to consider the following identical line
1327 * to be the "change".
1329 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1331 function _shift_boundaries ($lines, &$changed, $other_changed) {
1332 wfProfileIn( __METHOD__
);
1336 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1337 $len = sizeof($lines);
1338 $other_len = sizeof($other_changed);
1342 * Scan forwards to find beginning of another run of changes.
1343 * Also keep track of the corresponding point in the other file.
1345 * Throughout this code, $i and $j are adjusted together so that
1346 * the first $i elements of $changed and the first $j elements
1347 * of $other_changed both contain the same number of zeros
1348 * (unchanged lines).
1349 * Furthermore, $j is always kept so that $j == $other_len or
1350 * $other_changed[$j] == false.
1352 while ($j < $other_len && $other_changed[$j])
1355 while ($i < $len && ! $changed[$i]) {
1356 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1358 while ($j < $other_len && $other_changed[$j])
1367 // Find the end of this run of changes.
1368 while (++
$i < $len && $changed[$i])
1373 * Record the length of this run of changes, so that
1374 * we can later determine whether the run has grown.
1376 $runlength = $i - $start;
1379 * Move the changed region back, so long as the
1380 * previous unchanged line matches the last changed one.
1381 * This merges with previous changed regions.
1383 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1384 $changed[--$start] = 1;
1385 $changed[--$i] = false;
1386 while ($start > 0 && $changed[$start - 1])
1388 USE_ASSERTS
&& assert('$j > 0');
1389 while ($other_changed[--$j])
1391 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1395 * Set CORRESPONDING to the end of the changed run, at the last
1396 * point where it corresponds to a changed run in the other file.
1397 * CORRESPONDING == LEN means no such point has been found.
1399 $corresponding = $j < $other_len ?
$i : $len;
1402 * Move the changed region forward, so long as the
1403 * first changed line matches the following unchanged one.
1404 * This merges with following changed regions.
1405 * Do this second, so that if there are no merges,
1406 * the changed region is moved forward as far as possible.
1408 while ($i < $len && $lines[$start] == $lines[$i]) {
1409 $changed[$start++
] = false;
1411 while ($i < $len && $changed[$i])
1414 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1416 if ($j < $other_len && $other_changed[$j]) {
1417 $corresponding = $i;
1418 while ($j < $other_len && $other_changed[$j])
1422 } while ($runlength != $i - $start);
1425 * If possible, move the fully-merged run of changes
1426 * back to a corresponding run in the other file.
1428 while ($corresponding < $i) {
1429 $changed[--$start] = 1;
1431 USE_ASSERTS
&& assert('$j > 0');
1432 while ($other_changed[--$j])
1434 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1437 wfProfileOut( __METHOD__
);
1442 * Class representing a 'diff' between two sequences of strings.
1445 * @ingroup DifferenceEngine
1453 * Computes diff between sequences of strings.
1455 * @param $from_lines array An array of strings.
1456 * (Typically these are lines from a file.)
1457 * @param $to_lines array An array of strings.
1459 function Diff($from_lines, $to_lines) {
1460 $eng = new _DiffEngine
;
1461 $this->edits
= $eng->diff($from_lines, $to_lines);
1462 //$this->_check($from_lines, $to_lines);
1466 * Compute reversed Diff.
1470 * $diff = new Diff($lines1, $lines2);
1471 * $rev = $diff->reverse();
1472 * @return object A Diff object representing the inverse of the
1475 function reverse () {
1477 $rev->edits
= array();
1478 foreach ($this->edits
as $edit) {
1479 $rev->edits
[] = $edit->reverse();
1485 * Check for empty diff.
1487 * @return bool True iff two sequences were identical.
1489 function isEmpty () {
1490 foreach ($this->edits
as $edit) {
1491 if ($edit->type
!= 'copy')
1498 * Compute the length of the Longest Common Subsequence (LCS).
1500 * This is mostly for diagnostic purposed.
1502 * @return int The length of the LCS.
1506 foreach ($this->edits
as $edit) {
1507 if ($edit->type
== 'copy')
1508 $lcs +
= sizeof($edit->orig
);
1514 * Get the original set of lines.
1516 * This reconstructs the $from_lines parameter passed to the
1519 * @return array The original sequence of strings.
1524 foreach ($this->edits
as $edit) {
1526 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1532 * Get the closing set of lines.
1534 * This reconstructs the $to_lines parameter passed to the
1537 * @return array The sequence of strings.
1539 function closing() {
1542 foreach ($this->edits
as $edit) {
1544 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1550 * Check a Diff for validity.
1552 * This is here only for debugging purposes.
1554 function _check ($from_lines, $to_lines) {
1555 wfProfileIn( __METHOD__
);
1556 if (serialize($from_lines) != serialize($this->orig()))
1557 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1558 if (serialize($to_lines) != serialize($this->closing()))
1559 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1561 $rev = $this->reverse();
1562 if (serialize($to_lines) != serialize($rev->orig()))
1563 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1564 if (serialize($from_lines) != serialize($rev->closing()))
1565 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1569 foreach ($this->edits
as $edit) {
1570 if ( $prevtype == $edit->type
)
1571 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1572 $prevtype = $edit->type
;
1575 $lcs = $this->lcs();
1576 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1577 wfProfileOut( __METHOD__
);
1582 * @todo document, bad name.
1584 * @ingroup DifferenceEngine
1586 class MappedDiff
extends Diff
1591 * Computes diff between sequences of strings.
1593 * This can be used to compute things like
1594 * case-insensitve diffs, or diffs which ignore
1595 * changes in white-space.
1597 * @param $from_lines array An array of strings.
1598 * (Typically these are lines from a file.)
1600 * @param $to_lines array An array of strings.
1602 * @param $mapped_from_lines array This array should
1603 * have the same size number of elements as $from_lines.
1604 * The elements in $mapped_from_lines and
1605 * $mapped_to_lines are what is actually compared
1606 * when computing the diff.
1608 * @param $mapped_to_lines array This array should
1609 * have the same number of elements as $to_lines.
1611 function MappedDiff($from_lines, $to_lines,
1612 $mapped_from_lines, $mapped_to_lines) {
1613 wfProfileIn( __METHOD__
);
1615 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1616 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1618 $this->Diff($mapped_from_lines, $mapped_to_lines);
1621 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1622 $orig = &$this->edits
[$i]->orig
;
1623 if (is_array($orig)) {
1624 $orig = array_slice($from_lines, $xi, sizeof($orig));
1625 $xi +
= sizeof($orig);
1628 $closing = &$this->edits
[$i]->closing
;
1629 if (is_array($closing)) {
1630 $closing = array_slice($to_lines, $yi, sizeof($closing));
1631 $yi +
= sizeof($closing);
1634 wfProfileOut( __METHOD__
);
1639 * A class to format Diffs
1641 * This class formats the diff in classic diff format.
1642 * It is intended that this class be customized via inheritance,
1643 * to obtain fancier outputs.
1646 * @ingroup DifferenceEngine
1648 class DiffFormatter
{
1650 * Number of leading context "lines" to preserve.
1652 * This should be left at zero for this class, but subclasses
1653 * may want to set this to other values.
1655 var $leading_context_lines = 0;
1658 * Number of trailing context "lines" to preserve.
1660 * This should be left at zero for this class, but subclasses
1661 * may want to set this to other values.
1663 var $trailing_context_lines = 0;
1668 * @param $diff object A Diff object.
1669 * @return string The formatted output.
1671 function format($diff) {
1672 wfProfileIn( __METHOD__
);
1678 $nlead = $this->leading_context_lines
;
1679 $ntrail = $this->trailing_context_lines
;
1681 $this->_start_diff();
1683 foreach ($diff->edits
as $edit) {
1684 if ($edit->type
== 'copy') {
1685 if (is_array($block)) {
1686 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1691 $context = array_slice($edit->orig
, 0, $ntrail);
1692 $block[] = new _DiffOp_Copy($context);
1694 $this->_block($x0, $ntrail +
$xi - $x0,
1695 $y0, $ntrail +
$yi - $y0,
1700 $context = $edit->orig
;
1703 if (! is_array($block)) {
1704 $context = array_slice($context, sizeof($context) - $nlead);
1705 $x0 = $xi - sizeof($context);
1706 $y0 = $yi - sizeof($context);
1709 $block[] = new _DiffOp_Copy($context);
1715 $xi +
= sizeof($edit->orig
);
1717 $yi +
= sizeof($edit->closing
);
1720 if (is_array($block))
1721 $this->_block($x0, $xi - $x0,
1725 $end = $this->_end_diff();
1726 wfProfileOut( __METHOD__
);
1730 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1731 wfProfileIn( __METHOD__
);
1732 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1733 foreach ($edits as $edit) {
1734 if ($edit->type
== 'copy')
1735 $this->_context($edit->orig
);
1736 elseif ($edit->type
== 'add')
1737 $this->_added($edit->closing
);
1738 elseif ($edit->type
== 'delete')
1739 $this->_deleted($edit->orig
);
1740 elseif ($edit->type
== 'change')
1741 $this->_changed($edit->orig
, $edit->closing
);
1743 trigger_error('Unknown edit type', E_USER_ERROR
);
1745 $this->_end_block();
1746 wfProfileOut( __METHOD__
);
1749 function _start_diff() {
1753 function _end_diff() {
1754 $val = ob_get_contents();
1759 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1761 $xbeg .= "," . ($xbeg +
$xlen - 1);
1763 $ybeg .= "," . ($ybeg +
$ylen - 1);
1765 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1768 function _start_block($header) {
1769 echo $header . "\n";
1772 function _end_block() {
1775 function _lines($lines, $prefix = ' ') {
1776 foreach ($lines as $line)
1777 echo "$prefix $line\n";
1780 function _context($lines) {
1781 $this->_lines($lines);
1784 function _added($lines) {
1785 $this->_lines($lines, '>');
1787 function _deleted($lines) {
1788 $this->_lines($lines, '<');
1791 function _changed($orig, $closing) {
1792 $this->_deleted($orig);
1794 $this->_added($closing);
1799 * A formatter that outputs unified diffs
1800 * @ingroup DifferenceEngine
1803 class UnifiedDiffFormatter
extends DiffFormatter
{
1804 var $leading_context_lines = 2;
1805 var $trailing_context_lines = 2;
1807 function _added($lines) {
1808 $this->_lines($lines, '+');
1810 function _deleted($lines) {
1811 $this->_lines($lines, '-');
1813 function _changed($orig, $closing) {
1814 $this->_deleted($orig);
1815 $this->_added($closing);
1817 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1818 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1823 * A pseudo-formatter that just passes along the Diff::$edits array
1824 * @ingroup DifferenceEngine
1826 class ArrayDiffFormatter
extends DiffFormatter
{
1827 function format($diff) {
1831 foreach($diff->edits
as $edit)
1832 switch($edit->type
) {
1834 foreach($edit->closing
as $l) {
1838 'newline' => $newline++
1843 foreach($edit->orig
as $l) {
1845 'action' => 'delete',
1847 'oldline' => $oldline++
,
1852 foreach($edit->orig
as $i => $l) {
1854 'action' => 'change',
1856 'new' => @$edit->closing
[$i],
1857 'oldline' => $oldline++
,
1858 'newline' => $newline++
,
1863 $oldline +
= count($edit->orig
);
1864 $newline +
= count($edit->orig
);
1871 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1875 define('NBSP', ' '); // iso-8859-x non-breaking space.
1880 * @ingroup DifferenceEngine
1882 class _HWLDF_WordAccumulator
{
1883 function _HWLDF_WordAccumulator () {
1884 $this->_lines
= array();
1890 function _flushGroup ($new_tag) {
1891 if ($this->_group
!== '') {
1892 if ($this->_tag
== 'ins')
1893 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1894 htmlspecialchars ( $this->_group
) . '</ins>';
1895 elseif ($this->_tag
== 'del')
1896 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1897 htmlspecialchars ( $this->_group
) . '</del>';
1899 $this->_line
.= htmlspecialchars ( $this->_group
);
1902 $this->_tag
= $new_tag;
1905 function _flushLine ($new_tag) {
1906 $this->_flushGroup($new_tag);
1907 if ($this->_line
!= '')
1908 array_push ( $this->_lines
, $this->_line
);
1910 # make empty lines visible by inserting an NBSP
1911 array_push ( $this->_lines
, NBSP
);
1915 function addWords ($words, $tag = '') {
1916 if ($tag != $this->_tag
)
1917 $this->_flushGroup($tag);
1919 foreach ($words as $word) {
1920 // new-line should only come as first char of word.
1923 if ($word[0] == "\n") {
1924 $this->_flushLine($tag);
1925 $word = substr($word, 1);
1927 assert(!strstr($word, "\n"));
1928 $this->_group
.= $word;
1932 function getLines() {
1933 $this->_flushLine('~done');
1934 return $this->_lines
;
1941 * @ingroup DifferenceEngine
1943 class WordLevelDiff
extends MappedDiff
{
1944 const MAX_LINE_LENGTH
= 10000;
1946 function WordLevelDiff ($orig_lines, $closing_lines) {
1947 wfProfileIn( __METHOD__
);
1949 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1950 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1952 $this->MappedDiff($orig_words, $closing_words,
1953 $orig_stripped, $closing_stripped);
1954 wfProfileOut( __METHOD__
);
1957 function _split($lines) {
1958 wfProfileIn( __METHOD__
);
1961 $stripped = array();
1963 foreach ( $lines as $line ) {
1964 # If the line is too long, just pretend the entire line is one big word
1965 # This prevents resource exhaustion problems
1972 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1974 $stripped[] = $line;
1977 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1980 $words = array_merge( $words, $m[0] );
1981 $stripped = array_merge( $stripped, $m[1] );
1985 wfProfileOut( __METHOD__
);
1986 return array($words, $stripped);
1990 wfProfileIn( __METHOD__
);
1991 $orig = new _HWLDF_WordAccumulator
;
1993 foreach ($this->edits
as $edit) {
1994 if ($edit->type
== 'copy')
1995 $orig->addWords($edit->orig
);
1996 elseif ($edit->orig
)
1997 $orig->addWords($edit->orig
, 'del');
1999 $lines = $orig->getLines();
2000 wfProfileOut( __METHOD__
);
2004 function closing () {
2005 wfProfileIn( __METHOD__
);
2006 $closing = new _HWLDF_WordAccumulator
;
2008 foreach ($this->edits
as $edit) {
2009 if ($edit->type
== 'copy')
2010 $closing->addWords($edit->closing
);
2011 elseif ($edit->closing
)
2012 $closing->addWords($edit->closing
, 'ins');
2014 $lines = $closing->getLines();
2015 wfProfileOut( __METHOD__
);
2021 * Wikipedia Table style diff formatter.
2024 * @ingroup DifferenceEngine
2026 class TableDiffFormatter
extends DiffFormatter
{
2027 function TableDiffFormatter() {
2028 $this->leading_context_lines
= 2;
2029 $this->trailing_context_lines
= 2;
2032 public static function escapeWhiteSpace( $msg ) {
2033 $msg = preg_replace( '/^ /m', ' ', $msg );
2034 $msg = preg_replace( '/ $/m', ' ', $msg );
2035 $msg = preg_replace( '/ /', ' ', $msg );
2039 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2040 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2041 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2045 function _start_block( $header ) {
2049 function _end_block() {
2052 function _lines( $lines, $prefix=' ', $color='white' ) {
2055 # HTML-escape parameter before calling this
2056 function addedLine( $line ) {
2057 return $this->wrapLine( '+', 'diff-addedline', $line );
2060 # HTML-escape parameter before calling this
2061 function deletedLine( $line ) {
2062 return $this->wrapLine( '-', 'diff-deletedline', $line );
2065 # HTML-escape parameter before calling this
2066 function contextLine( $line ) {
2067 return $this->wrapLine( ' ', 'diff-context', $line );
2070 private function wrapLine( $marker, $class, $line ) {
2071 if( $line !== '' ) {
2072 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2073 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2075 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2078 function emptyLine() {
2079 return '<td colspan="2"> </td>';
2082 function _added( $lines ) {
2083 foreach ($lines as $line) {
2084 echo '<tr>' . $this->emptyLine() .
2085 $this->addedLine( '<ins class="diffchange">' .
2086 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2090 function _deleted($lines) {
2091 foreach ($lines as $line) {
2092 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2093 htmlspecialchars ( $line ) . '</del>' ) .
2094 $this->emptyLine() . "</tr>\n";
2098 function _context( $lines ) {
2099 foreach ($lines as $line) {
2101 $this->contextLine( htmlspecialchars ( $line ) ) .
2102 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2106 function _changed( $orig, $closing ) {
2107 wfProfileIn( __METHOD__
);
2109 $diff = new WordLevelDiff( $orig, $closing );
2110 $del = $diff->orig();
2111 $add = $diff->closing();
2113 # Notice that WordLevelDiff returns HTML-escaped output.
2114 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2116 while ( $line = array_shift( $del ) ) {
2117 $aline = array_shift( $add );
2118 echo '<tr>' . $this->deletedLine( $line ) .
2119 $this->addedLine( $aline ) . "</tr>\n";
2121 foreach ($add as $line) { # If any leftovers
2122 echo '<tr>' . $this->emptyLine() .
2123 $this->addedLine( $line ) . "</tr>\n";
2125 wfProfileOut( __METHOD__
);