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?
30 var $mCacheHit = false; // Was the diff fetched from cache?
33 protected $unhide = false;
38 * @param $titleObj Title object that the diff is associated with
39 * @param $old Integer: old ID we want to show and diff with.
40 * @param $new String: either 'prev' or 'next'.
41 * @param $rcid Integer: ??? FIXME (default 0)
42 * @param $refreshCache boolean If set, refreshes the diff cache
43 * @param $htmldiff boolean If set, output using HTMLDiff instead of raw wikicode diff
44 * @param $unhide boolean If set, allow viewing deleted revs
46 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0,
47 $refreshCache = false, $htmldiff = false, $unhide = false )
49 $this->mTitle
= $titleObj;
50 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
52 if ( 'prev' === $new ) {
53 # Show diff between revision $old and the previous one.
54 # Get previous one from DB.
55 $this->mNewid
= intval($old);
56 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
57 } elseif ( 'next' === $new ) {
58 # Show diff between revision $old and the next one.
59 # Get next one from DB.
60 $this->mOldid
= intval($old);
61 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
62 if ( false === $this->mNewid
) {
63 # if no result, NewId points to the newest old revision. The only newer
64 # revision is cur, which is "0".
68 $this->mOldid
= intval($old);
69 $this->mNewid
= intval($new);
70 wfRunHooks( 'NewDifferenceEngine', array(&$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new) );
72 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
73 $this->mRefreshCache
= $refreshCache;
74 $this->htmldiff
= $htmldiff;
75 $this->unhide
= $unhide;
82 function wasCacheHit() {
83 return $this->mCacheHit
;
94 function showDiffPage( $diffOnly = false ) {
95 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
96 wfProfileIn( __METHOD__
);
99 # If external diffs are enabled both globally and for the user,
100 # we'll use the application/x-external-editor interface to call
101 # an external diff tool like kompare, kdiff3, etc.
102 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
103 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
105 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
106 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
107 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
108 $special=$wgLang->getNsText(NS_SPECIAL
);
113 Script={$wgServer}{$wgScript}
114 Special namespace={$special}
128 $wgOut->setArticleFlag( false );
129 if ( !$this->loadRevisionData() ) {
130 $t = $this->mTitle
->getPrefixedText();
131 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
132 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
133 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
134 wfProfileOut( __METHOD__
);
138 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
140 if ( $this->mNewRev
->isCurrent() ) {
141 $wgOut->setArticleFlag( true );
144 # mOldid is false if the difference engine is called with a "vague" query for
145 # a diff between a version V and its previous version V' AND the version V
146 # is the first version of that article. In that case, V' does not exist.
147 if ( $this->mOldid
=== false ) {
148 $this->showFirstRevision();
149 $this->renderNewRevision(); // should we respect $diffOnly here or not?
150 wfProfileOut( __METHOD__
);
154 $wgOut->suppressQuickbar();
156 $oldTitle = $this->mOldPage
->getPrefixedText();
157 $newTitle = $this->mNewPage
->getPrefixedText();
158 if( $oldTitle == $newTitle ) {
159 $wgOut->setPageTitle( $newTitle );
161 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
163 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
164 $wgOut->setRobotPolicy( 'noindex,nofollow' );
166 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
167 $wgOut->loginToUse();
170 wfProfileOut( __METHOD__
);
174 $sk = $wgUser->getSkin();
176 // Check if page is editable
177 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
178 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
179 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
184 // Prepare a change patrol link, if applicable
185 if( $wgUseRCPatrol && $this->mTitle
->userCan('patrol') ) {
186 // If we've been given an explicit change identifier, use it; saves time
187 if( $this->mRcidMarkPatrolled
) {
188 $rcid = $this->mRcidMarkPatrolled
;
189 $rc = RecentChange
::newFromId( $rcid );
190 // Already patrolled?
191 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ?
$rcid : 0;
193 // Look for an unpatrolled change corresponding to this diff
194 $db = wfGetDB( DB_SLAVE
);
195 $change = RecentChange
::newFromConds(
197 // Redundant user,timestamp condition so we can use the existing index
198 'rc_user_text' => $this->mNewRev
->getRawUserText(),
199 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
200 'rc_this_oldid' => $this->mNewid
,
201 'rc_last_oldid' => $this->mOldid
,
206 if( $change instanceof RecentChange
) {
207 $rcid = $change->mAttribs
['rc_id'];
208 $this->mRcidMarkPatrolled
= $rcid;
216 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj( $this->mTitle
,
217 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$rcid}" ) . ']</span>';
226 # Carry over 'diffonly' param via navigation links
227 if( $diffOnly != $wgUser->getBoolOption('diffonly') ) {
228 $diffOnlyArg = '&diffonly='.$diffOnly;
230 $htmldiffarg = $this->htmlDiffArgument();
231 # Make "previous revision link"
232 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
233 "diff=prev&oldid={$this->mOldid}{$htmldiffarg}{$diffOnlyArg}", '', '', 'id="differences-prevlink"' );
234 # Make "next revision link"
235 if( $this->mNewRev
->isCurrent() ) {
236 $nextlink = ' ';
238 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
239 "diff=next&oldid={$this->mNewid}{$htmldiffarg}{$diffOnlyArg}", '', '', 'id="differences-nextlink"' );
245 if( $this->mOldRev
->isMinor() ) {
246 $oldminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
248 if( $this->mNewRev
->isMinor() ) {
249 $newminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
252 $rdel = ''; $ldel = '';
253 if( $wgUser->isAllowed( 'deleterevision' ) ) {
254 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
255 // If revision was hidden from sysops
256 $ldel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
258 $query = array( 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
259 'oldid' => $this->mOldRev
->getId()
261 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
263 $ldel = " $ldel ";
264 // We don't currently handle well changing the top revision's settings
265 if( $this->mNewRev
->isCurrent() ) {
266 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
267 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
268 // If revision was hidden from sysops
269 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
271 $query = array( 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
272 'oldid' => $this->mNewRev
->getId()
274 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
276 $rdel = " $rdel ";
279 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
280 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
281 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
282 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
283 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
284 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
285 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
286 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
288 # Check if this user can see the revisions
289 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
)
290 && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
291 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
)
292 ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
293 # Output the diff if allowed...
294 if( $deleted && (!$this->unhide ||
!$allowed) ) {
295 $this->showDiffStyle();
296 $multi = $this->getMultiNotice();
297 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
299 # Give explanation for why revision is not visible
300 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
301 array( 'rev-deleted-no-diff' ) );
303 # Give explanation and add a link to view the diff...
304 $link = $this->mTitle
->getFullUrl( "diff={$this->mNewid}&oldid={$this->mOldid}".
305 '&unhide=1&token='.urlencode( $wgUser->editToken($this->mNewid
) ) );
306 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
307 array( 'rev-deleted-unhide-diff', $link ) );
309 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
310 $multi = $this->getMultiNotice();
311 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
312 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
313 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
314 $this->renderHtmlDiff();
316 if( $wgEnableHtmlDiff ) {
317 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
318 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
320 $this->showDiff( $oldHeader, $newHeader );
322 $this->renderNewRevision();
325 wfProfileOut( __METHOD__
);
329 * Show the new revision of the page.
331 function renderNewRevision() {
332 global $wgOut, $wgUser;
333 wfProfileIn( __METHOD__
);
335 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
336 # Add deleted rev tag if needed
337 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
338 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
339 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
340 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
343 if( !$this->mNewRev
->isCurrent() ) {
344 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
347 $this->loadNewText();
348 if( is_object( $this->mNewRev
) ) {
349 $wgOut->setRevisionId( $this->mNewRev
->getId() );
352 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
353 // Stolen from Article::view --AG 2007-10-11
354 // Give hooks a chance to customise the output
355 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
356 // Wrap the whole lot in a <pre> and don't parse
358 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
359 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
360 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
361 $wgOut->addHTML( "\n</pre>\n" );
364 $wgOut->addWikiTextTidy( $this->mNewtext
);
367 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
368 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
370 # Add redundant patrol link on bottom...
371 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
372 $sk = $wgUser->getSkin();
374 "<div class='patrollink'>[" . $sk->makeKnownLinkObj( $this->mTitle
,
375 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) .
380 wfProfileOut( __METHOD__
);
384 function renderHtmlDiff() {
385 global $wgOut, $wgParser, $wgDebugComments;
386 wfProfileIn( __METHOD__
);
388 $this->showDiffStyle();
390 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
391 #add deleted rev tag if needed
392 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
393 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
394 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
395 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
398 if( !$this->mNewRev
->isCurrent() ) {
399 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
405 if( is_object( $this->mOldRev
) ) {
406 $wgOut->setRevisionId( $this->mOldRev
->getId() );
409 $popts = $wgOut->parserOptions();
410 $oldTidy = $popts->setTidy( true );
411 $popts->setEditSection( false );
413 $parserOutput = $wgParser->parse( $this->mOldtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
414 $popts->setTidy( $oldTidy );
417 //$wgOut->addParserOutputNoText( $parserOutput );
418 $oldHtml = $parserOutput->getText();
419 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
422 if( is_object( $this->mNewRev
) ) {
423 $wgOut->setRevisionId( $this->mNewRev
->getId() );
426 $popts = $wgOut->parserOptions();
427 $oldTidy = $popts->setTidy( true );
429 $parserOutput = $wgParser->parse( $this->mNewtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
430 $popts->setTidy( $oldTidy );
432 $wgOut->addParserOutputNoText( $parserOutput );
433 $newHtml = $parserOutput->getText();
434 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
436 unset($parserOutput, $popts);
438 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
439 $differ->htmlDiff($oldHtml, $newHtml);
440 if ( $wgDebugComments ) {
441 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
444 wfProfileOut( __METHOD__
);
448 * Show the first revision of an article. Uses normal diff headers in
449 * contrast to normal "old revision" display style.
451 function showFirstRevision() {
452 global $wgOut, $wgUser;
453 wfProfileIn( __METHOD__
);
455 # Get article text from the DB
457 if ( ! $this->loadNewText() ) {
458 $t = $this->mTitle
->getPrefixedText();
459 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
460 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
461 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
462 wfProfileOut( __METHOD__
);
465 if ( $this->mNewRev
->isCurrent() ) {
466 $wgOut->setArticleFlag( true );
469 # Check if user is allowed to look at this page. If not, bail out.
471 if ( !$this->mTitle
->userCanRead() ) {
472 $wgOut->loginToUse();
474 wfProfileOut( __METHOD__
);
475 throw new MWException("Permission Error: you do not have access to view this page");
478 # Prepare the header box
480 $sk = $wgUser->getSkin();
482 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
486 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
487 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
489 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
490 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
492 $wgOut->addHTML( $header );
494 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
495 $wgOut->setRobotPolicy( 'noindex,nofollow' );
497 wfProfileOut( __METHOD__
);
500 function htmlDiffArgument(){
501 global $wgEnableHtmlDiff;
502 if($wgEnableHtmlDiff){
504 return '&htmldiff=1';
506 return '&htmldiff=0';
514 * Get the diff text, send it to $wgOut
515 * Returns false if the diff could not be generated, otherwise returns true
517 function showDiff( $otitle, $ntitle ) {
519 $diff = $this->getDiff( $otitle, $ntitle );
520 if ( $diff === false ) {
521 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
524 $this->showDiffStyle();
525 $wgOut->addHTML( $diff );
531 * Add style sheets and supporting JS for diff display.
533 function showDiffStyle() {
534 global $wgStylePath, $wgStyleVersion, $wgOut;
535 $wgOut->addStyle( 'common/diff.css' );
537 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
538 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
542 * Get complete diff table, including header
544 * @param Title $otitle Old title
545 * @param Title $ntitle New title
548 function getDiff( $otitle, $ntitle ) {
549 $body = $this->getDiffBody();
550 if ( $body === false ) {
553 $multi = $this->getMultiNotice();
554 return $this->addHeader( $body, $otitle, $ntitle, $multi );
559 * Get the diff table body, without header
563 function getDiffBody() {
565 wfProfileIn( __METHOD__
);
566 $this->mCacheHit
= true;
567 // Check if the diff should be hidden from this user
568 if ( !$this->loadRevisionData() )
570 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
572 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
574 } else if ( $this->mOldRev
&& $this->mNewRev
&& $this->mOldRev
->getID() == $this->mNewRev
->getID() ) {
579 if ( $this->mOldid
&& $this->mNewid
) {
580 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
582 if ( !$this->mRefreshCache
) {
583 $difftext = $wgMemc->get( $key );
585 wfIncrStats( 'diff_cache_hit' );
586 $difftext = $this->localiseLineNumbers( $difftext );
587 $difftext .= "\n<!-- diff cache key $key -->\n";
588 wfProfileOut( __METHOD__
);
591 } // don't try to load but save the result
593 $this->mCacheHit
= false;
595 // Loadtext is permission safe, this just clears out the diff
596 if ( !$this->loadText() ) {
597 wfProfileOut( __METHOD__
);
601 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
603 // Save to cache for 7 days
604 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
605 wfIncrStats( 'diff_uncacheable' );
606 } else if ( $key !== false && $difftext !== false ) {
607 wfIncrStats( 'diff_cache_miss' );
608 $wgMemc->set( $key, $difftext, 7*86400 );
610 wfIncrStats( 'diff_uncacheable' );
612 // Replace line numbers with the text in the user's language
613 if ( $difftext !== false ) {
614 $difftext = $this->localiseLineNumbers( $difftext );
616 wfProfileOut( __METHOD__
);
621 * Make sure the proper modules are loaded before we try to
624 private function initDiffEngines() {
625 global $wgExternalDiffEngine;
626 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
627 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
628 wfSuppressWarnings();
629 dl( 'php_wikidiff.so' );
631 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
633 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
634 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
635 wfSuppressWarnings();
636 dl( 'php_wikidiff2.so' );
638 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
643 * Generate a diff, no caching
644 * $otext and $ntext must be already segmented
646 function generateDiffBody( $otext, $ntext ) {
647 global $wgExternalDiffEngine, $wgContLang;
649 $otext = str_replace( "\r\n", "\n", $otext );
650 $ntext = str_replace( "\r\n", "\n", $ntext );
652 $this->initDiffEngines();
654 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
655 # For historical reasons, external diff engine expects
656 # input text to be HTML-escaped already
657 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
658 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
659 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
660 $this->debug( 'wikidiff1' );
663 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
664 # Better external diff engine, the 2 may some day be dropped
665 # This one does the escaping and segmenting itself
666 wfProfileIn( 'wikidiff2_do_diff' );
667 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
668 $text .= $this->debug( 'wikidiff2' );
669 wfProfileOut( 'wikidiff2_do_diff' );
672 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
674 global $wgTmpDirectory;
675 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
676 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
678 $tempFile1 = fopen( $tempName1, "w" );
680 wfProfileOut( __METHOD__
);
683 $tempFile2 = fopen( $tempName2, "w" );
685 wfProfileOut( __METHOD__
);
688 fwrite( $tempFile1, $otext );
689 fwrite( $tempFile2, $ntext );
690 fclose( $tempFile1 );
691 fclose( $tempFile2 );
692 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
693 wfProfileIn( __METHOD__
. "-shellexec" );
694 $difftext = wfShellExec( $cmd );
695 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
696 wfProfileOut( __METHOD__
. "-shellexec" );
697 unlink( $tempName1 );
698 unlink( $tempName2 );
703 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
704 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
705 $diffs = new Diff( $ota, $nta );
706 $formatter = new TableDiffFormatter();
707 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
712 * Generate a debug comment indicating diff generating time,
713 * server node, and generator backend.
715 protected function debug( $generator="internal" ) {
716 global $wgShowHostnames;
717 $data = array( $generator );
718 if( $wgShowHostnames ) {
719 $data[] = wfHostname();
721 $data[] = wfTimestamp( TS_DB
);
722 return "<!-- diff generator: " .
731 * Replace line numbers with the text in the user's language
733 function localiseLineNumbers( $text ) {
734 return preg_replace_callback( '/<!--LINE (\d+)-->/',
735 array( &$this, 'localiseLineNumbersCb' ), $text );
738 function localiseLineNumbersCb( $matches ) {
740 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
745 * If there are revisions between the ones being compared, return a note saying so.
747 function getMultiNotice() {
748 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
751 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
752 // Comparing two different pages? Count would be meaningless.
756 $oldid = $this->mOldRev
->getId();
757 $newid = $this->mNewRev
->getId();
758 if ( $oldid > $newid ) {
759 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
762 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
766 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
771 * Add the header to a diff body
773 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
775 $header = "<table class='diff'>";
776 if( $diff ) { // Safari/Chrome show broken output if cols not used
778 <col class='diff-marker' />
779 <col class='diff-content' />
780 <col class='diff-marker' />
781 <col class='diff-content' />";
786 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
787 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
791 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
793 return $header . $diff . "</table>";
797 * Use specified text instead of loading from the database
799 function setText( $oldText, $newText ) {
800 $this->mOldtext
= $oldText;
801 $this->mNewtext
= $newText;
802 $this->mTextLoaded
= 2;
803 $this->mRevisionsLoaded
= true;
807 * Load revision metadata for the specified articles. If newid is 0, then compare
808 * the old article in oldid to the current article; if oldid is 0, then
809 * compare the current article to the immediately previous one (ignoring the
812 * If oldid is false, leave the corresponding revision object set
813 * to false. This is impossible via ordinary user input, and is provided for
816 function loadRevisionData() {
817 global $wgLang, $wgUser;
818 if ( $this->mRevisionsLoaded
) {
821 // Whether it succeeds or fails, we don't want to try again
822 $this->mRevisionsLoaded
= true;
825 // Load the new revision object
826 $this->mNewRev
= $this->mNewid
827 ? Revision
::newFromId( $this->mNewid
)
828 : Revision
::newFromTitle( $this->mTitle
);
829 if( !$this->mNewRev
instanceof Revision
)
832 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
833 $this->mNewid
= $this->mNewRev
->getId();
835 // Check if page is editable
836 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
838 // Set assorted variables
839 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
840 $this->mNewPage
= $this->mNewRev
->getTitle();
841 if( $this->mNewRev
->isCurrent() ) {
842 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
843 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev-asof', $timestamp ) );
844 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
846 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
847 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
849 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
850 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
851 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
853 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
854 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
856 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
857 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
858 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
859 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
862 // Load the old revision object
863 $this->mOldRev
= false;
864 if( $this->mOldid
) {
865 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
866 } elseif ( $this->mOldid
=== 0 ) {
867 $rev = $this->mNewRev
->getPrevious();
869 $this->mOldid
= $rev->getId();
870 $this->mOldRev
= $rev;
872 // No previous revision; mark to show as first-version only.
873 $this->mOldid
= false;
874 $this->mOldRev
= false;
876 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
878 if( is_null( $this->mOldRev
) ) {
882 if ( $this->mOldRev
) {
883 $this->mOldPage
= $this->mOldRev
->getTitle();
885 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
886 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
887 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
888 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
890 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
891 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
892 // Add an "undo" link
893 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
894 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
895 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
896 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
897 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
900 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
901 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
902 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
903 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
911 * Load the text of the revisions, as well as revision data.
913 function loadText() {
914 if ( $this->mTextLoaded
== 2 ) {
917 // Whether it succeeds or fails, we don't want to try again
918 $this->mTextLoaded
= 2;
921 if ( !$this->loadRevisionData() ) {
924 if ( $this->mOldRev
) {
925 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
926 if ( $this->mOldtext
=== false ) {
930 if ( $this->mNewRev
) {
931 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
932 if ( $this->mNewtext
=== false ) {
940 * Load the text of the new revision, not the old one
942 function loadNewText() {
943 if ( $this->mTextLoaded
>= 1 ) {
946 $this->mTextLoaded
= 1;
948 if ( !$this->loadRevisionData() ) {
951 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
958 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
960 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
961 // You may copy this code freely under the conditions of the GPL.
964 define('USE_ASSERTS', function_exists('assert'));
969 * @ingroup DifferenceEngine
977 trigger_error('pure virtual', E_USER_ERROR
);
981 return $this->orig ?
sizeof($this->orig
) : 0;
984 function nclosing() {
985 return $this->closing ?
sizeof($this->closing
) : 0;
992 * @ingroup DifferenceEngine
994 class _DiffOp_Copy
extends _DiffOp
{
997 function _DiffOp_Copy ($orig, $closing = false) {
998 if (!is_array($closing))
1000 $this->orig
= $orig;
1001 $this->closing
= $closing;
1004 function reverse() {
1005 return new _DiffOp_Copy($this->closing
, $this->orig
);
1012 * @ingroup DifferenceEngine
1014 class _DiffOp_Delete
extends _DiffOp
{
1015 var $type = 'delete';
1017 function _DiffOp_Delete ($lines) {
1018 $this->orig
= $lines;
1019 $this->closing
= false;
1022 function reverse() {
1023 return new _DiffOp_Add($this->orig
);
1030 * @ingroup DifferenceEngine
1032 class _DiffOp_Add
extends _DiffOp
{
1035 function _DiffOp_Add ($lines) {
1036 $this->closing
= $lines;
1037 $this->orig
= false;
1040 function reverse() {
1041 return new _DiffOp_Delete($this->closing
);
1048 * @ingroup DifferenceEngine
1050 class _DiffOp_Change
extends _DiffOp
{
1051 var $type = 'change';
1053 function _DiffOp_Change ($orig, $closing) {
1054 $this->orig
= $orig;
1055 $this->closing
= $closing;
1058 function reverse() {
1059 return new _DiffOp_Change($this->closing
, $this->orig
);
1064 * Class used internally by Diff to actually compute the diffs.
1066 * The algorithm used here is mostly lifted from the perl module
1067 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1068 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1070 * More ideas are taken from:
1071 * http://www.ics.uci.edu/~eppstein/161/960229.html
1073 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1074 * diffutils-2.7, which can be found at:
1075 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1077 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1080 * Line length limits for robustness added by Tim Starling, 2005-08-31
1081 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1083 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1085 * @ingroup DifferenceEngine
1089 const MAX_XREF_LENGTH
= 10000;
1091 function diff ($from_lines, $to_lines){
1092 wfProfileIn( __METHOD__
);
1094 // Diff and store locally
1095 $this->diff_local($from_lines, $to_lines);
1097 // Merge edits when possible
1098 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1099 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1101 // Compute the edit operations.
1102 $n_from = sizeof($from_lines);
1103 $n_to = sizeof($to_lines);
1107 while ($xi < $n_from ||
$yi < $n_to) {
1108 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1109 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1111 // Skip matching "snake".
1113 while ( $xi < $n_from && $yi < $n_to
1114 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1115 $copy[] = $from_lines[$xi++
];
1119 $edits[] = new _DiffOp_Copy($copy);
1121 // Find deletes & adds.
1123 while ($xi < $n_from && $this->xchanged
[$xi])
1124 $delete[] = $from_lines[$xi++
];
1127 while ($yi < $n_to && $this->ychanged
[$yi])
1128 $add[] = $to_lines[$yi++
];
1130 if ($delete && $add)
1131 $edits[] = new _DiffOp_Change($delete, $add);
1133 $edits[] = new _DiffOp_Delete($delete);
1135 $edits[] = new _DiffOp_Add($add);
1137 wfProfileOut( __METHOD__
);
1141 function diff_local ($from_lines, $to_lines) {
1142 global $wgExternalDiffEngine;
1143 wfProfileIn( __METHOD__
);
1145 if($wgExternalDiffEngine == 'wikidiff3'){
1147 $wikidiff3 = new WikiDiff3();
1148 $wikidiff3->diff($from_lines, $to_lines);
1149 $this->xchanged
= $wikidiff3->removed
;
1150 $this->ychanged
= $wikidiff3->added
;
1154 $n_from = sizeof($from_lines);
1155 $n_to = sizeof($to_lines);
1156 $this->xchanged
= $this->ychanged
= array();
1157 $this->xv
= $this->yv
= array();
1158 $this->xind
= $this->yind
= array();
1160 unset($this->in_seq
);
1163 // Skip leading common lines.
1164 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1165 if ($from_lines[$skip] !== $to_lines[$skip])
1167 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1169 // Skip trailing common lines.
1170 $xi = $n_from; $yi = $n_to;
1171 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1172 if ($from_lines[$xi] !== $to_lines[$yi])
1174 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1177 // Ignore lines which do not exist in both files.
1178 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1179 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1182 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1183 $line = $to_lines[$yi];
1184 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1186 $yhash[$this->_line_hash($line)] = 1;
1187 $this->yv
[] = $line;
1188 $this->yind
[] = $yi;
1190 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1191 $line = $from_lines[$xi];
1192 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1194 $this->xv
[] = $line;
1195 $this->xind
[] = $xi;
1199 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1201 wfProfileOut( __METHOD__
);
1205 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1207 function _line_hash( $line ) {
1208 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1209 return md5( $line );
1215 /* Divide the Largest Common Subsequence (LCS) of the sequences
1216 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1219 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1220 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1221 * sub sequences. The first sub-sequence is contained in [X0, X1),
1222 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1223 * that (X0, Y0) == (XOFF, YOFF) and
1224 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1226 * This function assumes that the first lines of the specified portions
1227 * of the two files do not match, and likewise that the last lines do not
1228 * match. The caller must trim matching lines from the beginning and end
1229 * of the portions it is going to specify.
1231 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1234 if ($xlim - $xoff > $ylim - $yoff) {
1235 // Things seems faster (I'm not sure I understand why)
1236 // when the shortest sequence in X.
1238 list ($xoff, $xlim, $yoff, $ylim)
1239 = array( $yoff, $ylim, $xoff, $xlim);
1243 for ($i = $ylim - 1; $i >= $yoff; $i--)
1244 $ymatches[$this->xv
[$i]][] = $i;
1246 for ($i = $ylim - 1; $i >= $yoff; $i--)
1247 $ymatches[$this->yv
[$i]][] = $i;
1250 $this->seq
[0]= $yoff - 1;
1251 $this->in_seq
= array();
1252 $ymids[0] = array();
1254 $numer = $xlim - $xoff +
$nchunks - 1;
1256 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1258 for ($i = 0; $i <= $this->lcs
; $i++
)
1259 $ymids[$i][$chunk-1] = $this->seq
[$i];
1261 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1262 for ( ; $x < $x1; $x++
) {
1263 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1264 if (empty($ymatches[$line]))
1266 $matches = $ymatches[$line];
1268 while (list ($junk, $y) = each($matches))
1269 if (empty($this->in_seq
[$y])) {
1270 $k = $this->_lcs_pos($y);
1271 USE_ASSERTS
&& assert($k > 0);
1272 $ymids[$k] = $ymids[$k-1];
1275 while (list ( /* $junk */, $y) = each($matches)) {
1276 if ($y > $this->seq
[$k-1]) {
1277 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1278 // Optimization: this is a common case:
1279 // next match is just replacing previous match.
1280 $this->in_seq
[$this->seq
[$k]] = false;
1281 $this->seq
[$k] = $y;
1282 $this->in_seq
[$y] = 1;
1283 } else if (empty($this->in_seq
[$y])) {
1284 $k = $this->_lcs_pos($y);
1285 USE_ASSERTS
&& assert($k > 0);
1286 $ymids[$k] = $ymids[$k-1];
1292 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1293 $ymid = $ymids[$this->lcs
];
1294 for ($n = 0; $n < $nchunks - 1; $n++
) {
1295 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1296 $y1 = $ymid[$n] +
1;
1297 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1299 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1301 return array($this->lcs
, $seps);
1304 function _lcs_pos ($ypos) {
1306 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1307 $this->seq
[++
$this->lcs
] = $ypos;
1308 $this->in_seq
[$ypos] = 1;
1313 while ($beg < $end) {
1314 $mid = (int)(($beg +
$end) / 2);
1315 if ( $ypos > $this->seq
[$mid] )
1321 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1323 $this->in_seq
[$this->seq
[$end]] = false;
1324 $this->seq
[$end] = $ypos;
1325 $this->in_seq
[$ypos] = 1;
1329 /* Find LCS of two sequences.
1331 * The results are recorded in the vectors $this->{x,y}changed[], by
1332 * storing a 1 in the element for each line that is an insertion
1333 * or deletion (ie. is not in the LCS).
1335 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1337 * Note that XLIM, YLIM are exclusive bounds.
1338 * All line numbers are origin-0 and discarded lines are not counted.
1340 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1341 // Slide down the bottom initial diagonal.
1342 while ($xoff < $xlim && $yoff < $ylim
1343 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1348 // Slide up the top initial diagonal.
1349 while ($xlim > $xoff && $ylim > $yoff
1350 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1355 if ($xoff == $xlim ||
$yoff == $ylim)
1358 // This is ad hoc but seems to work well.
1359 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1360 //$nchunks = max(2,min(8,(int)$nchunks));
1361 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1363 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1367 // X and Y sequences have no common subsequence:
1368 // mark all changed.
1369 while ($yoff < $ylim)
1370 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1371 while ($xoff < $xlim)
1372 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1374 // Use the partitions to split this problem into subproblems.
1377 while ($pt2 = next($seps)) {
1378 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1384 /* Adjust inserts/deletes of identical lines to join changes
1385 * as much as possible.
1387 * We do something when a run of changed lines include a
1388 * line at one end and has an excluded, identical line at the other.
1389 * We are free to choose which identical line is included.
1390 * `compareseq' usually chooses the one at the beginning,
1391 * but usually it is cleaner to consider the following identical line
1392 * to be the "change".
1394 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1396 function _shift_boundaries ($lines, &$changed, $other_changed) {
1397 wfProfileIn( __METHOD__
);
1401 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1402 $len = sizeof($lines);
1403 $other_len = sizeof($other_changed);
1407 * Scan forwards to find beginning of another run of changes.
1408 * Also keep track of the corresponding point in the other file.
1410 * Throughout this code, $i and $j are adjusted together so that
1411 * the first $i elements of $changed and the first $j elements
1412 * of $other_changed both contain the same number of zeros
1413 * (unchanged lines).
1414 * Furthermore, $j is always kept so that $j == $other_len or
1415 * $other_changed[$j] == false.
1417 while ($j < $other_len && $other_changed[$j])
1420 while ($i < $len && ! $changed[$i]) {
1421 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1423 while ($j < $other_len && $other_changed[$j])
1432 // Find the end of this run of changes.
1433 while (++
$i < $len && $changed[$i])
1438 * Record the length of this run of changes, so that
1439 * we can later determine whether the run has grown.
1441 $runlength = $i - $start;
1444 * Move the changed region back, so long as the
1445 * previous unchanged line matches the last changed one.
1446 * This merges with previous changed regions.
1448 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1449 $changed[--$start] = 1;
1450 $changed[--$i] = false;
1451 while ($start > 0 && $changed[$start - 1])
1453 USE_ASSERTS
&& assert('$j > 0');
1454 while ($other_changed[--$j])
1456 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1460 * Set CORRESPONDING to the end of the changed run, at the last
1461 * point where it corresponds to a changed run in the other file.
1462 * CORRESPONDING == LEN means no such point has been found.
1464 $corresponding = $j < $other_len ?
$i : $len;
1467 * Move the changed region forward, so long as the
1468 * first changed line matches the following unchanged one.
1469 * This merges with following changed regions.
1470 * Do this second, so that if there are no merges,
1471 * the changed region is moved forward as far as possible.
1473 while ($i < $len && $lines[$start] == $lines[$i]) {
1474 $changed[$start++
] = false;
1476 while ($i < $len && $changed[$i])
1479 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1481 if ($j < $other_len && $other_changed[$j]) {
1482 $corresponding = $i;
1483 while ($j < $other_len && $other_changed[$j])
1487 } while ($runlength != $i - $start);
1490 * If possible, move the fully-merged run of changes
1491 * back to a corresponding run in the other file.
1493 while ($corresponding < $i) {
1494 $changed[--$start] = 1;
1496 USE_ASSERTS
&& assert('$j > 0');
1497 while ($other_changed[--$j])
1499 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1502 wfProfileOut( __METHOD__
);
1507 * Class representing a 'diff' between two sequences of strings.
1510 * @ingroup DifferenceEngine
1518 * Computes diff between sequences of strings.
1520 * @param $from_lines array An array of strings.
1521 * (Typically these are lines from a file.)
1522 * @param $to_lines array An array of strings.
1524 function Diff($from_lines, $to_lines) {
1525 $eng = new _DiffEngine
;
1526 $this->edits
= $eng->diff($from_lines, $to_lines);
1527 //$this->_check($from_lines, $to_lines);
1531 * Compute reversed Diff.
1535 * $diff = new Diff($lines1, $lines2);
1536 * $rev = $diff->reverse();
1537 * @return object A Diff object representing the inverse of the
1540 function reverse () {
1542 $rev->edits
= array();
1543 foreach ($this->edits
as $edit) {
1544 $rev->edits
[] = $edit->reverse();
1550 * Check for empty diff.
1552 * @return bool True iff two sequences were identical.
1554 function isEmpty () {
1555 foreach ($this->edits
as $edit) {
1556 if ($edit->type
!= 'copy')
1563 * Compute the length of the Longest Common Subsequence (LCS).
1565 * This is mostly for diagnostic purposed.
1567 * @return int The length of the LCS.
1571 foreach ($this->edits
as $edit) {
1572 if ($edit->type
== 'copy')
1573 $lcs +
= sizeof($edit->orig
);
1579 * Get the original set of lines.
1581 * This reconstructs the $from_lines parameter passed to the
1584 * @return array The original sequence of strings.
1589 foreach ($this->edits
as $edit) {
1591 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1597 * Get the closing set of lines.
1599 * This reconstructs the $to_lines parameter passed to the
1602 * @return array The sequence of strings.
1604 function closing() {
1607 foreach ($this->edits
as $edit) {
1609 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1615 * Check a Diff for validity.
1617 * This is here only for debugging purposes.
1619 function _check ($from_lines, $to_lines) {
1620 wfProfileIn( __METHOD__
);
1621 if (serialize($from_lines) != serialize($this->orig()))
1622 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1623 if (serialize($to_lines) != serialize($this->closing()))
1624 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1626 $rev = $this->reverse();
1627 if (serialize($to_lines) != serialize($rev->orig()))
1628 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1629 if (serialize($from_lines) != serialize($rev->closing()))
1630 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1634 foreach ($this->edits
as $edit) {
1635 if ( $prevtype == $edit->type
)
1636 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1637 $prevtype = $edit->type
;
1640 $lcs = $this->lcs();
1641 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1642 wfProfileOut( __METHOD__
);
1647 * @todo document, bad name.
1649 * @ingroup DifferenceEngine
1651 class MappedDiff
extends Diff
1656 * Computes diff between sequences of strings.
1658 * This can be used to compute things like
1659 * case-insensitve diffs, or diffs which ignore
1660 * changes in white-space.
1662 * @param $from_lines array An array of strings.
1663 * (Typically these are lines from a file.)
1665 * @param $to_lines array An array of strings.
1667 * @param $mapped_from_lines array This array should
1668 * have the same size number of elements as $from_lines.
1669 * The elements in $mapped_from_lines and
1670 * $mapped_to_lines are what is actually compared
1671 * when computing the diff.
1673 * @param $mapped_to_lines array This array should
1674 * have the same number of elements as $to_lines.
1676 function MappedDiff($from_lines, $to_lines,
1677 $mapped_from_lines, $mapped_to_lines) {
1678 wfProfileIn( __METHOD__
);
1680 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1681 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1683 $this->Diff($mapped_from_lines, $mapped_to_lines);
1686 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1687 $orig = &$this->edits
[$i]->orig
;
1688 if (is_array($orig)) {
1689 $orig = array_slice($from_lines, $xi, sizeof($orig));
1690 $xi +
= sizeof($orig);
1693 $closing = &$this->edits
[$i]->closing
;
1694 if (is_array($closing)) {
1695 $closing = array_slice($to_lines, $yi, sizeof($closing));
1696 $yi +
= sizeof($closing);
1699 wfProfileOut( __METHOD__
);
1704 * A class to format Diffs
1706 * This class formats the diff in classic diff format.
1707 * It is intended that this class be customized via inheritance,
1708 * to obtain fancier outputs.
1711 * @ingroup DifferenceEngine
1713 class DiffFormatter
{
1715 * Number of leading context "lines" to preserve.
1717 * This should be left at zero for this class, but subclasses
1718 * may want to set this to other values.
1720 var $leading_context_lines = 0;
1723 * Number of trailing context "lines" to preserve.
1725 * This should be left at zero for this class, but subclasses
1726 * may want to set this to other values.
1728 var $trailing_context_lines = 0;
1733 * @param $diff object A Diff object.
1734 * @return string The formatted output.
1736 function format($diff) {
1737 wfProfileIn( __METHOD__
);
1743 $nlead = $this->leading_context_lines
;
1744 $ntrail = $this->trailing_context_lines
;
1746 $this->_start_diff();
1748 foreach ($diff->edits
as $edit) {
1749 if ($edit->type
== 'copy') {
1750 if (is_array($block)) {
1751 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1756 $context = array_slice($edit->orig
, 0, $ntrail);
1757 $block[] = new _DiffOp_Copy($context);
1759 $this->_block($x0, $ntrail +
$xi - $x0,
1760 $y0, $ntrail +
$yi - $y0,
1765 $context = $edit->orig
;
1768 if (! is_array($block)) {
1769 $context = array_slice($context, sizeof($context) - $nlead);
1770 $x0 = $xi - sizeof($context);
1771 $y0 = $yi - sizeof($context);
1774 $block[] = new _DiffOp_Copy($context);
1780 $xi +
= sizeof($edit->orig
);
1782 $yi +
= sizeof($edit->closing
);
1785 if (is_array($block))
1786 $this->_block($x0, $xi - $x0,
1790 $end = $this->_end_diff();
1791 wfProfileOut( __METHOD__
);
1795 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1796 wfProfileIn( __METHOD__
);
1797 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1798 foreach ($edits as $edit) {
1799 if ($edit->type
== 'copy')
1800 $this->_context($edit->orig
);
1801 elseif ($edit->type
== 'add')
1802 $this->_added($edit->closing
);
1803 elseif ($edit->type
== 'delete')
1804 $this->_deleted($edit->orig
);
1805 elseif ($edit->type
== 'change')
1806 $this->_changed($edit->orig
, $edit->closing
);
1808 trigger_error('Unknown edit type', E_USER_ERROR
);
1810 $this->_end_block();
1811 wfProfileOut( __METHOD__
);
1814 function _start_diff() {
1818 function _end_diff() {
1819 $val = ob_get_contents();
1824 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1826 $xbeg .= "," . ($xbeg +
$xlen - 1);
1828 $ybeg .= "," . ($ybeg +
$ylen - 1);
1830 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1833 function _start_block($header) {
1834 echo $header . "\n";
1837 function _end_block() {
1840 function _lines($lines, $prefix = ' ') {
1841 foreach ($lines as $line)
1842 echo "$prefix $line\n";
1845 function _context($lines) {
1846 $this->_lines($lines);
1849 function _added($lines) {
1850 $this->_lines($lines, '>');
1852 function _deleted($lines) {
1853 $this->_lines($lines, '<');
1856 function _changed($orig, $closing) {
1857 $this->_deleted($orig);
1859 $this->_added($closing);
1864 * A formatter that outputs unified diffs
1865 * @ingroup DifferenceEngine
1868 class UnifiedDiffFormatter
extends DiffFormatter
{
1869 var $leading_context_lines = 2;
1870 var $trailing_context_lines = 2;
1872 function _added($lines) {
1873 $this->_lines($lines, '+');
1875 function _deleted($lines) {
1876 $this->_lines($lines, '-');
1878 function _changed($orig, $closing) {
1879 $this->_deleted($orig);
1880 $this->_added($closing);
1882 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1883 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1888 * A pseudo-formatter that just passes along the Diff::$edits array
1889 * @ingroup DifferenceEngine
1891 class ArrayDiffFormatter
extends DiffFormatter
{
1892 function format($diff) {
1896 foreach($diff->edits
as $edit)
1897 switch($edit->type
) {
1899 foreach($edit->closing
as $l) {
1903 'newline' => $newline++
1908 foreach($edit->orig
as $l) {
1910 'action' => 'delete',
1912 'oldline' => $oldline++
,
1917 foreach($edit->orig
as $i => $l) {
1919 'action' => 'change',
1921 'new' => @$edit->closing
[$i],
1922 'oldline' => $oldline++
,
1923 'newline' => $newline++
,
1928 $oldline +
= count($edit->orig
);
1929 $newline +
= count($edit->orig
);
1936 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1940 define('NBSP', ' '); // iso-8859-x non-breaking space.
1945 * @ingroup DifferenceEngine
1947 class _HWLDF_WordAccumulator
{
1948 function _HWLDF_WordAccumulator () {
1949 $this->_lines
= array();
1955 function _flushGroup ($new_tag) {
1956 if ($this->_group
!== '') {
1957 if ($this->_tag
== 'ins')
1958 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1959 htmlspecialchars ( $this->_group
) . '</ins>';
1960 elseif ($this->_tag
== 'del')
1961 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1962 htmlspecialchars ( $this->_group
) . '</del>';
1964 $this->_line
.= htmlspecialchars ( $this->_group
);
1967 $this->_tag
= $new_tag;
1970 function _flushLine ($new_tag) {
1971 $this->_flushGroup($new_tag);
1972 if ($this->_line
!= '')
1973 array_push ( $this->_lines
, $this->_line
);
1975 # make empty lines visible by inserting an NBSP
1976 array_push ( $this->_lines
, NBSP
);
1980 function addWords ($words, $tag = '') {
1981 if ($tag != $this->_tag
)
1982 $this->_flushGroup($tag);
1984 foreach ($words as $word) {
1985 // new-line should only come as first char of word.
1988 if ($word[0] == "\n") {
1989 $this->_flushLine($tag);
1990 $word = substr($word, 1);
1992 assert(!strstr($word, "\n"));
1993 $this->_group
.= $word;
1997 function getLines() {
1998 $this->_flushLine('~done');
1999 return $this->_lines
;
2006 * @ingroup DifferenceEngine
2008 class WordLevelDiff
extends MappedDiff
{
2009 const MAX_LINE_LENGTH
= 10000;
2011 function WordLevelDiff ($orig_lines, $closing_lines) {
2012 wfProfileIn( __METHOD__
);
2014 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
2015 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
2017 $this->MappedDiff($orig_words, $closing_words,
2018 $orig_stripped, $closing_stripped);
2019 wfProfileOut( __METHOD__
);
2022 function _split($lines) {
2023 wfProfileIn( __METHOD__
);
2026 $stripped = array();
2028 foreach ( $lines as $line ) {
2029 # If the line is too long, just pretend the entire line is one big word
2030 # This prevents resource exhaustion problems
2037 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2039 $stripped[] = $line;
2042 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2045 $words = array_merge( $words, $m[0] );
2046 $stripped = array_merge( $stripped, $m[1] );
2050 wfProfileOut( __METHOD__
);
2051 return array($words, $stripped);
2055 wfProfileIn( __METHOD__
);
2056 $orig = new _HWLDF_WordAccumulator
;
2058 foreach ($this->edits
as $edit) {
2059 if ($edit->type
== 'copy')
2060 $orig->addWords($edit->orig
);
2061 elseif ($edit->orig
)
2062 $orig->addWords($edit->orig
, 'del');
2064 $lines = $orig->getLines();
2065 wfProfileOut( __METHOD__
);
2069 function closing () {
2070 wfProfileIn( __METHOD__
);
2071 $closing = new _HWLDF_WordAccumulator
;
2073 foreach ($this->edits
as $edit) {
2074 if ($edit->type
== 'copy')
2075 $closing->addWords($edit->closing
);
2076 elseif ($edit->closing
)
2077 $closing->addWords($edit->closing
, 'ins');
2079 $lines = $closing->getLines();
2080 wfProfileOut( __METHOD__
);
2086 * Wikipedia Table style diff formatter.
2089 * @ingroup DifferenceEngine
2091 class TableDiffFormatter
extends DiffFormatter
{
2092 function TableDiffFormatter() {
2093 $this->leading_context_lines
= 2;
2094 $this->trailing_context_lines
= 2;
2097 public static function escapeWhiteSpace( $msg ) {
2098 $msg = preg_replace( '/^ /m', ' ', $msg );
2099 $msg = preg_replace( '/ $/m', ' ', $msg );
2100 $msg = preg_replace( '/ /', ' ', $msg );
2104 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2105 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2106 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2110 function _start_block( $header ) {
2114 function _end_block() {
2117 function _lines( $lines, $prefix=' ', $color='white' ) {
2120 # HTML-escape parameter before calling this
2121 function addedLine( $line ) {
2122 return $this->wrapLine( '+', 'diff-addedline', $line );
2125 # HTML-escape parameter before calling this
2126 function deletedLine( $line ) {
2127 return $this->wrapLine( '-', 'diff-deletedline', $line );
2130 # HTML-escape parameter before calling this
2131 function contextLine( $line ) {
2132 return $this->wrapLine( ' ', 'diff-context', $line );
2135 private function wrapLine( $marker, $class, $line ) {
2136 if( $line !== '' ) {
2137 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2138 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2140 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2143 function emptyLine() {
2144 return '<td colspan="2"> </td>';
2147 function _added( $lines ) {
2148 foreach ($lines as $line) {
2149 echo '<tr>' . $this->emptyLine() .
2150 $this->addedLine( '<ins class="diffchange">' .
2151 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2155 function _deleted($lines) {
2156 foreach ($lines as $line) {
2157 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2158 htmlspecialchars ( $line ) . '</del>' ) .
2159 $this->emptyLine() . "</tr>\n";
2163 function _context( $lines ) {
2164 foreach ($lines as $line) {
2166 $this->contextLine( htmlspecialchars ( $line ) ) .
2167 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2171 function _changed( $orig, $closing ) {
2172 wfProfileIn( __METHOD__
);
2174 $diff = new WordLevelDiff( $orig, $closing );
2175 $del = $diff->orig();
2176 $add = $diff->closing();
2178 # Notice that WordLevelDiff returns HTML-escaped output.
2179 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2181 while ( $line = array_shift( $del ) ) {
2182 $aline = array_shift( $add );
2183 echo '<tr>' . $this->deletedLine( $line ) .
2184 $this->addedLine( $aline ) . "</tr>\n";
2186 foreach ($add as $line) { # If any leftovers
2187 echo '<tr>' . $this->emptyLine() .
2188 $this->addedLine( $line ) . "</tr>\n";
2190 wfProfileOut( __METHOD__
);