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'];
194 $this->mRcidMarkPatrolled
= $rcid;
202 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj( $this->mTitle
,
203 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$rcid}" ) . ']</span>';
211 $htmldiffarg = $this->htmlDiffArgument();
212 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
213 'diff=prev&oldid='.$this->mOldid
.$htmldiffarg, '', '', 'id="differences-prevlink"' );
214 if ( $this->mNewRev
->isCurrent() ) {
215 $nextlink = ' ';
217 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
218 'diff=next&oldid='.$this->mNewid
.$htmldiffarg, '', '', 'id="differences-nextlink"' );
224 if( $this->mOldRev
->isMinor() ) {
225 $oldminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
227 if( $this->mNewRev
->isMinor() ) {
228 $newminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
231 $rdel = ''; $ldel = '';
232 if( $wgUser->isAllowed( 'deleterevision' ) ) {
233 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
234 // If revision was hidden from sysops
235 $ldel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
237 $query = array( 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
238 'oldid' => $this->mOldRev
->getId()
240 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
242 $ldel = " $ldel ";
243 // We don't currently handle well changing the top revision's settings
244 if( $this->mNewRev
->isCurrent() ) {
245 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
246 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
247 // If revision was hidden from sysops
248 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
250 $query = array( 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
251 'oldid' => $this->mNewRev
->getId()
253 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
255 $rdel = " $rdel ";
258 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
259 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
260 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
261 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
262 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
263 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
264 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
265 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
267 # Output the diff if allowed
268 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
) && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
269 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
270 if( $deleted && (!$this->unhide ||
!$allowed) ) {
271 $this->showDiffStyle();
272 $multi = $this->getMultiNotice();
273 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
274 $wgOut->addWikiMsg( 'rev-deleted-no-diff' );
275 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
276 $multi = $this->getMultiNotice();
277 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
278 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
279 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
280 $this->renderHtmlDiff();
282 if( $wgEnableHtmlDiff ) {
283 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
284 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
286 $this->showDiff( $oldHeader, $newHeader );
288 $this->renderNewRevision();
291 wfProfileOut( __METHOD__
);
295 * Show the new revision of the page.
297 function renderNewRevision() {
298 global $wgOut, $wgUser;
299 wfProfileIn( __METHOD__
);
301 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
302 # Add deleted rev tag if needed
303 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
304 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
305 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
306 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
309 if( !$this->mNewRev
->isCurrent() ) {
310 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
313 $this->loadNewText();
314 if( is_object( $this->mNewRev
) ) {
315 $wgOut->setRevisionId( $this->mNewRev
->getId() );
318 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
319 // Stolen from Article::view --AG 2007-10-11
320 // Give hooks a chance to customise the output
321 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
322 // Wrap the whole lot in a <pre> and don't parse
324 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
325 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
326 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
327 $wgOut->addHTML( "\n</pre>\n" );
330 $wgOut->addWikiTextTidy( $this->mNewtext
);
333 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
334 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
336 # Add redundant patrol link on bottom...
337 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
338 $sk = $wgUser->getSkin();
340 "<div class='patrollink'>[" . $sk->makeKnownLinkObj( $this->mTitle
,
341 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) .
346 wfProfileOut( __METHOD__
);
350 function renderHtmlDiff() {
351 global $wgOut, $wgTitle, $wgParser, $wgDebugComments;
352 wfProfileIn( __METHOD__
);
354 $this->showDiffStyle();
356 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
357 #add deleted rev tag if needed
358 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
359 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
360 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
361 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
364 if( !$this->mNewRev
->isCurrent() ) {
365 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
371 if( is_object( $this->mOldRev
) ) {
372 $wgOut->setRevisionId( $this->mOldRev
->getId() );
375 $popts = $wgOut->parserOptions();
376 $oldTidy = $popts->setTidy( true );
377 $popts->setEditSection( false );
379 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
380 $popts->setTidy( $oldTidy );
383 //$wgOut->addParserOutputNoText( $parserOutput );
384 $oldHtml = $parserOutput->getText();
385 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
388 if( is_object( $this->mNewRev
) ) {
389 $wgOut->setRevisionId( $this->mNewRev
->getId() );
392 $popts = $wgOut->parserOptions();
393 $oldTidy = $popts->setTidy( true );
395 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
396 $popts->setTidy( $oldTidy );
398 $wgOut->addParserOutputNoText( $parserOutput );
399 $newHtml = $parserOutput->getText();
400 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
402 unset($parserOutput, $popts);
404 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
405 $differ->htmlDiff($oldHtml, $newHtml);
406 if ( $wgDebugComments ) {
407 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
410 wfProfileOut( __METHOD__
);
414 * Show the first revision of an article. Uses normal diff headers in
415 * contrast to normal "old revision" display style.
417 function showFirstRevision() {
418 global $wgOut, $wgUser;
419 wfProfileIn( __METHOD__
);
421 # Get article text from the DB
423 if ( ! $this->loadNewText() ) {
424 $t = $this->mTitle
->getPrefixedText();
425 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
426 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
427 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
428 wfProfileOut( __METHOD__
);
431 if ( $this->mNewRev
->isCurrent() ) {
432 $wgOut->setArticleFlag( true );
435 # Check if user is allowed to look at this page. If not, bail out.
437 if ( !$this->mTitle
->userCanRead() ) {
438 $wgOut->loginToUse();
440 wfProfileOut( __METHOD__
);
441 throw new MWException("Permission Error: you do not have access to view this page");
444 # Prepare the header box
446 $sk = $wgUser->getSkin();
448 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
452 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
453 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
455 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
456 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
458 $wgOut->addHTML( $header );
460 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
461 $wgOut->setRobotPolicy( 'noindex,nofollow' );
463 wfProfileOut( __METHOD__
);
466 function htmlDiffArgument(){
467 global $wgEnableHtmlDiff;
468 if($wgEnableHtmlDiff){
470 return '&htmldiff=1';
472 return '&htmldiff=0';
480 * Get the diff text, send it to $wgOut
481 * Returns false if the diff could not be generated, otherwise returns true
483 function showDiff( $otitle, $ntitle ) {
485 $diff = $this->getDiff( $otitle, $ntitle );
486 if ( $diff === false ) {
487 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
490 $this->showDiffStyle();
491 $wgOut->addHTML( $diff );
497 * Add style sheets and supporting JS for diff display.
499 function showDiffStyle() {
500 global $wgStylePath, $wgStyleVersion, $wgOut;
501 $wgOut->addStyle( 'common/diff.css' );
503 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
504 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
508 * Get complete diff table, including header
510 * @param Title $otitle Old title
511 * @param Title $ntitle New title
514 function getDiff( $otitle, $ntitle ) {
515 $body = $this->getDiffBody();
516 if ( $body === false ) {
519 $multi = $this->getMultiNotice();
520 return $this->addHeader( $body, $otitle, $ntitle, $multi );
525 * Get the diff table body, without header
529 function getDiffBody() {
531 wfProfileIn( __METHOD__
);
532 // Check if the diff should be hidden from this user
533 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
535 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
540 if ( $this->mOldid
&& $this->mNewid
) {
541 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
543 if ( !$this->mRefreshCache
) {
544 $difftext = $wgMemc->get( $key );
546 wfIncrStats( 'diff_cache_hit' );
547 $difftext = $this->localiseLineNumbers( $difftext );
548 $difftext .= "\n<!-- diff cache key $key -->\n";
549 wfProfileOut( __METHOD__
);
552 } // don't try to load but save the result
555 // Loadtext is permission safe, this just clears out the diff
556 if ( !$this->loadText() ) {
557 wfProfileOut( __METHOD__
);
561 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
563 // Save to cache for 7 days
564 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
565 wfIncrStats( 'diff_uncacheable' );
566 } else if ( $key !== false && $difftext !== false ) {
567 wfIncrStats( 'diff_cache_miss' );
568 $wgMemc->set( $key, $difftext, 7*86400 );
570 wfIncrStats( 'diff_uncacheable' );
572 // Replace line numbers with the text in the user's language
573 if ( $difftext !== false ) {
574 $difftext = $this->localiseLineNumbers( $difftext );
576 wfProfileOut( __METHOD__
);
581 * Generate a diff, no caching
582 * $otext and $ntext must be already segmented
584 function generateDiffBody( $otext, $ntext ) {
585 global $wgExternalDiffEngine, $wgContLang;
587 $otext = str_replace( "\r\n", "\n", $otext );
588 $ntext = str_replace( "\r\n", "\n", $ntext );
590 if ( $wgExternalDiffEngine == 'wikidiff' ) {
591 # For historical reasons, external diff engine expects
592 # input text to be HTML-escaped already
593 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
594 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
595 if( !function_exists( 'wikidiff_do_diff' ) ) {
596 dl('php_wikidiff.so');
598 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
599 $this->debug( 'wikidiff1' );
602 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
603 # Better external diff engine, the 2 may some day be dropped
604 # This one does the escaping and segmenting itself
605 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
606 wfProfileIn( __METHOD__
. "-dl" );
607 @dl
('php_wikidiff2.so');
608 wfProfileOut( __METHOD__
. "-dl" );
610 if ( function_exists( 'wikidiff2_do_diff' ) ) {
611 wfProfileIn( 'wikidiff2_do_diff' );
612 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
613 $text .= $this->debug( 'wikidiff2' );
614 wfProfileOut( 'wikidiff2_do_diff' );
618 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
620 global $wgTmpDirectory;
621 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
622 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
624 $tempFile1 = fopen( $tempName1, "w" );
626 wfProfileOut( __METHOD__
);
629 $tempFile2 = fopen( $tempName2, "w" );
631 wfProfileOut( __METHOD__
);
634 fwrite( $tempFile1, $otext );
635 fwrite( $tempFile2, $ntext );
636 fclose( $tempFile1 );
637 fclose( $tempFile2 );
638 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
639 wfProfileIn( __METHOD__
. "-shellexec" );
640 $difftext = wfShellExec( $cmd );
641 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
642 wfProfileOut( __METHOD__
. "-shellexec" );
643 unlink( $tempName1 );
644 unlink( $tempName2 );
649 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
650 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
651 $diffs = new Diff( $ota, $nta );
652 $formatter = new TableDiffFormatter();
653 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
658 * Generate a debug comment indicating diff generating time,
659 * server node, and generator backend.
661 protected function debug( $generator="internal" ) {
662 global $wgShowHostnames;
663 $data = array( $generator );
664 if( $wgShowHostnames ) {
665 $data[] = wfHostname();
667 $data[] = wfTimestamp( TS_DB
);
668 return "<!-- diff generator: " .
677 * Replace line numbers with the text in the user's language
679 function localiseLineNumbers( $text ) {
680 return preg_replace_callback( '/<!--LINE (\d+)-->/',
681 array( &$this, 'localiseLineNumbersCb' ), $text );
684 function localiseLineNumbersCb( $matches ) {
686 return wfMsgExt( 'lineno', array( 'parseinline' ), $wgLang->formatNum( $matches[1] ) );
691 * If there are revisions between the ones being compared, return a note saying so.
693 function getMultiNotice() {
694 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
697 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
698 // Comparing two different pages? Count would be meaningless.
702 $oldid = $this->mOldRev
->getId();
703 $newid = $this->mNewRev
->getId();
704 if ( $oldid > $newid ) {
705 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
708 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
712 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
717 * Add the header to a diff body
719 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
722 <col class='diff-marker' />
723 <col class='diff-content' />
724 <col class='diff-marker' />
725 <col class='diff-content' />
727 <td colspan='2' class='diff-otitle'>{$otitle}</td>
728 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
733 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
735 return $header . $diff . "</table>";
739 * Use specified text instead of loading from the database
741 function setText( $oldText, $newText ) {
742 $this->mOldtext
= $oldText;
743 $this->mNewtext
= $newText;
744 $this->mTextLoaded
= 2;
748 * Load revision metadata for the specified articles. If newid is 0, then compare
749 * the old article in oldid to the current article; if oldid is 0, then
750 * compare the current article to the immediately previous one (ignoring the
753 * If oldid is false, leave the corresponding revision object set
754 * to false. This is impossible via ordinary user input, and is provided for
757 function loadRevisionData() {
758 global $wgLang, $wgUser;
759 if ( $this->mRevisionsLoaded
) {
762 // Whether it succeeds or fails, we don't want to try again
763 $this->mRevisionsLoaded
= true;
766 // Load the new revision object
767 $this->mNewRev
= $this->mNewid
768 ? Revision
::newFromId( $this->mNewid
)
769 : Revision
::newFromTitle( $this->mTitle
);
770 if( !$this->mNewRev
instanceof Revision
)
773 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
774 $this->mNewid
= $this->mNewRev
->getId();
776 // Check if page is editable
777 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
779 // Set assorted variables
780 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
781 $this->mNewPage
= $this->mNewRev
->getTitle();
782 if( $this->mNewRev
->isCurrent() ) {
783 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
784 $this->mPagetitle
= wfMsgHTML( 'currentrev-asof', $timestamp );
785 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
787 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
788 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
791 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
792 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
793 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
795 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
796 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
798 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
799 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
800 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
801 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
804 // Load the old revision object
805 $this->mOldRev
= false;
806 if( $this->mOldid
) {
807 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
808 } elseif ( $this->mOldid
=== 0 ) {
809 $rev = $this->mNewRev
->getPrevious();
811 $this->mOldid
= $rev->getId();
812 $this->mOldRev
= $rev;
814 // No previous revision; mark to show as first-version only.
815 $this->mOldid
= false;
816 $this->mOldRev
= false;
818 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
820 if( is_null( $this->mOldRev
) ) {
824 if ( $this->mOldRev
) {
825 $this->mOldPage
= $this->mOldRev
->getTitle();
827 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
828 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
829 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
830 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
832 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
833 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
834 // Add an "undo" link
835 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
836 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
837 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
838 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
839 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
842 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
843 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
844 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
845 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
853 * Load the text of the revisions, as well as revision data.
855 function loadText() {
856 if ( $this->mTextLoaded
== 2 ) {
859 // Whether it succeeds or fails, we don't want to try again
860 $this->mTextLoaded
= 2;
863 if ( !$this->loadRevisionData() ) {
866 if ( $this->mOldRev
) {
867 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
868 if ( $this->mOldtext
=== false ) {
872 if ( $this->mNewRev
) {
873 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
874 if ( $this->mNewtext
=== false ) {
882 * Load the text of the new revision, not the old one
884 function loadNewText() {
885 if ( $this->mTextLoaded
>= 1 ) {
888 $this->mTextLoaded
= 1;
890 if ( !$this->loadRevisionData() ) {
893 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
900 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
902 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
903 // You may copy this code freely under the conditions of the GPL.
906 define('USE_ASSERTS', function_exists('assert'));
911 * @ingroup DifferenceEngine
919 trigger_error('pure virtual', E_USER_ERROR
);
923 return $this->orig ?
sizeof($this->orig
) : 0;
926 function nclosing() {
927 return $this->closing ?
sizeof($this->closing
) : 0;
934 * @ingroup DifferenceEngine
936 class _DiffOp_Copy
extends _DiffOp
{
939 function _DiffOp_Copy ($orig, $closing = false) {
940 if (!is_array($closing))
943 $this->closing
= $closing;
947 return new _DiffOp_Copy($this->closing
, $this->orig
);
954 * @ingroup DifferenceEngine
956 class _DiffOp_Delete
extends _DiffOp
{
957 var $type = 'delete';
959 function _DiffOp_Delete ($lines) {
960 $this->orig
= $lines;
961 $this->closing
= false;
965 return new _DiffOp_Add($this->orig
);
972 * @ingroup DifferenceEngine
974 class _DiffOp_Add
extends _DiffOp
{
977 function _DiffOp_Add ($lines) {
978 $this->closing
= $lines;
983 return new _DiffOp_Delete($this->closing
);
990 * @ingroup DifferenceEngine
992 class _DiffOp_Change
extends _DiffOp
{
993 var $type = 'change';
995 function _DiffOp_Change ($orig, $closing) {
997 $this->closing
= $closing;
1000 function reverse() {
1001 return new _DiffOp_Change($this->closing
, $this->orig
);
1006 * Class used internally by Diff to actually compute the diffs.
1008 * The algorithm used here is mostly lifted from the perl module
1009 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1010 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1012 * More ideas are taken from:
1013 * http://www.ics.uci.edu/~eppstein/161/960229.html
1015 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1016 * diffutils-2.7, which can be found at:
1017 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1019 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1022 * Line length limits for robustness added by Tim Starling, 2005-08-31
1023 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1025 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1027 * @ingroup DifferenceEngine
1031 const MAX_XREF_LENGTH
= 10000;
1033 function diff ($from_lines, $to_lines){
1034 wfProfileIn( __METHOD__
);
1036 // Diff and store locally
1037 $this->diff_local($from_lines, $to_lines);
1039 // Merge edits when possible
1040 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1041 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1043 // Compute the edit operations.
1044 $n_from = sizeof($from_lines);
1045 $n_to = sizeof($to_lines);
1049 while ($xi < $n_from ||
$yi < $n_to) {
1050 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1051 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1053 // Skip matching "snake".
1055 while ( $xi < $n_from && $yi < $n_to
1056 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1057 $copy[] = $from_lines[$xi++
];
1061 $edits[] = new _DiffOp_Copy($copy);
1063 // Find deletes & adds.
1065 while ($xi < $n_from && $this->xchanged
[$xi])
1066 $delete[] = $from_lines[$xi++
];
1069 while ($yi < $n_to && $this->ychanged
[$yi])
1070 $add[] = $to_lines[$yi++
];
1072 if ($delete && $add)
1073 $edits[] = new _DiffOp_Change($delete, $add);
1075 $edits[] = new _DiffOp_Delete($delete);
1077 $edits[] = new _DiffOp_Add($add);
1079 wfProfileOut( __METHOD__
);
1083 function diff_local ($from_lines, $to_lines) {
1084 global $wgExternalDiffEngine;
1085 wfProfileIn( __METHOD__
);
1087 if($wgExternalDiffEngine == 'wikidiff3'){
1089 $wikidiff3 = new WikiDiff3();
1090 $wikidiff3->diff($from_lines, $to_lines);
1091 $this->xchanged
= $wikidiff3->removed
;
1092 $this->ychanged
= $wikidiff3->added
;
1096 $n_from = sizeof($from_lines);
1097 $n_to = sizeof($to_lines);
1098 $this->xchanged
= $this->ychanged
= array();
1099 $this->xv
= $this->yv
= array();
1100 $this->xind
= $this->yind
= array();
1102 unset($this->in_seq
);
1105 // Skip leading common lines.
1106 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1107 if ($from_lines[$skip] !== $to_lines[$skip])
1109 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1111 // Skip trailing common lines.
1112 $xi = $n_from; $yi = $n_to;
1113 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1114 if ($from_lines[$xi] !== $to_lines[$yi])
1116 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1119 // Ignore lines which do not exist in both files.
1120 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1121 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1124 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1125 $line = $to_lines[$yi];
1126 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1128 $yhash[$this->_line_hash($line)] = 1;
1129 $this->yv
[] = $line;
1130 $this->yind
[] = $yi;
1132 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1133 $line = $from_lines[$xi];
1134 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1136 $this->xv
[] = $line;
1137 $this->xind
[] = $xi;
1141 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1143 wfProfileOut( __METHOD__
);
1147 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1149 function _line_hash( $line ) {
1150 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1151 return md5( $line );
1157 /* Divide the Largest Common Subsequence (LCS) of the sequences
1158 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1161 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1162 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1163 * sub sequences. The first sub-sequence is contained in [X0, X1),
1164 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1165 * that (X0, Y0) == (XOFF, YOFF) and
1166 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1168 * This function assumes that the first lines of the specified portions
1169 * of the two files do not match, and likewise that the last lines do not
1170 * match. The caller must trim matching lines from the beginning and end
1171 * of the portions it is going to specify.
1173 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1176 if ($xlim - $xoff > $ylim - $yoff) {
1177 // Things seems faster (I'm not sure I understand why)
1178 // when the shortest sequence in X.
1180 list ($xoff, $xlim, $yoff, $ylim)
1181 = array( $yoff, $ylim, $xoff, $xlim);
1185 for ($i = $ylim - 1; $i >= $yoff; $i--)
1186 $ymatches[$this->xv
[$i]][] = $i;
1188 for ($i = $ylim - 1; $i >= $yoff; $i--)
1189 $ymatches[$this->yv
[$i]][] = $i;
1192 $this->seq
[0]= $yoff - 1;
1193 $this->in_seq
= array();
1194 $ymids[0] = array();
1196 $numer = $xlim - $xoff +
$nchunks - 1;
1198 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1200 for ($i = 0; $i <= $this->lcs
; $i++
)
1201 $ymids[$i][$chunk-1] = $this->seq
[$i];
1203 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1204 for ( ; $x < $x1; $x++
) {
1205 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1206 if (empty($ymatches[$line]))
1208 $matches = $ymatches[$line];
1210 while (list ($junk, $y) = each($matches))
1211 if (empty($this->in_seq
[$y])) {
1212 $k = $this->_lcs_pos($y);
1213 USE_ASSERTS
&& assert($k > 0);
1214 $ymids[$k] = $ymids[$k-1];
1217 while (list ( /* $junk */, $y) = each($matches)) {
1218 if ($y > $this->seq
[$k-1]) {
1219 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1220 // Optimization: this is a common case:
1221 // next match is just replacing previous match.
1222 $this->in_seq
[$this->seq
[$k]] = false;
1223 $this->seq
[$k] = $y;
1224 $this->in_seq
[$y] = 1;
1225 } else if (empty($this->in_seq
[$y])) {
1226 $k = $this->_lcs_pos($y);
1227 USE_ASSERTS
&& assert($k > 0);
1228 $ymids[$k] = $ymids[$k-1];
1234 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1235 $ymid = $ymids[$this->lcs
];
1236 for ($n = 0; $n < $nchunks - 1; $n++
) {
1237 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1238 $y1 = $ymid[$n] +
1;
1239 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1241 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1243 return array($this->lcs
, $seps);
1246 function _lcs_pos ($ypos) {
1248 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1249 $this->seq
[++
$this->lcs
] = $ypos;
1250 $this->in_seq
[$ypos] = 1;
1255 while ($beg < $end) {
1256 $mid = (int)(($beg +
$end) / 2);
1257 if ( $ypos > $this->seq
[$mid] )
1263 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1265 $this->in_seq
[$this->seq
[$end]] = false;
1266 $this->seq
[$end] = $ypos;
1267 $this->in_seq
[$ypos] = 1;
1271 /* Find LCS of two sequences.
1273 * The results are recorded in the vectors $this->{x,y}changed[], by
1274 * storing a 1 in the element for each line that is an insertion
1275 * or deletion (ie. is not in the LCS).
1277 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1279 * Note that XLIM, YLIM are exclusive bounds.
1280 * All line numbers are origin-0 and discarded lines are not counted.
1282 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1283 // Slide down the bottom initial diagonal.
1284 while ($xoff < $xlim && $yoff < $ylim
1285 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1290 // Slide up the top initial diagonal.
1291 while ($xlim > $xoff && $ylim > $yoff
1292 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1297 if ($xoff == $xlim ||
$yoff == $ylim)
1300 // This is ad hoc but seems to work well.
1301 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1302 //$nchunks = max(2,min(8,(int)$nchunks));
1303 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1305 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1309 // X and Y sequences have no common subsequence:
1310 // mark all changed.
1311 while ($yoff < $ylim)
1312 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1313 while ($xoff < $xlim)
1314 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1316 // Use the partitions to split this problem into subproblems.
1319 while ($pt2 = next($seps)) {
1320 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1326 /* Adjust inserts/deletes of identical lines to join changes
1327 * as much as possible.
1329 * We do something when a run of changed lines include a
1330 * line at one end and has an excluded, identical line at the other.
1331 * We are free to choose which identical line is included.
1332 * `compareseq' usually chooses the one at the beginning,
1333 * but usually it is cleaner to consider the following identical line
1334 * to be the "change".
1336 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1338 function _shift_boundaries ($lines, &$changed, $other_changed) {
1339 wfProfileIn( __METHOD__
);
1343 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1344 $len = sizeof($lines);
1345 $other_len = sizeof($other_changed);
1349 * Scan forwards to find beginning of another run of changes.
1350 * Also keep track of the corresponding point in the other file.
1352 * Throughout this code, $i and $j are adjusted together so that
1353 * the first $i elements of $changed and the first $j elements
1354 * of $other_changed both contain the same number of zeros
1355 * (unchanged lines).
1356 * Furthermore, $j is always kept so that $j == $other_len or
1357 * $other_changed[$j] == false.
1359 while ($j < $other_len && $other_changed[$j])
1362 while ($i < $len && ! $changed[$i]) {
1363 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1365 while ($j < $other_len && $other_changed[$j])
1374 // Find the end of this run of changes.
1375 while (++
$i < $len && $changed[$i])
1380 * Record the length of this run of changes, so that
1381 * we can later determine whether the run has grown.
1383 $runlength = $i - $start;
1386 * Move the changed region back, so long as the
1387 * previous unchanged line matches the last changed one.
1388 * This merges with previous changed regions.
1390 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1391 $changed[--$start] = 1;
1392 $changed[--$i] = false;
1393 while ($start > 0 && $changed[$start - 1])
1395 USE_ASSERTS
&& assert('$j > 0');
1396 while ($other_changed[--$j])
1398 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1402 * Set CORRESPONDING to the end of the changed run, at the last
1403 * point where it corresponds to a changed run in the other file.
1404 * CORRESPONDING == LEN means no such point has been found.
1406 $corresponding = $j < $other_len ?
$i : $len;
1409 * Move the changed region forward, so long as the
1410 * first changed line matches the following unchanged one.
1411 * This merges with following changed regions.
1412 * Do this second, so that if there are no merges,
1413 * the changed region is moved forward as far as possible.
1415 while ($i < $len && $lines[$start] == $lines[$i]) {
1416 $changed[$start++
] = false;
1418 while ($i < $len && $changed[$i])
1421 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1423 if ($j < $other_len && $other_changed[$j]) {
1424 $corresponding = $i;
1425 while ($j < $other_len && $other_changed[$j])
1429 } while ($runlength != $i - $start);
1432 * If possible, move the fully-merged run of changes
1433 * back to a corresponding run in the other file.
1435 while ($corresponding < $i) {
1436 $changed[--$start] = 1;
1438 USE_ASSERTS
&& assert('$j > 0');
1439 while ($other_changed[--$j])
1441 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1444 wfProfileOut( __METHOD__
);
1449 * Class representing a 'diff' between two sequences of strings.
1452 * @ingroup DifferenceEngine
1460 * Computes diff between sequences of strings.
1462 * @param $from_lines array An array of strings.
1463 * (Typically these are lines from a file.)
1464 * @param $to_lines array An array of strings.
1466 function Diff($from_lines, $to_lines) {
1467 $eng = new _DiffEngine
;
1468 $this->edits
= $eng->diff($from_lines, $to_lines);
1469 //$this->_check($from_lines, $to_lines);
1473 * Compute reversed Diff.
1477 * $diff = new Diff($lines1, $lines2);
1478 * $rev = $diff->reverse();
1479 * @return object A Diff object representing the inverse of the
1482 function reverse () {
1484 $rev->edits
= array();
1485 foreach ($this->edits
as $edit) {
1486 $rev->edits
[] = $edit->reverse();
1492 * Check for empty diff.
1494 * @return bool True iff two sequences were identical.
1496 function isEmpty () {
1497 foreach ($this->edits
as $edit) {
1498 if ($edit->type
!= 'copy')
1505 * Compute the length of the Longest Common Subsequence (LCS).
1507 * This is mostly for diagnostic purposed.
1509 * @return int The length of the LCS.
1513 foreach ($this->edits
as $edit) {
1514 if ($edit->type
== 'copy')
1515 $lcs +
= sizeof($edit->orig
);
1521 * Get the original set of lines.
1523 * This reconstructs the $from_lines parameter passed to the
1526 * @return array The original sequence of strings.
1531 foreach ($this->edits
as $edit) {
1533 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1539 * Get the closing set of lines.
1541 * This reconstructs the $to_lines parameter passed to the
1544 * @return array The sequence of strings.
1546 function closing() {
1549 foreach ($this->edits
as $edit) {
1551 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1557 * Check a Diff for validity.
1559 * This is here only for debugging purposes.
1561 function _check ($from_lines, $to_lines) {
1562 wfProfileIn( __METHOD__
);
1563 if (serialize($from_lines) != serialize($this->orig()))
1564 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1565 if (serialize($to_lines) != serialize($this->closing()))
1566 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1568 $rev = $this->reverse();
1569 if (serialize($to_lines) != serialize($rev->orig()))
1570 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1571 if (serialize($from_lines) != serialize($rev->closing()))
1572 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1576 foreach ($this->edits
as $edit) {
1577 if ( $prevtype == $edit->type
)
1578 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1579 $prevtype = $edit->type
;
1582 $lcs = $this->lcs();
1583 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1584 wfProfileOut( __METHOD__
);
1589 * @todo document, bad name.
1591 * @ingroup DifferenceEngine
1593 class MappedDiff
extends Diff
1598 * Computes diff between sequences of strings.
1600 * This can be used to compute things like
1601 * case-insensitve diffs, or diffs which ignore
1602 * changes in white-space.
1604 * @param $from_lines array An array of strings.
1605 * (Typically these are lines from a file.)
1607 * @param $to_lines array An array of strings.
1609 * @param $mapped_from_lines array This array should
1610 * have the same size number of elements as $from_lines.
1611 * The elements in $mapped_from_lines and
1612 * $mapped_to_lines are what is actually compared
1613 * when computing the diff.
1615 * @param $mapped_to_lines array This array should
1616 * have the same number of elements as $to_lines.
1618 function MappedDiff($from_lines, $to_lines,
1619 $mapped_from_lines, $mapped_to_lines) {
1620 wfProfileIn( __METHOD__
);
1622 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1623 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1625 $this->Diff($mapped_from_lines, $mapped_to_lines);
1628 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1629 $orig = &$this->edits
[$i]->orig
;
1630 if (is_array($orig)) {
1631 $orig = array_slice($from_lines, $xi, sizeof($orig));
1632 $xi +
= sizeof($orig);
1635 $closing = &$this->edits
[$i]->closing
;
1636 if (is_array($closing)) {
1637 $closing = array_slice($to_lines, $yi, sizeof($closing));
1638 $yi +
= sizeof($closing);
1641 wfProfileOut( __METHOD__
);
1646 * A class to format Diffs
1648 * This class formats the diff in classic diff format.
1649 * It is intended that this class be customized via inheritance,
1650 * to obtain fancier outputs.
1653 * @ingroup DifferenceEngine
1655 class DiffFormatter
{
1657 * Number of leading context "lines" to preserve.
1659 * This should be left at zero for this class, but subclasses
1660 * may want to set this to other values.
1662 var $leading_context_lines = 0;
1665 * Number of trailing context "lines" to preserve.
1667 * This should be left at zero for this class, but subclasses
1668 * may want to set this to other values.
1670 var $trailing_context_lines = 0;
1675 * @param $diff object A Diff object.
1676 * @return string The formatted output.
1678 function format($diff) {
1679 wfProfileIn( __METHOD__
);
1685 $nlead = $this->leading_context_lines
;
1686 $ntrail = $this->trailing_context_lines
;
1688 $this->_start_diff();
1690 foreach ($diff->edits
as $edit) {
1691 if ($edit->type
== 'copy') {
1692 if (is_array($block)) {
1693 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1698 $context = array_slice($edit->orig
, 0, $ntrail);
1699 $block[] = new _DiffOp_Copy($context);
1701 $this->_block($x0, $ntrail +
$xi - $x0,
1702 $y0, $ntrail +
$yi - $y0,
1707 $context = $edit->orig
;
1710 if (! is_array($block)) {
1711 $context = array_slice($context, sizeof($context) - $nlead);
1712 $x0 = $xi - sizeof($context);
1713 $y0 = $yi - sizeof($context);
1716 $block[] = new _DiffOp_Copy($context);
1722 $xi +
= sizeof($edit->orig
);
1724 $yi +
= sizeof($edit->closing
);
1727 if (is_array($block))
1728 $this->_block($x0, $xi - $x0,
1732 $end = $this->_end_diff();
1733 wfProfileOut( __METHOD__
);
1737 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1738 wfProfileIn( __METHOD__
);
1739 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1740 foreach ($edits as $edit) {
1741 if ($edit->type
== 'copy')
1742 $this->_context($edit->orig
);
1743 elseif ($edit->type
== 'add')
1744 $this->_added($edit->closing
);
1745 elseif ($edit->type
== 'delete')
1746 $this->_deleted($edit->orig
);
1747 elseif ($edit->type
== 'change')
1748 $this->_changed($edit->orig
, $edit->closing
);
1750 trigger_error('Unknown edit type', E_USER_ERROR
);
1752 $this->_end_block();
1753 wfProfileOut( __METHOD__
);
1756 function _start_diff() {
1760 function _end_diff() {
1761 $val = ob_get_contents();
1766 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1768 $xbeg .= "," . ($xbeg +
$xlen - 1);
1770 $ybeg .= "," . ($ybeg +
$ylen - 1);
1772 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1775 function _start_block($header) {
1776 echo $header . "\n";
1779 function _end_block() {
1782 function _lines($lines, $prefix = ' ') {
1783 foreach ($lines as $line)
1784 echo "$prefix $line\n";
1787 function _context($lines) {
1788 $this->_lines($lines);
1791 function _added($lines) {
1792 $this->_lines($lines, '>');
1794 function _deleted($lines) {
1795 $this->_lines($lines, '<');
1798 function _changed($orig, $closing) {
1799 $this->_deleted($orig);
1801 $this->_added($closing);
1806 * A formatter that outputs unified diffs
1807 * @ingroup DifferenceEngine
1810 class UnifiedDiffFormatter
extends DiffFormatter
{
1811 var $leading_context_lines = 2;
1812 var $trailing_context_lines = 2;
1814 function _added($lines) {
1815 $this->_lines($lines, '+');
1817 function _deleted($lines) {
1818 $this->_lines($lines, '-');
1820 function _changed($orig, $closing) {
1821 $this->_deleted($orig);
1822 $this->_added($closing);
1824 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1825 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1830 * A pseudo-formatter that just passes along the Diff::$edits array
1831 * @ingroup DifferenceEngine
1833 class ArrayDiffFormatter
extends DiffFormatter
{
1834 function format($diff) {
1838 foreach($diff->edits
as $edit)
1839 switch($edit->type
) {
1841 foreach($edit->closing
as $l) {
1845 'newline' => $newline++
1850 foreach($edit->orig
as $l) {
1852 'action' => 'delete',
1854 'oldline' => $oldline++
,
1859 foreach($edit->orig
as $i => $l) {
1861 'action' => 'change',
1863 'new' => @$edit->closing
[$i],
1864 'oldline' => $oldline++
,
1865 'newline' => $newline++
,
1870 $oldline +
= count($edit->orig
);
1871 $newline +
= count($edit->orig
);
1878 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1882 define('NBSP', ' '); // iso-8859-x non-breaking space.
1887 * @ingroup DifferenceEngine
1889 class _HWLDF_WordAccumulator
{
1890 function _HWLDF_WordAccumulator () {
1891 $this->_lines
= array();
1897 function _flushGroup ($new_tag) {
1898 if ($this->_group
!== '') {
1899 if ($this->_tag
== 'ins')
1900 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1901 htmlspecialchars ( $this->_group
) . '</ins>';
1902 elseif ($this->_tag
== 'del')
1903 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1904 htmlspecialchars ( $this->_group
) . '</del>';
1906 $this->_line
.= htmlspecialchars ( $this->_group
);
1909 $this->_tag
= $new_tag;
1912 function _flushLine ($new_tag) {
1913 $this->_flushGroup($new_tag);
1914 if ($this->_line
!= '')
1915 array_push ( $this->_lines
, $this->_line
);
1917 # make empty lines visible by inserting an NBSP
1918 array_push ( $this->_lines
, NBSP
);
1922 function addWords ($words, $tag = '') {
1923 if ($tag != $this->_tag
)
1924 $this->_flushGroup($tag);
1926 foreach ($words as $word) {
1927 // new-line should only come as first char of word.
1930 if ($word[0] == "\n") {
1931 $this->_flushLine($tag);
1932 $word = substr($word, 1);
1934 assert(!strstr($word, "\n"));
1935 $this->_group
.= $word;
1939 function getLines() {
1940 $this->_flushLine('~done');
1941 return $this->_lines
;
1948 * @ingroup DifferenceEngine
1950 class WordLevelDiff
extends MappedDiff
{
1951 const MAX_LINE_LENGTH
= 10000;
1953 function WordLevelDiff ($orig_lines, $closing_lines) {
1954 wfProfileIn( __METHOD__
);
1956 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1957 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1959 $this->MappedDiff($orig_words, $closing_words,
1960 $orig_stripped, $closing_stripped);
1961 wfProfileOut( __METHOD__
);
1964 function _split($lines) {
1965 wfProfileIn( __METHOD__
);
1968 $stripped = array();
1970 foreach ( $lines as $line ) {
1971 # If the line is too long, just pretend the entire line is one big word
1972 # This prevents resource exhaustion problems
1979 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1981 $stripped[] = $line;
1984 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1987 $words = array_merge( $words, $m[0] );
1988 $stripped = array_merge( $stripped, $m[1] );
1992 wfProfileOut( __METHOD__
);
1993 return array($words, $stripped);
1997 wfProfileIn( __METHOD__
);
1998 $orig = new _HWLDF_WordAccumulator
;
2000 foreach ($this->edits
as $edit) {
2001 if ($edit->type
== 'copy')
2002 $orig->addWords($edit->orig
);
2003 elseif ($edit->orig
)
2004 $orig->addWords($edit->orig
, 'del');
2006 $lines = $orig->getLines();
2007 wfProfileOut( __METHOD__
);
2011 function closing () {
2012 wfProfileIn( __METHOD__
);
2013 $closing = new _HWLDF_WordAccumulator
;
2015 foreach ($this->edits
as $edit) {
2016 if ($edit->type
== 'copy')
2017 $closing->addWords($edit->closing
);
2018 elseif ($edit->closing
)
2019 $closing->addWords($edit->closing
, 'ins');
2021 $lines = $closing->getLines();
2022 wfProfileOut( __METHOD__
);
2028 * Wikipedia Table style diff formatter.
2031 * @ingroup DifferenceEngine
2033 class TableDiffFormatter
extends DiffFormatter
{
2034 function TableDiffFormatter() {
2035 $this->leading_context_lines
= 2;
2036 $this->trailing_context_lines
= 2;
2039 public static function escapeWhiteSpace( $msg ) {
2040 $msg = preg_replace( '/^ /m', ' ', $msg );
2041 $msg = preg_replace( '/ $/m', ' ', $msg );
2042 $msg = preg_replace( '/ /', ' ', $msg );
2046 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2047 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2048 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2052 function _start_block( $header ) {
2056 function _end_block() {
2059 function _lines( $lines, $prefix=' ', $color='white' ) {
2062 # HTML-escape parameter before calling this
2063 function addedLine( $line ) {
2064 return $this->wrapLine( '+', 'diff-addedline', $line );
2067 # HTML-escape parameter before calling this
2068 function deletedLine( $line ) {
2069 return $this->wrapLine( '-', 'diff-deletedline', $line );
2072 # HTML-escape parameter before calling this
2073 function contextLine( $line ) {
2074 return $this->wrapLine( ' ', 'diff-context', $line );
2077 private function wrapLine( $marker, $class, $line ) {
2078 if( $line !== '' ) {
2079 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2080 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2082 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2085 function emptyLine() {
2086 return '<td colspan="2"> </td>';
2089 function _added( $lines ) {
2090 foreach ($lines as $line) {
2091 echo '<tr>' . $this->emptyLine() .
2092 $this->addedLine( '<ins class="diffchange">' .
2093 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2097 function _deleted($lines) {
2098 foreach ($lines as $line) {
2099 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2100 htmlspecialchars ( $line ) . '</del>' ) .
2101 $this->emptyLine() . "</tr>\n";
2105 function _context( $lines ) {
2106 foreach ($lines as $line) {
2108 $this->contextLine( htmlspecialchars ( $line ) ) .
2109 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2113 function _changed( $orig, $closing ) {
2114 wfProfileIn( __METHOD__
);
2116 $diff = new WordLevelDiff( $orig, $closing );
2117 $del = $diff->orig();
2118 $add = $diff->closing();
2120 # Notice that WordLevelDiff returns HTML-escaped output.
2121 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2123 while ( $line = array_shift( $del ) ) {
2124 $aline = array_shift( $add );
2125 echo '<tr>' . $this->deletedLine( $line ) .
2126 $this->addedLine( $aline ) . "</tr>\n";
2128 foreach ($add as $line) { # If any leftovers
2129 echo '<tr>' . $this->emptyLine() .
2130 $this->addedLine( $line ) . "</tr>\n";
2132 wfProfileOut( __METHOD__
);