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?
35 * @param $titleObj Title object that the diff is associated with
36 * @param $old Integer: old ID we want to show and diff with.
37 * @param $new String: either 'prev' or 'next'.
38 * @param $rcid Integer: ??? FIXME (default 0)
39 * @param $refreshCache boolean If set, refreshes the diff cache
40 * @param $htmldiff boolean If set, output using HTMLDiff instead of raw wikicode diff
42 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false , $htmldiff = false) {
43 $this->mTitle
= $titleObj;
44 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
46 if ( 'prev' === $new ) {
47 # Show diff between revision $old and the previous one.
48 # Get previous one from DB.
49 $this->mNewid
= intval($old);
50 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
51 } elseif ( 'next' === $new ) {
52 # Show diff between revision $old and the previous one.
53 # Get previous one from DB.
55 $this->mOldid
= intval($old);
56 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
57 if ( false === $this->mNewid
) {
58 # if no result, NewId points to the newest old revision. The only newer
59 # revision is cur, which is "0".
63 $this->mOldid
= intval($old);
64 $this->mNewid
= intval($new);
65 wfRunHooks( 'NewDifferenceEngine', array(&$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new) );
67 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
68 $this->mRefreshCache
= $refreshCache;
69 $this->htmldiff
= $htmldiff;
76 function showDiffPage( $diffOnly = false ) {
77 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
78 wfProfileIn( __METHOD__
);
81 # If external diffs are enabled both globally and for the user,
82 # we'll use the application/x-external-editor interface to call
83 # an external diff tool like kompare, kdiff3, etc.
84 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
85 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
87 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
88 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
89 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
90 $special=$wgLang->getNsText(NS_SPECIAL
);
95 Script={$wgServer}{$wgScript}
96 Special namespace={$special}
110 $wgOut->setArticleFlag( false );
111 if ( !$this->loadRevisionData() ) {
112 $t = $this->mTitle
->getPrefixedText();
113 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
114 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
115 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
116 wfProfileOut( __METHOD__
);
120 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
122 if ( $this->mNewRev
->isCurrent() ) {
123 $wgOut->setArticleFlag( true );
126 # mOldid is false if the difference engine is called with a "vague" query for
127 # a diff between a version V and its previous version V' AND the version V
128 # is the first version of that article. In that case, V' does not exist.
129 if ( $this->mOldid
=== false ) {
130 $this->showFirstRevision();
131 $this->renderNewRevision(); // should we respect $diffOnly here or not?
132 wfProfileOut( __METHOD__
);
136 $wgOut->suppressQuickbar();
138 $oldTitle = $this->mOldPage
->getPrefixedText();
139 $newTitle = $this->mNewPage
->getPrefixedText();
140 if( $oldTitle == $newTitle ) {
141 $wgOut->setPageTitle( $newTitle );
143 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
145 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
146 $wgOut->setRobotPolicy( 'noindex,nofollow' );
148 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
149 $wgOut->loginToUse();
152 wfProfileOut( __METHOD__
);
156 $sk = $wgUser->getSkin();
158 // Check if page is editable
159 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
160 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
161 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
166 // Prepare a change patrol link, if applicable
167 if( $wgUseRCPatrol && $this->mTitle
->userCan('patrol') ) {
168 // If we've been given an explicit change identifier, use it; saves time
169 if( $this->mRcidMarkPatrolled
) {
170 $rcid = $this->mRcidMarkPatrolled
;
171 $rc = RecentChange
::newFromId( $rcid );
172 // Already patrolled?
173 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ?
$rcid : 0;
175 // Look for an unpatrolled change corresponding to this diff
176 $db = wfGetDB( DB_SLAVE
);
177 $change = RecentChange
::newFromConds(
179 // Add redundant user,timestamp condition so we can use the existing index
180 'rc_user_text' => $this->mNewRev
->getRawUserText(),
181 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
182 'rc_this_oldid' => $this->mNewid
,
183 'rc_last_oldid' => $this->mOldid
,
188 if( $change instanceof RecentChange
) {
189 $rcid = $change->mAttribs
['rc_id'];
197 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
199 wfMsgHtml( 'markaspatrolleddiff' ),
200 "action=markpatrolled&rcid={$rcid}"
209 $htmldiffarg = $this->htmlDiffArgument();
210 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
211 'diff=prev&oldid='.$this->mOldid
.$htmldiffarg, '', '', 'id="differences-prevlink"' );
212 if ( $this->mNewRev
->isCurrent() ) {
213 $nextlink = ' ';
215 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
216 'diff=next&oldid='.$this->mNewid
.$htmldiffarg, '', '', 'id="differences-nextlink"' );
222 if( $this->mOldRev
->isMinor() ) {
223 $oldminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
225 if( $this->mNewRev
->isMinor() ) {
226 $newminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
229 $rdel = ''; $ldel = '';
230 if( $wgUser->isAllowed( 'deleterevision' ) ) {
231 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
232 // If revision was hidden from sysops
233 $ldel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
235 $query = array( 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
236 'oldid' => $this->mOldRev
->getId()
238 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
240 $ldel = " $ldel ";
241 // We don't currently handle well changing the top revision's settings
242 if( $this->mNewRev
->isCurrent() ) {
243 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
244 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
245 // If revision was hidden from sysops
246 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
248 $query = array( 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
249 'oldid' => $this->mNewRev
->getId()
251 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
253 $rdel = " $rdel ";
256 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
257 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
258 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
259 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
260 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
261 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
262 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
263 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
266 if( !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ||
!$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
267 $this->showDiffStyle();
268 $multi = $this->getMultiNotice();
269 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
270 $wgOut->addWikiMsg( 'rev-deleted-no-diff' );
271 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
272 $multi = $this->getMultiNotice();
273 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
274 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
275 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
276 $this->renderHtmlDiff();
278 if( $wgEnableHtmlDiff ) {
279 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
280 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
282 $this->showDiff( $oldHeader, $newHeader );
284 $this->renderNewRevision();
287 wfProfileOut( __METHOD__
);
291 * Show the new revision of the page.
293 function renderNewRevision() {
295 wfProfileIn( __METHOD__
);
297 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
298 # Add deleted rev tag if needed
299 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
300 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
301 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
302 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
305 if( !$this->mNewRev
->isCurrent() ) {
306 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
309 $this->loadNewText();
310 if( is_object( $this->mNewRev
) ) {
311 $wgOut->setRevisionId( $this->mNewRev
->getId() );
314 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
315 // Stolen from Article::view --AG 2007-10-11
316 // Give hooks a chance to customise the output
317 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
318 // Wrap the whole lot in a <pre> and don't parse
320 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
321 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
322 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
323 $wgOut->addHTML( "\n</pre>\n" );
326 $wgOut->addWikiTextTidy( $this->mNewtext
);
329 if( !$this->mNewRev
->isCurrent() ) {
330 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
333 wfProfileOut( __METHOD__
);
337 function renderHtmlDiff() {
338 global $wgOut, $wgTitle, $wgParser, $wgDebugComments;
339 wfProfileIn( __METHOD__
);
341 $this->showDiffStyle();
343 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
344 #add deleted rev tag if needed
345 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
346 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
347 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
348 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
351 if( !$this->mNewRev
->isCurrent() ) {
352 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
358 if( is_object( $this->mOldRev
) ) {
359 $wgOut->setRevisionId( $this->mOldRev
->getId() );
362 $popts = $wgOut->parserOptions();
363 $oldTidy = $popts->setTidy( true );
364 $popts->setEditSection( false );
366 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
367 $popts->setTidy( $oldTidy );
370 //$wgOut->addParserOutputNoText( $parserOutput );
371 $oldHtml = $parserOutput->getText();
372 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
375 if( is_object( $this->mNewRev
) ) {
376 $wgOut->setRevisionId( $this->mNewRev
->getId() );
379 $popts = $wgOut->parserOptions();
380 $oldTidy = $popts->setTidy( true );
382 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
383 $popts->setTidy( $oldTidy );
385 $wgOut->addParserOutputNoText( $parserOutput );
386 $newHtml = $parserOutput->getText();
387 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
389 unset($parserOutput, $popts);
391 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
392 $differ->htmlDiff($oldHtml, $newHtml);
393 if ( $wgDebugComments ) {
394 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
397 wfProfileOut( __METHOD__
);
401 * Show the first revision of an article. Uses normal diff headers in
402 * contrast to normal "old revision" display style.
404 function showFirstRevision() {
405 global $wgOut, $wgUser;
406 wfProfileIn( __METHOD__
);
408 # Get article text from the DB
410 if ( ! $this->loadNewText() ) {
411 $t = $this->mTitle
->getPrefixedText();
412 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
413 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
414 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
415 wfProfileOut( __METHOD__
);
418 if ( $this->mNewRev
->isCurrent() ) {
419 $wgOut->setArticleFlag( true );
422 # Check if user is allowed to look at this page. If not, bail out.
424 if ( !$this->mTitle
->userCanRead() ) {
425 $wgOut->loginToUse();
427 wfProfileOut( __METHOD__
);
428 throw new MWException("Permission Error: you do not have access to view this page");
431 # Prepare the header box
433 $sk = $wgUser->getSkin();
435 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
439 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
440 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
442 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
443 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
445 $wgOut->addHTML( $header );
447 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
448 $wgOut->setRobotPolicy( 'noindex,nofollow' );
450 wfProfileOut( __METHOD__
);
453 function htmlDiffArgument(){
454 global $wgEnableHtmlDiff;
455 if($wgEnableHtmlDiff){
457 return '&htmldiff=1';
459 return '&htmldiff=0';
467 * Get the diff text, send it to $wgOut
468 * Returns false if the diff could not be generated, otherwise returns true
470 function showDiff( $otitle, $ntitle ) {
472 $diff = $this->getDiff( $otitle, $ntitle );
473 if ( $diff === false ) {
474 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
477 $this->showDiffStyle();
478 $wgOut->addHTML( $diff );
484 * Add style sheets and supporting JS for diff display.
486 function showDiffStyle() {
487 global $wgStylePath, $wgStyleVersion, $wgOut;
488 $wgOut->addStyle( 'common/diff.css' );
490 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
491 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
495 * Get complete diff table, including header
497 * @param Title $otitle Old title
498 * @param Title $ntitle New title
501 function getDiff( $otitle, $ntitle ) {
502 $body = $this->getDiffBody();
503 if ( $body === false ) {
506 $multi = $this->getMultiNotice();
507 return $this->addHeader( $body, $otitle, $ntitle, $multi );
512 * Get the diff table body, without header
516 function getDiffBody() {
518 wfProfileIn( __METHOD__
);
519 // Check if the diff should be hidden from this user
520 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
522 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
527 if ( $this->mOldid
&& $this->mNewid
) {
528 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
530 if ( !$this->mRefreshCache
) {
531 $difftext = $wgMemc->get( $key );
533 wfIncrStats( 'diff_cache_hit' );
534 $difftext = $this->localiseLineNumbers( $difftext );
535 $difftext .= "\n<!-- diff cache key $key -->\n";
536 wfProfileOut( __METHOD__
);
539 } // don't try to load but save the result
542 // Loadtext is permission safe, this just clears out the diff
543 if ( !$this->loadText() ) {
544 wfProfileOut( __METHOD__
);
548 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
550 // Save to cache for 7 days
551 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
552 wfIncrStats( 'diff_uncacheable' );
553 } else if ( $key !== false && $difftext !== false ) {
554 wfIncrStats( 'diff_cache_miss' );
555 $wgMemc->set( $key, $difftext, 7*86400 );
557 wfIncrStats( 'diff_uncacheable' );
559 // Replace line numbers with the text in the user's language
560 if ( $difftext !== false ) {
561 $difftext = $this->localiseLineNumbers( $difftext );
563 wfProfileOut( __METHOD__
);
568 * Generate a diff, no caching
569 * $otext and $ntext must be already segmented
571 function generateDiffBody( $otext, $ntext ) {
572 global $wgExternalDiffEngine, $wgContLang;
574 $otext = str_replace( "\r\n", "\n", $otext );
575 $ntext = str_replace( "\r\n", "\n", $ntext );
577 if ( $wgExternalDiffEngine == 'wikidiff' ) {
578 # For historical reasons, external diff engine expects
579 # input text to be HTML-escaped already
580 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
581 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
582 if( !function_exists( 'wikidiff_do_diff' ) ) {
583 dl('php_wikidiff.so');
585 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
586 $this->debug( 'wikidiff1' );
589 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
590 # Better external diff engine, the 2 may some day be dropped
591 # This one does the escaping and segmenting itself
592 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
593 wfProfileIn( __METHOD__
. "-dl" );
594 @dl
('php_wikidiff2.so');
595 wfProfileOut( __METHOD__
. "-dl" );
597 if ( function_exists( 'wikidiff2_do_diff' ) ) {
598 wfProfileIn( 'wikidiff2_do_diff' );
599 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
600 $text .= $this->debug( 'wikidiff2' );
601 wfProfileOut( 'wikidiff2_do_diff' );
605 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
607 global $wgTmpDirectory;
608 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
609 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
611 $tempFile1 = fopen( $tempName1, "w" );
613 wfProfileOut( __METHOD__
);
616 $tempFile2 = fopen( $tempName2, "w" );
618 wfProfileOut( __METHOD__
);
621 fwrite( $tempFile1, $otext );
622 fwrite( $tempFile2, $ntext );
623 fclose( $tempFile1 );
624 fclose( $tempFile2 );
625 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
626 wfProfileIn( __METHOD__
. "-shellexec" );
627 $difftext = wfShellExec( $cmd );
628 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
629 wfProfileOut( __METHOD__
. "-shellexec" );
630 unlink( $tempName1 );
631 unlink( $tempName2 );
636 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
637 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
638 $diffs = new Diff( $ota, $nta );
639 $formatter = new TableDiffFormatter();
640 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
645 * Generate a debug comment indicating diff generating time,
646 * server node, and generator backend.
648 protected function debug( $generator="internal" ) {
649 global $wgShowHostnames;
650 $data = array( $generator );
651 if( $wgShowHostnames ) {
652 $data[] = wfHostname();
654 $data[] = wfTimestamp( TS_DB
);
655 return "<!-- diff generator: " .
664 * Replace line numbers with the text in the user's language
666 function localiseLineNumbers( $text ) {
667 return preg_replace_callback( '/<!--LINE (\d+)-->/',
668 array( &$this, 'localiseLineNumbersCb' ), $text );
671 function localiseLineNumbersCb( $matches ) {
673 return wfMsgExt( 'lineno', array( 'parseinline' ), $wgLang->formatNum( $matches[1] ) );
678 * If there are revisions between the ones being compared, return a note saying so.
680 function getMultiNotice() {
681 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
684 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
685 // Comparing two different pages? Count would be meaningless.
689 $oldid = $this->mOldRev
->getId();
690 $newid = $this->mNewRev
->getId();
691 if ( $oldid > $newid ) {
692 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
695 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
699 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
704 * Add the header to a diff body
706 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
709 <col class='diff-marker' />
710 <col class='diff-content' />
711 <col class='diff-marker' />
712 <col class='diff-content' />
714 <td colspan='2' class='diff-otitle'>{$otitle}</td>
715 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
720 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
722 return $header . $diff . "</table>";
726 * Use specified text instead of loading from the database
728 function setText( $oldText, $newText ) {
729 $this->mOldtext
= $oldText;
730 $this->mNewtext
= $newText;
731 $this->mTextLoaded
= 2;
735 * Load revision metadata for the specified articles. If newid is 0, then compare
736 * the old article in oldid to the current article; if oldid is 0, then
737 * compare the current article to the immediately previous one (ignoring the
740 * If oldid is false, leave the corresponding revision object set
741 * to false. This is impossible via ordinary user input, and is provided for
744 function loadRevisionData() {
745 global $wgLang, $wgUser;
746 if ( $this->mRevisionsLoaded
) {
749 // Whether it succeeds or fails, we don't want to try again
750 $this->mRevisionsLoaded
= true;
753 // Load the new revision object
754 $this->mNewRev
= $this->mNewid
755 ? Revision
::newFromId( $this->mNewid
)
756 : Revision
::newFromTitle( $this->mTitle
);
757 if( !$this->mNewRev
instanceof Revision
)
760 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
761 $this->mNewid
= $this->mNewRev
->getId();
763 // Check if page is editable
764 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
766 // Set assorted variables
767 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
768 $this->mNewPage
= $this->mNewRev
->getTitle();
769 if( $this->mNewRev
->isCurrent() ) {
770 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
771 $this->mPagetitle
= wfMsgHTML( 'currentrev-asof', $timestamp );
772 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
774 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
775 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
778 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
779 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
780 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
782 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
783 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
785 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
786 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
787 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
788 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
791 // Load the old revision object
792 $this->mOldRev
= false;
793 if( $this->mOldid
) {
794 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
795 } elseif ( $this->mOldid
=== 0 ) {
796 $rev = $this->mNewRev
->getPrevious();
798 $this->mOldid
= $rev->getId();
799 $this->mOldRev
= $rev;
801 // No previous revision; mark to show as first-version only.
802 $this->mOldid
= false;
803 $this->mOldRev
= false;
805 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
807 if( is_null( $this->mOldRev
) ) {
811 if ( $this->mOldRev
) {
812 $this->mOldPage
= $this->mOldRev
->getTitle();
814 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
815 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
816 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
817 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
819 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
820 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
821 // Add an "undo" link
822 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
823 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
824 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
825 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
826 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
829 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
830 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
831 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
832 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
840 * Load the text of the revisions, as well as revision data.
842 function loadText() {
843 if ( $this->mTextLoaded
== 2 ) {
846 // Whether it succeeds or fails, we don't want to try again
847 $this->mTextLoaded
= 2;
850 if ( !$this->loadRevisionData() ) {
853 if ( $this->mOldRev
) {
854 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
855 if ( $this->mOldtext
=== false ) {
859 if ( $this->mNewRev
) {
860 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
861 if ( $this->mNewtext
=== false ) {
869 * Load the text of the new revision, not the old one
871 function loadNewText() {
872 if ( $this->mTextLoaded
>= 1 ) {
875 $this->mTextLoaded
= 1;
877 if ( !$this->loadRevisionData() ) {
880 $this->mNewtext
= $this->mNewRev
->getText();
887 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
889 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
890 // You may copy this code freely under the conditions of the GPL.
893 define('USE_ASSERTS', function_exists('assert'));
898 * @ingroup DifferenceEngine
906 trigger_error('pure virtual', E_USER_ERROR
);
910 return $this->orig ?
sizeof($this->orig
) : 0;
913 function nclosing() {
914 return $this->closing ?
sizeof($this->closing
) : 0;
921 * @ingroup DifferenceEngine
923 class _DiffOp_Copy
extends _DiffOp
{
926 function _DiffOp_Copy ($orig, $closing = false) {
927 if (!is_array($closing))
930 $this->closing
= $closing;
934 return new _DiffOp_Copy($this->closing
, $this->orig
);
941 * @ingroup DifferenceEngine
943 class _DiffOp_Delete
extends _DiffOp
{
944 var $type = 'delete';
946 function _DiffOp_Delete ($lines) {
947 $this->orig
= $lines;
948 $this->closing
= false;
952 return new _DiffOp_Add($this->orig
);
959 * @ingroup DifferenceEngine
961 class _DiffOp_Add
extends _DiffOp
{
964 function _DiffOp_Add ($lines) {
965 $this->closing
= $lines;
970 return new _DiffOp_Delete($this->closing
);
977 * @ingroup DifferenceEngine
979 class _DiffOp_Change
extends _DiffOp
{
980 var $type = 'change';
982 function _DiffOp_Change ($orig, $closing) {
984 $this->closing
= $closing;
988 return new _DiffOp_Change($this->closing
, $this->orig
);
993 * Class used internally by Diff to actually compute the diffs.
995 * The algorithm used here is mostly lifted from the perl module
996 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
997 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
999 * More ideas are taken from:
1000 * http://www.ics.uci.edu/~eppstein/161/960229.html
1002 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1003 * diffutils-2.7, which can be found at:
1004 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1006 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1009 * Line length limits for robustness added by Tim Starling, 2005-08-31
1010 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1012 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1014 * @ingroup DifferenceEngine
1018 const MAX_XREF_LENGTH
= 10000;
1020 function diff ($from_lines, $to_lines){
1021 wfProfileIn( __METHOD__
);
1023 // Diff and store locally
1024 $this->diff_local($from_lines, $to_lines);
1026 // Merge edits when possible
1027 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1028 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1030 // Compute the edit operations.
1031 $n_from = sizeof($from_lines);
1032 $n_to = sizeof($to_lines);
1036 while ($xi < $n_from ||
$yi < $n_to) {
1037 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1038 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1040 // Skip matching "snake".
1042 while ( $xi < $n_from && $yi < $n_to
1043 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1044 $copy[] = $from_lines[$xi++
];
1048 $edits[] = new _DiffOp_Copy($copy);
1050 // Find deletes & adds.
1052 while ($xi < $n_from && $this->xchanged
[$xi])
1053 $delete[] = $from_lines[$xi++
];
1056 while ($yi < $n_to && $this->ychanged
[$yi])
1057 $add[] = $to_lines[$yi++
];
1059 if ($delete && $add)
1060 $edits[] = new _DiffOp_Change($delete, $add);
1062 $edits[] = new _DiffOp_Delete($delete);
1064 $edits[] = new _DiffOp_Add($add);
1066 wfProfileOut( __METHOD__
);
1070 function diff_local ($from_lines, $to_lines) {
1071 global $wgExternalDiffEngine;
1072 wfProfileIn( __METHOD__
);
1074 if($wgExternalDiffEngine == 'wikidiff3'){
1076 $wikidiff3 = new WikiDiff3();
1077 $wikidiff3->diff($from_lines, $to_lines);
1078 $this->xchanged
= $wikidiff3->removed
;
1079 $this->ychanged
= $wikidiff3->added
;
1083 $n_from = sizeof($from_lines);
1084 $n_to = sizeof($to_lines);
1085 $this->xchanged
= $this->ychanged
= array();
1086 $this->xv
= $this->yv
= array();
1087 $this->xind
= $this->yind
= array();
1089 unset($this->in_seq
);
1092 // Skip leading common lines.
1093 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1094 if ($from_lines[$skip] !== $to_lines[$skip])
1096 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1098 // Skip trailing common lines.
1099 $xi = $n_from; $yi = $n_to;
1100 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1101 if ($from_lines[$xi] !== $to_lines[$yi])
1103 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1106 // Ignore lines which do not exist in both files.
1107 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1108 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1111 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1112 $line = $to_lines[$yi];
1113 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1115 $yhash[$this->_line_hash($line)] = 1;
1116 $this->yv
[] = $line;
1117 $this->yind
[] = $yi;
1119 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1120 $line = $from_lines[$xi];
1121 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1123 $this->xv
[] = $line;
1124 $this->xind
[] = $xi;
1128 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1130 wfProfileOut( __METHOD__
);
1134 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1136 function _line_hash( $line ) {
1137 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1138 return md5( $line );
1144 /* Divide the Largest Common Subsequence (LCS) of the sequences
1145 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1148 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1149 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1150 * sub sequences. The first sub-sequence is contained in [X0, X1),
1151 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1152 * that (X0, Y0) == (XOFF, YOFF) and
1153 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1155 * This function assumes that the first lines of the specified portions
1156 * of the two files do not match, and likewise that the last lines do not
1157 * match. The caller must trim matching lines from the beginning and end
1158 * of the portions it is going to specify.
1160 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1163 if ($xlim - $xoff > $ylim - $yoff) {
1164 // Things seems faster (I'm not sure I understand why)
1165 // when the shortest sequence in X.
1167 list ($xoff, $xlim, $yoff, $ylim)
1168 = array( $yoff, $ylim, $xoff, $xlim);
1172 for ($i = $ylim - 1; $i >= $yoff; $i--)
1173 $ymatches[$this->xv
[$i]][] = $i;
1175 for ($i = $ylim - 1; $i >= $yoff; $i--)
1176 $ymatches[$this->yv
[$i]][] = $i;
1179 $this->seq
[0]= $yoff - 1;
1180 $this->in_seq
= array();
1181 $ymids[0] = array();
1183 $numer = $xlim - $xoff +
$nchunks - 1;
1185 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1187 for ($i = 0; $i <= $this->lcs
; $i++
)
1188 $ymids[$i][$chunk-1] = $this->seq
[$i];
1190 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1191 for ( ; $x < $x1; $x++
) {
1192 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1193 if (empty($ymatches[$line]))
1195 $matches = $ymatches[$line];
1197 while (list ($junk, $y) = each($matches))
1198 if (empty($this->in_seq
[$y])) {
1199 $k = $this->_lcs_pos($y);
1200 USE_ASSERTS
&& assert($k > 0);
1201 $ymids[$k] = $ymids[$k-1];
1204 while (list ( /* $junk */, $y) = each($matches)) {
1205 if ($y > $this->seq
[$k-1]) {
1206 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1207 // Optimization: this is a common case:
1208 // next match is just replacing previous match.
1209 $this->in_seq
[$this->seq
[$k]] = false;
1210 $this->seq
[$k] = $y;
1211 $this->in_seq
[$y] = 1;
1212 } else if (empty($this->in_seq
[$y])) {
1213 $k = $this->_lcs_pos($y);
1214 USE_ASSERTS
&& assert($k > 0);
1215 $ymids[$k] = $ymids[$k-1];
1221 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1222 $ymid = $ymids[$this->lcs
];
1223 for ($n = 0; $n < $nchunks - 1; $n++
) {
1224 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1225 $y1 = $ymid[$n] +
1;
1226 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1228 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1230 return array($this->lcs
, $seps);
1233 function _lcs_pos ($ypos) {
1235 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1236 $this->seq
[++
$this->lcs
] = $ypos;
1237 $this->in_seq
[$ypos] = 1;
1242 while ($beg < $end) {
1243 $mid = (int)(($beg +
$end) / 2);
1244 if ( $ypos > $this->seq
[$mid] )
1250 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1252 $this->in_seq
[$this->seq
[$end]] = false;
1253 $this->seq
[$end] = $ypos;
1254 $this->in_seq
[$ypos] = 1;
1258 /* Find LCS of two sequences.
1260 * The results are recorded in the vectors $this->{x,y}changed[], by
1261 * storing a 1 in the element for each line that is an insertion
1262 * or deletion (ie. is not in the LCS).
1264 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1266 * Note that XLIM, YLIM are exclusive bounds.
1267 * All line numbers are origin-0 and discarded lines are not counted.
1269 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1270 // Slide down the bottom initial diagonal.
1271 while ($xoff < $xlim && $yoff < $ylim
1272 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1277 // Slide up the top initial diagonal.
1278 while ($xlim > $xoff && $ylim > $yoff
1279 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1284 if ($xoff == $xlim ||
$yoff == $ylim)
1287 // This is ad hoc but seems to work well.
1288 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1289 //$nchunks = max(2,min(8,(int)$nchunks));
1290 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1292 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1296 // X and Y sequences have no common subsequence:
1297 // mark all changed.
1298 while ($yoff < $ylim)
1299 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1300 while ($xoff < $xlim)
1301 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1303 // Use the partitions to split this problem into subproblems.
1306 while ($pt2 = next($seps)) {
1307 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1313 /* Adjust inserts/deletes of identical lines to join changes
1314 * as much as possible.
1316 * We do something when a run of changed lines include a
1317 * line at one end and has an excluded, identical line at the other.
1318 * We are free to choose which identical line is included.
1319 * `compareseq' usually chooses the one at the beginning,
1320 * but usually it is cleaner to consider the following identical line
1321 * to be the "change".
1323 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1325 function _shift_boundaries ($lines, &$changed, $other_changed) {
1326 wfProfileIn( __METHOD__
);
1330 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1331 $len = sizeof($lines);
1332 $other_len = sizeof($other_changed);
1336 * Scan forwards to find beginning of another run of changes.
1337 * Also keep track of the corresponding point in the other file.
1339 * Throughout this code, $i and $j are adjusted together so that
1340 * the first $i elements of $changed and the first $j elements
1341 * of $other_changed both contain the same number of zeros
1342 * (unchanged lines).
1343 * Furthermore, $j is always kept so that $j == $other_len or
1344 * $other_changed[$j] == false.
1346 while ($j < $other_len && $other_changed[$j])
1349 while ($i < $len && ! $changed[$i]) {
1350 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1352 while ($j < $other_len && $other_changed[$j])
1361 // Find the end of this run of changes.
1362 while (++
$i < $len && $changed[$i])
1367 * Record the length of this run of changes, so that
1368 * we can later determine whether the run has grown.
1370 $runlength = $i - $start;
1373 * Move the changed region back, so long as the
1374 * previous unchanged line matches the last changed one.
1375 * This merges with previous changed regions.
1377 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1378 $changed[--$start] = 1;
1379 $changed[--$i] = false;
1380 while ($start > 0 && $changed[$start - 1])
1382 USE_ASSERTS
&& assert('$j > 0');
1383 while ($other_changed[--$j])
1385 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1389 * Set CORRESPONDING to the end of the changed run, at the last
1390 * point where it corresponds to a changed run in the other file.
1391 * CORRESPONDING == LEN means no such point has been found.
1393 $corresponding = $j < $other_len ?
$i : $len;
1396 * Move the changed region forward, so long as the
1397 * first changed line matches the following unchanged one.
1398 * This merges with following changed regions.
1399 * Do this second, so that if there are no merges,
1400 * the changed region is moved forward as far as possible.
1402 while ($i < $len && $lines[$start] == $lines[$i]) {
1403 $changed[$start++
] = false;
1405 while ($i < $len && $changed[$i])
1408 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1410 if ($j < $other_len && $other_changed[$j]) {
1411 $corresponding = $i;
1412 while ($j < $other_len && $other_changed[$j])
1416 } while ($runlength != $i - $start);
1419 * If possible, move the fully-merged run of changes
1420 * back to a corresponding run in the other file.
1422 while ($corresponding < $i) {
1423 $changed[--$start] = 1;
1425 USE_ASSERTS
&& assert('$j > 0');
1426 while ($other_changed[--$j])
1428 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1431 wfProfileOut( __METHOD__
);
1436 * Class representing a 'diff' between two sequences of strings.
1439 * @ingroup DifferenceEngine
1447 * Computes diff between sequences of strings.
1449 * @param $from_lines array An array of strings.
1450 * (Typically these are lines from a file.)
1451 * @param $to_lines array An array of strings.
1453 function Diff($from_lines, $to_lines) {
1454 $eng = new _DiffEngine
;
1455 $this->edits
= $eng->diff($from_lines, $to_lines);
1456 //$this->_check($from_lines, $to_lines);
1460 * Compute reversed Diff.
1464 * $diff = new Diff($lines1, $lines2);
1465 * $rev = $diff->reverse();
1466 * @return object A Diff object representing the inverse of the
1469 function reverse () {
1471 $rev->edits
= array();
1472 foreach ($this->edits
as $edit) {
1473 $rev->edits
[] = $edit->reverse();
1479 * Check for empty diff.
1481 * @return bool True iff two sequences were identical.
1483 function isEmpty () {
1484 foreach ($this->edits
as $edit) {
1485 if ($edit->type
!= 'copy')
1492 * Compute the length of the Longest Common Subsequence (LCS).
1494 * This is mostly for diagnostic purposed.
1496 * @return int The length of the LCS.
1500 foreach ($this->edits
as $edit) {
1501 if ($edit->type
== 'copy')
1502 $lcs +
= sizeof($edit->orig
);
1508 * Get the original set of lines.
1510 * This reconstructs the $from_lines parameter passed to the
1513 * @return array The original sequence of strings.
1518 foreach ($this->edits
as $edit) {
1520 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1526 * Get the closing set of lines.
1528 * This reconstructs the $to_lines parameter passed to the
1531 * @return array The sequence of strings.
1533 function closing() {
1536 foreach ($this->edits
as $edit) {
1538 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1544 * Check a Diff for validity.
1546 * This is here only for debugging purposes.
1548 function _check ($from_lines, $to_lines) {
1549 wfProfileIn( __METHOD__
);
1550 if (serialize($from_lines) != serialize($this->orig()))
1551 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1552 if (serialize($to_lines) != serialize($this->closing()))
1553 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1555 $rev = $this->reverse();
1556 if (serialize($to_lines) != serialize($rev->orig()))
1557 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1558 if (serialize($from_lines) != serialize($rev->closing()))
1559 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1563 foreach ($this->edits
as $edit) {
1564 if ( $prevtype == $edit->type
)
1565 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1566 $prevtype = $edit->type
;
1569 $lcs = $this->lcs();
1570 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1571 wfProfileOut( __METHOD__
);
1576 * @todo document, bad name.
1578 * @ingroup DifferenceEngine
1580 class MappedDiff
extends Diff
1585 * Computes diff between sequences of strings.
1587 * This can be used to compute things like
1588 * case-insensitve diffs, or diffs which ignore
1589 * changes in white-space.
1591 * @param $from_lines array An array of strings.
1592 * (Typically these are lines from a file.)
1594 * @param $to_lines array An array of strings.
1596 * @param $mapped_from_lines array This array should
1597 * have the same size number of elements as $from_lines.
1598 * The elements in $mapped_from_lines and
1599 * $mapped_to_lines are what is actually compared
1600 * when computing the diff.
1602 * @param $mapped_to_lines array This array should
1603 * have the same number of elements as $to_lines.
1605 function MappedDiff($from_lines, $to_lines,
1606 $mapped_from_lines, $mapped_to_lines) {
1607 wfProfileIn( __METHOD__
);
1609 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1610 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1612 $this->Diff($mapped_from_lines, $mapped_to_lines);
1615 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1616 $orig = &$this->edits
[$i]->orig
;
1617 if (is_array($orig)) {
1618 $orig = array_slice($from_lines, $xi, sizeof($orig));
1619 $xi +
= sizeof($orig);
1622 $closing = &$this->edits
[$i]->closing
;
1623 if (is_array($closing)) {
1624 $closing = array_slice($to_lines, $yi, sizeof($closing));
1625 $yi +
= sizeof($closing);
1628 wfProfileOut( __METHOD__
);
1633 * A class to format Diffs
1635 * This class formats the diff in classic diff format.
1636 * It is intended that this class be customized via inheritance,
1637 * to obtain fancier outputs.
1640 * @ingroup DifferenceEngine
1642 class DiffFormatter
{
1644 * Number of leading context "lines" to preserve.
1646 * This should be left at zero for this class, but subclasses
1647 * may want to set this to other values.
1649 var $leading_context_lines = 0;
1652 * Number of trailing context "lines" to preserve.
1654 * This should be left at zero for this class, but subclasses
1655 * may want to set this to other values.
1657 var $trailing_context_lines = 0;
1662 * @param $diff object A Diff object.
1663 * @return string The formatted output.
1665 function format($diff) {
1666 wfProfileIn( __METHOD__
);
1672 $nlead = $this->leading_context_lines
;
1673 $ntrail = $this->trailing_context_lines
;
1675 $this->_start_diff();
1677 foreach ($diff->edits
as $edit) {
1678 if ($edit->type
== 'copy') {
1679 if (is_array($block)) {
1680 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1685 $context = array_slice($edit->orig
, 0, $ntrail);
1686 $block[] = new _DiffOp_Copy($context);
1688 $this->_block($x0, $ntrail +
$xi - $x0,
1689 $y0, $ntrail +
$yi - $y0,
1694 $context = $edit->orig
;
1697 if (! is_array($block)) {
1698 $context = array_slice($context, sizeof($context) - $nlead);
1699 $x0 = $xi - sizeof($context);
1700 $y0 = $yi - sizeof($context);
1703 $block[] = new _DiffOp_Copy($context);
1709 $xi +
= sizeof($edit->orig
);
1711 $yi +
= sizeof($edit->closing
);
1714 if (is_array($block))
1715 $this->_block($x0, $xi - $x0,
1719 $end = $this->_end_diff();
1720 wfProfileOut( __METHOD__
);
1724 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1725 wfProfileIn( __METHOD__
);
1726 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1727 foreach ($edits as $edit) {
1728 if ($edit->type
== 'copy')
1729 $this->_context($edit->orig
);
1730 elseif ($edit->type
== 'add')
1731 $this->_added($edit->closing
);
1732 elseif ($edit->type
== 'delete')
1733 $this->_deleted($edit->orig
);
1734 elseif ($edit->type
== 'change')
1735 $this->_changed($edit->orig
, $edit->closing
);
1737 trigger_error('Unknown edit type', E_USER_ERROR
);
1739 $this->_end_block();
1740 wfProfileOut( __METHOD__
);
1743 function _start_diff() {
1747 function _end_diff() {
1748 $val = ob_get_contents();
1753 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1755 $xbeg .= "," . ($xbeg +
$xlen - 1);
1757 $ybeg .= "," . ($ybeg +
$ylen - 1);
1759 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1762 function _start_block($header) {
1763 echo $header . "\n";
1766 function _end_block() {
1769 function _lines($lines, $prefix = ' ') {
1770 foreach ($lines as $line)
1771 echo "$prefix $line\n";
1774 function _context($lines) {
1775 $this->_lines($lines);
1778 function _added($lines) {
1779 $this->_lines($lines, '>');
1781 function _deleted($lines) {
1782 $this->_lines($lines, '<');
1785 function _changed($orig, $closing) {
1786 $this->_deleted($orig);
1788 $this->_added($closing);
1793 * A formatter that outputs unified diffs
1794 * @ingroup DifferenceEngine
1797 class UnifiedDiffFormatter
extends DiffFormatter
{
1798 var $leading_context_lines = 2;
1799 var $trailing_context_lines = 2;
1801 function _added($lines) {
1802 $this->_lines($lines, '+');
1804 function _deleted($lines) {
1805 $this->_lines($lines, '-');
1807 function _changed($orig, $closing) {
1808 $this->_deleted($orig);
1809 $this->_added($closing);
1811 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1812 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1817 * A pseudo-formatter that just passes along the Diff::$edits array
1818 * @ingroup DifferenceEngine
1820 class ArrayDiffFormatter
extends DiffFormatter
{
1821 function format($diff) {
1825 foreach($diff->edits
as $edit)
1826 switch($edit->type
) {
1828 foreach($edit->closing
as $l) {
1832 'newline' => $newline++
1837 foreach($edit->orig
as $l) {
1839 'action' => 'delete',
1841 'oldline' => $oldline++
,
1846 foreach($edit->orig
as $i => $l) {
1848 'action' => 'change',
1850 'new' => @$edit->closing
[$i],
1851 'oldline' => $oldline++
,
1852 'newline' => $newline++
,
1857 $oldline +
= count($edit->orig
);
1858 $newline +
= count($edit->orig
);
1865 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1869 define('NBSP', ' '); // iso-8859-x non-breaking space.
1874 * @ingroup DifferenceEngine
1876 class _HWLDF_WordAccumulator
{
1877 function _HWLDF_WordAccumulator () {
1878 $this->_lines
= array();
1884 function _flushGroup ($new_tag) {
1885 if ($this->_group
!== '') {
1886 if ($this->_tag
== 'ins')
1887 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1888 htmlspecialchars ( $this->_group
) . '</ins>';
1889 elseif ($this->_tag
== 'del')
1890 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1891 htmlspecialchars ( $this->_group
) . '</del>';
1893 $this->_line
.= htmlspecialchars ( $this->_group
);
1896 $this->_tag
= $new_tag;
1899 function _flushLine ($new_tag) {
1900 $this->_flushGroup($new_tag);
1901 if ($this->_line
!= '')
1902 array_push ( $this->_lines
, $this->_line
);
1904 # make empty lines visible by inserting an NBSP
1905 array_push ( $this->_lines
, NBSP
);
1909 function addWords ($words, $tag = '') {
1910 if ($tag != $this->_tag
)
1911 $this->_flushGroup($tag);
1913 foreach ($words as $word) {
1914 // new-line should only come as first char of word.
1917 if ($word[0] == "\n") {
1918 $this->_flushLine($tag);
1919 $word = substr($word, 1);
1921 assert(!strstr($word, "\n"));
1922 $this->_group
.= $word;
1926 function getLines() {
1927 $this->_flushLine('~done');
1928 return $this->_lines
;
1935 * @ingroup DifferenceEngine
1937 class WordLevelDiff
extends MappedDiff
{
1938 const MAX_LINE_LENGTH
= 10000;
1940 function WordLevelDiff ($orig_lines, $closing_lines) {
1941 wfProfileIn( __METHOD__
);
1943 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1944 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1946 $this->MappedDiff($orig_words, $closing_words,
1947 $orig_stripped, $closing_stripped);
1948 wfProfileOut( __METHOD__
);
1951 function _split($lines) {
1952 wfProfileIn( __METHOD__
);
1955 $stripped = array();
1957 foreach ( $lines as $line ) {
1958 # If the line is too long, just pretend the entire line is one big word
1959 # This prevents resource exhaustion problems
1966 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1968 $stripped[] = $line;
1971 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1974 $words = array_merge( $words, $m[0] );
1975 $stripped = array_merge( $stripped, $m[1] );
1979 wfProfileOut( __METHOD__
);
1980 return array($words, $stripped);
1984 wfProfileIn( __METHOD__
);
1985 $orig = new _HWLDF_WordAccumulator
;
1987 foreach ($this->edits
as $edit) {
1988 if ($edit->type
== 'copy')
1989 $orig->addWords($edit->orig
);
1990 elseif ($edit->orig
)
1991 $orig->addWords($edit->orig
, 'del');
1993 $lines = $orig->getLines();
1994 wfProfileOut( __METHOD__
);
1998 function closing () {
1999 wfProfileIn( __METHOD__
);
2000 $closing = new _HWLDF_WordAccumulator
;
2002 foreach ($this->edits
as $edit) {
2003 if ($edit->type
== 'copy')
2004 $closing->addWords($edit->closing
);
2005 elseif ($edit->closing
)
2006 $closing->addWords($edit->closing
, 'ins');
2008 $lines = $closing->getLines();
2009 wfProfileOut( __METHOD__
);
2015 * Wikipedia Table style diff formatter.
2018 * @ingroup DifferenceEngine
2020 class TableDiffFormatter
extends DiffFormatter
{
2021 function TableDiffFormatter() {
2022 $this->leading_context_lines
= 2;
2023 $this->trailing_context_lines
= 2;
2026 public static function escapeWhiteSpace( $msg ) {
2027 $msg = preg_replace( '/^ /m', ' ', $msg );
2028 $msg = preg_replace( '/ $/m', ' ', $msg );
2029 $msg = preg_replace( '/ /', ' ', $msg );
2033 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2034 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2035 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2039 function _start_block( $header ) {
2043 function _end_block() {
2046 function _lines( $lines, $prefix=' ', $color='white' ) {
2049 # HTML-escape parameter before calling this
2050 function addedLine( $line ) {
2051 return $this->wrapLine( '+', 'diff-addedline', $line );
2054 # HTML-escape parameter before calling this
2055 function deletedLine( $line ) {
2056 return $this->wrapLine( '-', 'diff-deletedline', $line );
2059 # HTML-escape parameter before calling this
2060 function contextLine( $line ) {
2061 return $this->wrapLine( ' ', 'diff-context', $line );
2064 private function wrapLine( $marker, $class, $line ) {
2065 if( $line !== '' ) {
2066 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2067 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2069 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2072 function emptyLine() {
2073 return '<td colspan="2"> </td>';
2076 function _added( $lines ) {
2077 foreach ($lines as $line) {
2078 echo '<tr>' . $this->emptyLine() .
2079 $this->addedLine( '<ins class="diffchange">' .
2080 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2084 function _deleted($lines) {
2085 foreach ($lines as $line) {
2086 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2087 htmlspecialchars ( $line ) . '</del>' ) .
2088 $this->emptyLine() . "</tr>\n";
2092 function _context( $lines ) {
2093 foreach ($lines as $line) {
2095 $this->contextLine( htmlspecialchars ( $line ) ) .
2096 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2100 function _changed( $orig, $closing ) {
2101 wfProfileIn( __METHOD__
);
2103 $diff = new WordLevelDiff( $orig, $closing );
2104 $del = $diff->orig();
2105 $add = $diff->closing();
2107 # Notice that WordLevelDiff returns HTML-escaped output.
2108 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2110 while ( $line = array_shift( $del ) ) {
2111 $aline = array_shift( $add );
2112 echo '<tr>' . $this->deletedLine( $line ) .
2113 $this->addedLine( $aline ) . "</tr>\n";
2115 foreach ($add as $line) { # If any leftovers
2116 echo '<tr>' . $this->emptyLine() .
2117 $this->addedLine( $line ) . "</tr>\n";
2119 wfProfileOut( __METHOD__
);