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' ).')' );
259 'type' => 'revision',
260 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
261 'ids' => $this->mOldRev
->getId()
263 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
265 $ldel = " $ldel ";
266 // We don't currently handle well changing the top revision's settings
267 if( $this->mNewRev
->isCurrent() ) {
268 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
269 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
270 // If revision was hidden from sysops
271 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
274 'type' => 'revision',
275 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
276 'ids' => $this->mNewRev
->getId()
278 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
280 $rdel = " $rdel ";
283 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
284 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
285 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
286 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
287 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
288 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
289 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
290 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
292 # Check if this user can see the revisions
293 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
)
294 && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
295 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
)
296 ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
297 # Output the diff if allowed...
298 if( $deleted && (!$this->unhide ||
!$allowed) ) {
299 $this->showDiffStyle();
300 $multi = $this->getMultiNotice();
301 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
303 # Give explanation for why revision is not visible
304 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
305 array( 'rev-deleted-no-diff' ) );
307 # Give explanation and add a link to view the diff...
308 $link = $this->mTitle
->getFullUrl( "diff={$this->mNewid}&oldid={$this->mOldid}&unhide=1" );
309 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
310 array( 'rev-deleted-unhide-diff', $link ) );
312 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
313 $multi = $this->getMultiNotice();
314 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
315 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
316 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
317 $this->renderHtmlDiff();
319 if( $wgEnableHtmlDiff ) {
320 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
321 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
323 $this->showDiff( $oldHeader, $newHeader );
325 $this->renderNewRevision();
328 wfProfileOut( __METHOD__
);
332 * Show the new revision of the page.
334 function renderNewRevision() {
335 global $wgOut, $wgUser;
336 wfProfileIn( __METHOD__
);
338 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
339 # Add deleted rev tag if needed
340 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
341 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
342 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
343 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
346 if( !$this->mNewRev
->isCurrent() ) {
347 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
350 $this->loadNewText();
351 if( is_object( $this->mNewRev
) ) {
352 $wgOut->setRevisionId( $this->mNewRev
->getId() );
355 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
356 // Stolen from Article::view --AG 2007-10-11
357 // Give hooks a chance to customise the output
358 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
359 // Wrap the whole lot in a <pre> and don't parse
361 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
362 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
363 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
364 $wgOut->addHTML( "\n</pre>\n" );
367 $wgOut->addWikiTextTidy( $this->mNewtext
);
370 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
371 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
373 # Add redundant patrol link on bottom...
374 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
375 $sk = $wgUser->getSkin();
377 "<div class='patrollink'>[" . $sk->makeKnownLinkObj( $this->mTitle
,
378 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) .
383 wfProfileOut( __METHOD__
);
387 function renderHtmlDiff() {
388 global $wgOut, $wgParser, $wgDebugComments;
389 wfProfileIn( __METHOD__
);
391 $this->showDiffStyle();
393 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
394 #add deleted rev tag if needed
395 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
396 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
397 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
398 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
401 if( !$this->mNewRev
->isCurrent() ) {
402 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
408 if( is_object( $this->mOldRev
) ) {
409 $wgOut->setRevisionId( $this->mOldRev
->getId() );
412 $popts = $wgOut->parserOptions();
413 $oldTidy = $popts->setTidy( true );
414 $popts->setEditSection( false );
416 $parserOutput = $wgParser->parse( $this->mOldtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
417 $popts->setTidy( $oldTidy );
420 //$wgOut->addParserOutputNoText( $parserOutput );
421 $oldHtml = $parserOutput->getText();
422 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
425 if( is_object( $this->mNewRev
) ) {
426 $wgOut->setRevisionId( $this->mNewRev
->getId() );
429 $popts = $wgOut->parserOptions();
430 $oldTidy = $popts->setTidy( true );
432 $parserOutput = $wgParser->parse( $this->mNewtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
433 $popts->setTidy( $oldTidy );
435 $wgOut->addParserOutputNoText( $parserOutput );
436 $newHtml = $parserOutput->getText();
437 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
439 unset($parserOutput, $popts);
441 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
442 $differ->htmlDiff($oldHtml, $newHtml);
443 if ( $wgDebugComments ) {
444 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
447 wfProfileOut( __METHOD__
);
451 * Show the first revision of an article. Uses normal diff headers in
452 * contrast to normal "old revision" display style.
454 function showFirstRevision() {
455 global $wgOut, $wgUser;
456 wfProfileIn( __METHOD__
);
458 # Get article text from the DB
460 if ( ! $this->loadNewText() ) {
461 $t = $this->mTitle
->getPrefixedText();
462 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
463 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
464 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
465 wfProfileOut( __METHOD__
);
468 if ( $this->mNewRev
->isCurrent() ) {
469 $wgOut->setArticleFlag( true );
472 # Check if user is allowed to look at this page. If not, bail out.
474 if ( !$this->mTitle
->userCanRead() ) {
475 $wgOut->loginToUse();
477 wfProfileOut( __METHOD__
);
478 throw new MWException("Permission Error: you do not have access to view this page");
481 # Prepare the header box
483 $sk = $wgUser->getSkin();
485 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
489 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
490 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
492 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
493 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
495 $wgOut->addHTML( $header );
497 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
498 $wgOut->setRobotPolicy( 'noindex,nofollow' );
500 wfProfileOut( __METHOD__
);
503 function htmlDiffArgument(){
504 global $wgEnableHtmlDiff;
505 if($wgEnableHtmlDiff){
507 return '&htmldiff=1';
509 return '&htmldiff=0';
517 * Get the diff text, send it to $wgOut
518 * Returns false if the diff could not be generated, otherwise returns true
520 function showDiff( $otitle, $ntitle ) {
522 $diff = $this->getDiff( $otitle, $ntitle );
523 if ( $diff === false ) {
524 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
527 $this->showDiffStyle();
528 $wgOut->addHTML( $diff );
534 * Add style sheets and supporting JS for diff display.
536 function showDiffStyle() {
537 global $wgStylePath, $wgStyleVersion, $wgOut;
538 $wgOut->addStyle( 'common/diff.css' );
540 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
541 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
545 * Get complete diff table, including header
547 * @param Title $otitle Old title
548 * @param Title $ntitle New title
551 function getDiff( $otitle, $ntitle ) {
552 $body = $this->getDiffBody();
553 if ( $body === false ) {
556 $multi = $this->getMultiNotice();
557 return $this->addHeader( $body, $otitle, $ntitle, $multi );
562 * Get the diff table body, without header
566 function getDiffBody() {
568 wfProfileIn( __METHOD__
);
569 $this->mCacheHit
= true;
570 // Check if the diff should be hidden from this user
571 if ( !$this->loadRevisionData() )
573 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
575 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
577 } else if ( $this->mOldRev
&& $this->mNewRev
&& $this->mOldRev
->getID() == $this->mNewRev
->getID() ) {
582 if ( $this->mOldid
&& $this->mNewid
) {
583 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
585 if ( !$this->mRefreshCache
) {
586 $difftext = $wgMemc->get( $key );
588 wfIncrStats( 'diff_cache_hit' );
589 $difftext = $this->localiseLineNumbers( $difftext );
590 $difftext .= "\n<!-- diff cache key $key -->\n";
591 wfProfileOut( __METHOD__
);
594 } // don't try to load but save the result
596 $this->mCacheHit
= false;
598 // Loadtext is permission safe, this just clears out the diff
599 if ( !$this->loadText() ) {
600 wfProfileOut( __METHOD__
);
604 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
606 // Save to cache for 7 days
607 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
608 wfIncrStats( 'diff_uncacheable' );
609 } else if ( $key !== false && $difftext !== false ) {
610 wfIncrStats( 'diff_cache_miss' );
611 $wgMemc->set( $key, $difftext, 7*86400 );
613 wfIncrStats( 'diff_uncacheable' );
615 // Replace line numbers with the text in the user's language
616 if ( $difftext !== false ) {
617 $difftext = $this->localiseLineNumbers( $difftext );
619 wfProfileOut( __METHOD__
);
624 * Make sure the proper modules are loaded before we try to
627 private function initDiffEngines() {
628 global $wgExternalDiffEngine;
629 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
630 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
631 wfSuppressWarnings();
632 dl( 'php_wikidiff.so' );
634 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
636 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
637 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
638 wfSuppressWarnings();
639 dl( 'php_wikidiff2.so' );
641 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
646 * Generate a diff, no caching
647 * $otext and $ntext must be already segmented
649 function generateDiffBody( $otext, $ntext ) {
650 global $wgExternalDiffEngine, $wgContLang;
652 $otext = str_replace( "\r\n", "\n", $otext );
653 $ntext = str_replace( "\r\n", "\n", $ntext );
655 $this->initDiffEngines();
657 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
658 # For historical reasons, external diff engine expects
659 # input text to be HTML-escaped already
660 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
661 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
662 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
663 $this->debug( 'wikidiff1' );
666 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
667 # Better external diff engine, the 2 may some day be dropped
668 # This one does the escaping and segmenting itself
669 wfProfileIn( 'wikidiff2_do_diff' );
670 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
671 $text .= $this->debug( 'wikidiff2' );
672 wfProfileOut( 'wikidiff2_do_diff' );
675 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
677 global $wgTmpDirectory;
678 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
679 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
681 $tempFile1 = fopen( $tempName1, "w" );
683 wfProfileOut( __METHOD__
);
686 $tempFile2 = fopen( $tempName2, "w" );
688 wfProfileOut( __METHOD__
);
691 fwrite( $tempFile1, $otext );
692 fwrite( $tempFile2, $ntext );
693 fclose( $tempFile1 );
694 fclose( $tempFile2 );
695 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
696 wfProfileIn( __METHOD__
. "-shellexec" );
697 $difftext = wfShellExec( $cmd );
698 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
699 wfProfileOut( __METHOD__
. "-shellexec" );
700 unlink( $tempName1 );
701 unlink( $tempName2 );
706 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
707 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
708 $diffs = new Diff( $ota, $nta );
709 $formatter = new TableDiffFormatter();
710 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
715 * Generate a debug comment indicating diff generating time,
716 * server node, and generator backend.
718 protected function debug( $generator="internal" ) {
719 global $wgShowHostnames;
720 $data = array( $generator );
721 if( $wgShowHostnames ) {
722 $data[] = wfHostname();
724 $data[] = wfTimestamp( TS_DB
);
725 return "<!-- diff generator: " .
734 * Replace line numbers with the text in the user's language
736 function localiseLineNumbers( $text ) {
737 return preg_replace_callback( '/<!--LINE (\d+)-->/',
738 array( &$this, 'localiseLineNumbersCb' ), $text );
741 function localiseLineNumbersCb( $matches ) {
743 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
748 * If there are revisions between the ones being compared, return a note saying so.
750 function getMultiNotice() {
751 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
754 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
755 // Comparing two different pages? Count would be meaningless.
759 $oldid = $this->mOldRev
->getId();
760 $newid = $this->mNewRev
->getId();
761 if ( $oldid > $newid ) {
762 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
765 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
769 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
774 * Add the header to a diff body
776 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
778 $header = "<table class='diff'>";
779 if( $diff ) { // Safari/Chrome show broken output if cols not used
781 <col class='diff-marker' />
782 <col class='diff-content' />
783 <col class='diff-marker' />
784 <col class='diff-content' />";
789 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
790 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
794 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
796 return $header . $diff . "</table>";
800 * Use specified text instead of loading from the database
802 function setText( $oldText, $newText ) {
803 $this->mOldtext
= $oldText;
804 $this->mNewtext
= $newText;
805 $this->mTextLoaded
= 2;
806 $this->mRevisionsLoaded
= true;
810 * Load revision metadata for the specified articles. If newid is 0, then compare
811 * the old article in oldid to the current article; if oldid is 0, then
812 * compare the current article to the immediately previous one (ignoring the
815 * If oldid is false, leave the corresponding revision object set
816 * to false. This is impossible via ordinary user input, and is provided for
819 function loadRevisionData() {
820 global $wgLang, $wgUser;
821 if ( $this->mRevisionsLoaded
) {
824 // Whether it succeeds or fails, we don't want to try again
825 $this->mRevisionsLoaded
= true;
828 // Load the new revision object
829 $this->mNewRev
= $this->mNewid
830 ? Revision
::newFromId( $this->mNewid
)
831 : Revision
::newFromTitle( $this->mTitle
);
832 if( !$this->mNewRev
instanceof Revision
)
835 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
836 $this->mNewid
= $this->mNewRev
->getId();
838 // Check if page is editable
839 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
841 // Set assorted variables
842 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
843 $dateofrev = $wgLang->date( $this->mNewRev
->getTimestamp(), true );
844 $timeofrev = $wgLang->time( $this->mNewRev
->getTimestamp(), true );
845 $this->mNewPage
= $this->mNewRev
->getTitle();
846 if( $this->mNewRev
->isCurrent() ) {
847 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
848 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev-asof', $timestamp ) );
849 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
851 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
852 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
854 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
855 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
856 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp, $dateofrev, $timeofrev ) );
858 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
859 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
861 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
862 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
863 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
864 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
867 // Load the old revision object
868 $this->mOldRev
= false;
869 if( $this->mOldid
) {
870 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
871 } elseif ( $this->mOldid
=== 0 ) {
872 $rev = $this->mNewRev
->getPrevious();
874 $this->mOldid
= $rev->getId();
875 $this->mOldRev
= $rev;
877 // No previous revision; mark to show as first-version only.
878 $this->mOldid
= false;
879 $this->mOldRev
= false;
881 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
883 if( is_null( $this->mOldRev
) ) {
887 if ( $this->mOldRev
) {
888 $this->mOldPage
= $this->mOldRev
->getTitle();
890 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
891 $dateofrev = $wgLang->date( $this->mOldRev
->getTimestamp(), true );
892 $timeofrev = $wgLang->time( $this->mOldRev
->getTimestamp(), true );
893 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
894 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
895 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
897 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
898 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
899 // Add an "undo" link
900 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
901 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
902 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
903 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
904 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
907 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
908 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
909 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
910 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
918 * Load the text of the revisions, as well as revision data.
920 function loadText() {
921 if ( $this->mTextLoaded
== 2 ) {
924 // Whether it succeeds or fails, we don't want to try again
925 $this->mTextLoaded
= 2;
928 if ( !$this->loadRevisionData() ) {
931 if ( $this->mOldRev
) {
932 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
933 if ( $this->mOldtext
=== false ) {
937 if ( $this->mNewRev
) {
938 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
939 if ( $this->mNewtext
=== false ) {
947 * Load the text of the new revision, not the old one
949 function loadNewText() {
950 if ( $this->mTextLoaded
>= 1 ) {
953 $this->mTextLoaded
= 1;
955 if ( !$this->loadRevisionData() ) {
958 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
965 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
967 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
968 // You may copy this code freely under the conditions of the GPL.
971 define('USE_ASSERTS', function_exists('assert'));
976 * @ingroup DifferenceEngine
984 trigger_error('pure virtual', E_USER_ERROR
);
988 return $this->orig ?
sizeof($this->orig
) : 0;
991 function nclosing() {
992 return $this->closing ?
sizeof($this->closing
) : 0;
999 * @ingroup DifferenceEngine
1001 class _DiffOp_Copy
extends _DiffOp
{
1004 function _DiffOp_Copy ($orig, $closing = false) {
1005 if (!is_array($closing))
1007 $this->orig
= $orig;
1008 $this->closing
= $closing;
1011 function reverse() {
1012 return new _DiffOp_Copy($this->closing
, $this->orig
);
1019 * @ingroup DifferenceEngine
1021 class _DiffOp_Delete
extends _DiffOp
{
1022 var $type = 'delete';
1024 function _DiffOp_Delete ($lines) {
1025 $this->orig
= $lines;
1026 $this->closing
= false;
1029 function reverse() {
1030 return new _DiffOp_Add($this->orig
);
1037 * @ingroup DifferenceEngine
1039 class _DiffOp_Add
extends _DiffOp
{
1042 function _DiffOp_Add ($lines) {
1043 $this->closing
= $lines;
1044 $this->orig
= false;
1047 function reverse() {
1048 return new _DiffOp_Delete($this->closing
);
1055 * @ingroup DifferenceEngine
1057 class _DiffOp_Change
extends _DiffOp
{
1058 var $type = 'change';
1060 function _DiffOp_Change ($orig, $closing) {
1061 $this->orig
= $orig;
1062 $this->closing
= $closing;
1065 function reverse() {
1066 return new _DiffOp_Change($this->closing
, $this->orig
);
1071 * Class used internally by Diff to actually compute the diffs.
1073 * The algorithm used here is mostly lifted from the perl module
1074 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1075 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1077 * More ideas are taken from:
1078 * http://www.ics.uci.edu/~eppstein/161/960229.html
1080 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1081 * diffutils-2.7, which can be found at:
1082 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1084 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1087 * Line length limits for robustness added by Tim Starling, 2005-08-31
1088 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1090 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1092 * @ingroup DifferenceEngine
1096 const MAX_XREF_LENGTH
= 10000;
1098 function diff ($from_lines, $to_lines){
1099 wfProfileIn( __METHOD__
);
1101 // Diff and store locally
1102 $this->diff_local($from_lines, $to_lines);
1104 // Merge edits when possible
1105 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1106 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1108 // Compute the edit operations.
1109 $n_from = sizeof($from_lines);
1110 $n_to = sizeof($to_lines);
1114 while ($xi < $n_from ||
$yi < $n_to) {
1115 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1116 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1118 // Skip matching "snake".
1120 while ( $xi < $n_from && $yi < $n_to
1121 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1122 $copy[] = $from_lines[$xi++
];
1126 $edits[] = new _DiffOp_Copy($copy);
1128 // Find deletes & adds.
1130 while ($xi < $n_from && $this->xchanged
[$xi])
1131 $delete[] = $from_lines[$xi++
];
1134 while ($yi < $n_to && $this->ychanged
[$yi])
1135 $add[] = $to_lines[$yi++
];
1137 if ($delete && $add)
1138 $edits[] = new _DiffOp_Change($delete, $add);
1140 $edits[] = new _DiffOp_Delete($delete);
1142 $edits[] = new _DiffOp_Add($add);
1144 wfProfileOut( __METHOD__
);
1148 function diff_local ($from_lines, $to_lines) {
1149 global $wgExternalDiffEngine;
1150 wfProfileIn( __METHOD__
);
1152 if($wgExternalDiffEngine == 'wikidiff3'){
1154 $wikidiff3 = new WikiDiff3();
1155 $wikidiff3->diff($from_lines, $to_lines);
1156 $this->xchanged
= $wikidiff3->removed
;
1157 $this->ychanged
= $wikidiff3->added
;
1161 $n_from = sizeof($from_lines);
1162 $n_to = sizeof($to_lines);
1163 $this->xchanged
= $this->ychanged
= array();
1164 $this->xv
= $this->yv
= array();
1165 $this->xind
= $this->yind
= array();
1167 unset($this->in_seq
);
1170 // Skip leading common lines.
1171 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1172 if ($from_lines[$skip] !== $to_lines[$skip])
1174 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1176 // Skip trailing common lines.
1177 $xi = $n_from; $yi = $n_to;
1178 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1179 if ($from_lines[$xi] !== $to_lines[$yi])
1181 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1184 // Ignore lines which do not exist in both files.
1185 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1186 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1189 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1190 $line = $to_lines[$yi];
1191 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1193 $yhash[$this->_line_hash($line)] = 1;
1194 $this->yv
[] = $line;
1195 $this->yind
[] = $yi;
1197 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1198 $line = $from_lines[$xi];
1199 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1201 $this->xv
[] = $line;
1202 $this->xind
[] = $xi;
1206 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1208 wfProfileOut( __METHOD__
);
1212 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1214 function _line_hash( $line ) {
1215 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1216 return md5( $line );
1222 /* Divide the Largest Common Subsequence (LCS) of the sequences
1223 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1226 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1227 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1228 * sub sequences. The first sub-sequence is contained in [X0, X1),
1229 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1230 * that (X0, Y0) == (XOFF, YOFF) and
1231 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1233 * This function assumes that the first lines of the specified portions
1234 * of the two files do not match, and likewise that the last lines do not
1235 * match. The caller must trim matching lines from the beginning and end
1236 * of the portions it is going to specify.
1238 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1241 if ($xlim - $xoff > $ylim - $yoff) {
1242 // Things seems faster (I'm not sure I understand why)
1243 // when the shortest sequence in X.
1245 list ($xoff, $xlim, $yoff, $ylim)
1246 = array( $yoff, $ylim, $xoff, $xlim);
1250 for ($i = $ylim - 1; $i >= $yoff; $i--)
1251 $ymatches[$this->xv
[$i]][] = $i;
1253 for ($i = $ylim - 1; $i >= $yoff; $i--)
1254 $ymatches[$this->yv
[$i]][] = $i;
1257 $this->seq
[0]= $yoff - 1;
1258 $this->in_seq
= array();
1259 $ymids[0] = array();
1261 $numer = $xlim - $xoff +
$nchunks - 1;
1263 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1265 for ($i = 0; $i <= $this->lcs
; $i++
)
1266 $ymids[$i][$chunk-1] = $this->seq
[$i];
1268 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1269 for ( ; $x < $x1; $x++
) {
1270 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1271 if (empty($ymatches[$line]))
1273 $matches = $ymatches[$line];
1275 while (list ($junk, $y) = each($matches))
1276 if (empty($this->in_seq
[$y])) {
1277 $k = $this->_lcs_pos($y);
1278 USE_ASSERTS
&& assert($k > 0);
1279 $ymids[$k] = $ymids[$k-1];
1282 while (list ( /* $junk */, $y) = each($matches)) {
1283 if ($y > $this->seq
[$k-1]) {
1284 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1285 // Optimization: this is a common case:
1286 // next match is just replacing previous match.
1287 $this->in_seq
[$this->seq
[$k]] = false;
1288 $this->seq
[$k] = $y;
1289 $this->in_seq
[$y] = 1;
1290 } else if (empty($this->in_seq
[$y])) {
1291 $k = $this->_lcs_pos($y);
1292 USE_ASSERTS
&& assert($k > 0);
1293 $ymids[$k] = $ymids[$k-1];
1299 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1300 $ymid = $ymids[$this->lcs
];
1301 for ($n = 0; $n < $nchunks - 1; $n++
) {
1302 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1303 $y1 = $ymid[$n] +
1;
1304 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1306 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1308 return array($this->lcs
, $seps);
1311 function _lcs_pos ($ypos) {
1313 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1314 $this->seq
[++
$this->lcs
] = $ypos;
1315 $this->in_seq
[$ypos] = 1;
1320 while ($beg < $end) {
1321 $mid = (int)(($beg +
$end) / 2);
1322 if ( $ypos > $this->seq
[$mid] )
1328 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1330 $this->in_seq
[$this->seq
[$end]] = false;
1331 $this->seq
[$end] = $ypos;
1332 $this->in_seq
[$ypos] = 1;
1336 /* Find LCS of two sequences.
1338 * The results are recorded in the vectors $this->{x,y}changed[], by
1339 * storing a 1 in the element for each line that is an insertion
1340 * or deletion (ie. is not in the LCS).
1342 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1344 * Note that XLIM, YLIM are exclusive bounds.
1345 * All line numbers are origin-0 and discarded lines are not counted.
1347 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1348 // Slide down the bottom initial diagonal.
1349 while ($xoff < $xlim && $yoff < $ylim
1350 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1355 // Slide up the top initial diagonal.
1356 while ($xlim > $xoff && $ylim > $yoff
1357 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1362 if ($xoff == $xlim ||
$yoff == $ylim)
1365 // This is ad hoc but seems to work well.
1366 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1367 //$nchunks = max(2,min(8,(int)$nchunks));
1368 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1370 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1374 // X and Y sequences have no common subsequence:
1375 // mark all changed.
1376 while ($yoff < $ylim)
1377 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1378 while ($xoff < $xlim)
1379 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1381 // Use the partitions to split this problem into subproblems.
1384 while ($pt2 = next($seps)) {
1385 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1391 /* Adjust inserts/deletes of identical lines to join changes
1392 * as much as possible.
1394 * We do something when a run of changed lines include a
1395 * line at one end and has an excluded, identical line at the other.
1396 * We are free to choose which identical line is included.
1397 * `compareseq' usually chooses the one at the beginning,
1398 * but usually it is cleaner to consider the following identical line
1399 * to be the "change".
1401 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1403 function _shift_boundaries ($lines, &$changed, $other_changed) {
1404 wfProfileIn( __METHOD__
);
1408 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1409 $len = sizeof($lines);
1410 $other_len = sizeof($other_changed);
1414 * Scan forwards to find beginning of another run of changes.
1415 * Also keep track of the corresponding point in the other file.
1417 * Throughout this code, $i and $j are adjusted together so that
1418 * the first $i elements of $changed and the first $j elements
1419 * of $other_changed both contain the same number of zeros
1420 * (unchanged lines).
1421 * Furthermore, $j is always kept so that $j == $other_len or
1422 * $other_changed[$j] == false.
1424 while ($j < $other_len && $other_changed[$j])
1427 while ($i < $len && ! $changed[$i]) {
1428 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1430 while ($j < $other_len && $other_changed[$j])
1439 // Find the end of this run of changes.
1440 while (++
$i < $len && $changed[$i])
1445 * Record the length of this run of changes, so that
1446 * we can later determine whether the run has grown.
1448 $runlength = $i - $start;
1451 * Move the changed region back, so long as the
1452 * previous unchanged line matches the last changed one.
1453 * This merges with previous changed regions.
1455 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1456 $changed[--$start] = 1;
1457 $changed[--$i] = false;
1458 while ($start > 0 && $changed[$start - 1])
1460 USE_ASSERTS
&& assert('$j > 0');
1461 while ($other_changed[--$j])
1463 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1467 * Set CORRESPONDING to the end of the changed run, at the last
1468 * point where it corresponds to a changed run in the other file.
1469 * CORRESPONDING == LEN means no such point has been found.
1471 $corresponding = $j < $other_len ?
$i : $len;
1474 * Move the changed region forward, so long as the
1475 * first changed line matches the following unchanged one.
1476 * This merges with following changed regions.
1477 * Do this second, so that if there are no merges,
1478 * the changed region is moved forward as far as possible.
1480 while ($i < $len && $lines[$start] == $lines[$i]) {
1481 $changed[$start++
] = false;
1483 while ($i < $len && $changed[$i])
1486 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1488 if ($j < $other_len && $other_changed[$j]) {
1489 $corresponding = $i;
1490 while ($j < $other_len && $other_changed[$j])
1494 } while ($runlength != $i - $start);
1497 * If possible, move the fully-merged run of changes
1498 * back to a corresponding run in the other file.
1500 while ($corresponding < $i) {
1501 $changed[--$start] = 1;
1503 USE_ASSERTS
&& assert('$j > 0');
1504 while ($other_changed[--$j])
1506 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1509 wfProfileOut( __METHOD__
);
1514 * Class representing a 'diff' between two sequences of strings.
1517 * @ingroup DifferenceEngine
1525 * Computes diff between sequences of strings.
1527 * @param $from_lines array An array of strings.
1528 * (Typically these are lines from a file.)
1529 * @param $to_lines array An array of strings.
1531 function Diff($from_lines, $to_lines) {
1532 $eng = new _DiffEngine
;
1533 $this->edits
= $eng->diff($from_lines, $to_lines);
1534 //$this->_check($from_lines, $to_lines);
1538 * Compute reversed Diff.
1542 * $diff = new Diff($lines1, $lines2);
1543 * $rev = $diff->reverse();
1544 * @return object A Diff object representing the inverse of the
1547 function reverse () {
1549 $rev->edits
= array();
1550 foreach ($this->edits
as $edit) {
1551 $rev->edits
[] = $edit->reverse();
1557 * Check for empty diff.
1559 * @return bool True iff two sequences were identical.
1561 function isEmpty () {
1562 foreach ($this->edits
as $edit) {
1563 if ($edit->type
!= 'copy')
1570 * Compute the length of the Longest Common Subsequence (LCS).
1572 * This is mostly for diagnostic purposed.
1574 * @return int The length of the LCS.
1578 foreach ($this->edits
as $edit) {
1579 if ($edit->type
== 'copy')
1580 $lcs +
= sizeof($edit->orig
);
1586 * Get the original set of lines.
1588 * This reconstructs the $from_lines parameter passed to the
1591 * @return array The original sequence of strings.
1596 foreach ($this->edits
as $edit) {
1598 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1604 * Get the closing set of lines.
1606 * This reconstructs the $to_lines parameter passed to the
1609 * @return array The sequence of strings.
1611 function closing() {
1614 foreach ($this->edits
as $edit) {
1616 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1622 * Check a Diff for validity.
1624 * This is here only for debugging purposes.
1626 function _check ($from_lines, $to_lines) {
1627 wfProfileIn( __METHOD__
);
1628 if (serialize($from_lines) != serialize($this->orig()))
1629 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1630 if (serialize($to_lines) != serialize($this->closing()))
1631 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1633 $rev = $this->reverse();
1634 if (serialize($to_lines) != serialize($rev->orig()))
1635 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1636 if (serialize($from_lines) != serialize($rev->closing()))
1637 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1641 foreach ($this->edits
as $edit) {
1642 if ( $prevtype == $edit->type
)
1643 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1644 $prevtype = $edit->type
;
1647 $lcs = $this->lcs();
1648 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1649 wfProfileOut( __METHOD__
);
1654 * @todo document, bad name.
1656 * @ingroup DifferenceEngine
1658 class MappedDiff
extends Diff
1663 * Computes diff between sequences of strings.
1665 * This can be used to compute things like
1666 * case-insensitve diffs, or diffs which ignore
1667 * changes in white-space.
1669 * @param $from_lines array An array of strings.
1670 * (Typically these are lines from a file.)
1672 * @param $to_lines array An array of strings.
1674 * @param $mapped_from_lines array This array should
1675 * have the same size number of elements as $from_lines.
1676 * The elements in $mapped_from_lines and
1677 * $mapped_to_lines are what is actually compared
1678 * when computing the diff.
1680 * @param $mapped_to_lines array This array should
1681 * have the same number of elements as $to_lines.
1683 function MappedDiff($from_lines, $to_lines,
1684 $mapped_from_lines, $mapped_to_lines) {
1685 wfProfileIn( __METHOD__
);
1687 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1688 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1690 $this->Diff($mapped_from_lines, $mapped_to_lines);
1693 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1694 $orig = &$this->edits
[$i]->orig
;
1695 if (is_array($orig)) {
1696 $orig = array_slice($from_lines, $xi, sizeof($orig));
1697 $xi +
= sizeof($orig);
1700 $closing = &$this->edits
[$i]->closing
;
1701 if (is_array($closing)) {
1702 $closing = array_slice($to_lines, $yi, sizeof($closing));
1703 $yi +
= sizeof($closing);
1706 wfProfileOut( __METHOD__
);
1711 * A class to format Diffs
1713 * This class formats the diff in classic diff format.
1714 * It is intended that this class be customized via inheritance,
1715 * to obtain fancier outputs.
1718 * @ingroup DifferenceEngine
1720 class DiffFormatter
{
1722 * Number of leading context "lines" to preserve.
1724 * This should be left at zero for this class, but subclasses
1725 * may want to set this to other values.
1727 var $leading_context_lines = 0;
1730 * Number of trailing context "lines" to preserve.
1732 * This should be left at zero for this class, but subclasses
1733 * may want to set this to other values.
1735 var $trailing_context_lines = 0;
1740 * @param $diff object A Diff object.
1741 * @return string The formatted output.
1743 function format($diff) {
1744 wfProfileIn( __METHOD__
);
1750 $nlead = $this->leading_context_lines
;
1751 $ntrail = $this->trailing_context_lines
;
1753 $this->_start_diff();
1755 foreach ($diff->edits
as $edit) {
1756 if ($edit->type
== 'copy') {
1757 if (is_array($block)) {
1758 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1763 $context = array_slice($edit->orig
, 0, $ntrail);
1764 $block[] = new _DiffOp_Copy($context);
1766 $this->_block($x0, $ntrail +
$xi - $x0,
1767 $y0, $ntrail +
$yi - $y0,
1772 $context = $edit->orig
;
1775 if (! is_array($block)) {
1776 $context = array_slice($context, sizeof($context) - $nlead);
1777 $x0 = $xi - sizeof($context);
1778 $y0 = $yi - sizeof($context);
1781 $block[] = new _DiffOp_Copy($context);
1787 $xi +
= sizeof($edit->orig
);
1789 $yi +
= sizeof($edit->closing
);
1792 if (is_array($block))
1793 $this->_block($x0, $xi - $x0,
1797 $end = $this->_end_diff();
1798 wfProfileOut( __METHOD__
);
1802 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1803 wfProfileIn( __METHOD__
);
1804 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1805 foreach ($edits as $edit) {
1806 if ($edit->type
== 'copy')
1807 $this->_context($edit->orig
);
1808 elseif ($edit->type
== 'add')
1809 $this->_added($edit->closing
);
1810 elseif ($edit->type
== 'delete')
1811 $this->_deleted($edit->orig
);
1812 elseif ($edit->type
== 'change')
1813 $this->_changed($edit->orig
, $edit->closing
);
1815 trigger_error('Unknown edit type', E_USER_ERROR
);
1817 $this->_end_block();
1818 wfProfileOut( __METHOD__
);
1821 function _start_diff() {
1825 function _end_diff() {
1826 $val = ob_get_contents();
1831 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1833 $xbeg .= "," . ($xbeg +
$xlen - 1);
1835 $ybeg .= "," . ($ybeg +
$ylen - 1);
1837 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1840 function _start_block($header) {
1841 echo $header . "\n";
1844 function _end_block() {
1847 function _lines($lines, $prefix = ' ') {
1848 foreach ($lines as $line)
1849 echo "$prefix $line\n";
1852 function _context($lines) {
1853 $this->_lines($lines);
1856 function _added($lines) {
1857 $this->_lines($lines, '>');
1859 function _deleted($lines) {
1860 $this->_lines($lines, '<');
1863 function _changed($orig, $closing) {
1864 $this->_deleted($orig);
1866 $this->_added($closing);
1871 * A formatter that outputs unified diffs
1872 * @ingroup DifferenceEngine
1875 class UnifiedDiffFormatter
extends DiffFormatter
{
1876 var $leading_context_lines = 2;
1877 var $trailing_context_lines = 2;
1879 function _added($lines) {
1880 $this->_lines($lines, '+');
1882 function _deleted($lines) {
1883 $this->_lines($lines, '-');
1885 function _changed($orig, $closing) {
1886 $this->_deleted($orig);
1887 $this->_added($closing);
1889 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1890 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1895 * A pseudo-formatter that just passes along the Diff::$edits array
1896 * @ingroup DifferenceEngine
1898 class ArrayDiffFormatter
extends DiffFormatter
{
1899 function format($diff) {
1903 foreach($diff->edits
as $edit)
1904 switch($edit->type
) {
1906 foreach($edit->closing
as $l) {
1910 'newline' => $newline++
1915 foreach($edit->orig
as $l) {
1917 'action' => 'delete',
1919 'oldline' => $oldline++
,
1924 foreach($edit->orig
as $i => $l) {
1926 'action' => 'change',
1928 'new' => @$edit->closing
[$i],
1929 'oldline' => $oldline++
,
1930 'newline' => $newline++
,
1935 $oldline +
= count($edit->orig
);
1936 $newline +
= count($edit->orig
);
1943 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1947 define('NBSP', ' '); // iso-8859-x non-breaking space.
1952 * @ingroup DifferenceEngine
1954 class _HWLDF_WordAccumulator
{
1955 function _HWLDF_WordAccumulator () {
1956 $this->_lines
= array();
1962 function _flushGroup ($new_tag) {
1963 if ($this->_group
!== '') {
1964 if ($this->_tag
== 'ins')
1965 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1966 htmlspecialchars ( $this->_group
) . '</ins>';
1967 elseif ($this->_tag
== 'del')
1968 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1969 htmlspecialchars ( $this->_group
) . '</del>';
1971 $this->_line
.= htmlspecialchars ( $this->_group
);
1974 $this->_tag
= $new_tag;
1977 function _flushLine ($new_tag) {
1978 $this->_flushGroup($new_tag);
1979 if ($this->_line
!= '')
1980 array_push ( $this->_lines
, $this->_line
);
1982 # make empty lines visible by inserting an NBSP
1983 array_push ( $this->_lines
, NBSP
);
1987 function addWords ($words, $tag = '') {
1988 if ($tag != $this->_tag
)
1989 $this->_flushGroup($tag);
1991 foreach ($words as $word) {
1992 // new-line should only come as first char of word.
1995 if ($word[0] == "\n") {
1996 $this->_flushLine($tag);
1997 $word = substr($word, 1);
1999 assert(!strstr($word, "\n"));
2000 $this->_group
.= $word;
2004 function getLines() {
2005 $this->_flushLine('~done');
2006 return $this->_lines
;
2013 * @ingroup DifferenceEngine
2015 class WordLevelDiff
extends MappedDiff
{
2016 const MAX_LINE_LENGTH
= 10000;
2018 function WordLevelDiff ($orig_lines, $closing_lines) {
2019 wfProfileIn( __METHOD__
);
2021 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
2022 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
2024 $this->MappedDiff($orig_words, $closing_words,
2025 $orig_stripped, $closing_stripped);
2026 wfProfileOut( __METHOD__
);
2029 function _split($lines) {
2030 wfProfileIn( __METHOD__
);
2033 $stripped = array();
2035 foreach ( $lines as $line ) {
2036 # If the line is too long, just pretend the entire line is one big word
2037 # This prevents resource exhaustion problems
2044 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2046 $stripped[] = $line;
2049 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2052 $words = array_merge( $words, $m[0] );
2053 $stripped = array_merge( $stripped, $m[1] );
2057 wfProfileOut( __METHOD__
);
2058 return array($words, $stripped);
2062 wfProfileIn( __METHOD__
);
2063 $orig = new _HWLDF_WordAccumulator
;
2065 foreach ($this->edits
as $edit) {
2066 if ($edit->type
== 'copy')
2067 $orig->addWords($edit->orig
);
2068 elseif ($edit->orig
)
2069 $orig->addWords($edit->orig
, 'del');
2071 $lines = $orig->getLines();
2072 wfProfileOut( __METHOD__
);
2076 function closing () {
2077 wfProfileIn( __METHOD__
);
2078 $closing = new _HWLDF_WordAccumulator
;
2080 foreach ($this->edits
as $edit) {
2081 if ($edit->type
== 'copy')
2082 $closing->addWords($edit->closing
);
2083 elseif ($edit->closing
)
2084 $closing->addWords($edit->closing
, 'ins');
2086 $lines = $closing->getLines();
2087 wfProfileOut( __METHOD__
);
2093 * Wikipedia Table style diff formatter.
2096 * @ingroup DifferenceEngine
2098 class TableDiffFormatter
extends DiffFormatter
{
2099 function TableDiffFormatter() {
2100 $this->leading_context_lines
= 2;
2101 $this->trailing_context_lines
= 2;
2104 public static function escapeWhiteSpace( $msg ) {
2105 $msg = preg_replace( '/^ /m', ' ', $msg );
2106 $msg = preg_replace( '/ $/m', ' ', $msg );
2107 $msg = preg_replace( '/ /', ' ', $msg );
2111 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2112 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2113 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2117 function _start_block( $header ) {
2121 function _end_block() {
2124 function _lines( $lines, $prefix=' ', $color='white' ) {
2127 # HTML-escape parameter before calling this
2128 function addedLine( $line ) {
2129 return $this->wrapLine( '+', 'diff-addedline', $line );
2132 # HTML-escape parameter before calling this
2133 function deletedLine( $line ) {
2134 return $this->wrapLine( '-', 'diff-deletedline', $line );
2137 # HTML-escape parameter before calling this
2138 function contextLine( $line ) {
2139 return $this->wrapLine( ' ', 'diff-context', $line );
2142 private function wrapLine( $marker, $class, $line ) {
2143 if( $line !== '' ) {
2144 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2145 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2147 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2150 function emptyLine() {
2151 return '<td colspan="2"> </td>';
2154 function _added( $lines ) {
2155 foreach ($lines as $line) {
2156 echo '<tr>' . $this->emptyLine() .
2157 $this->addedLine( '<ins class="diffchange">' .
2158 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2162 function _deleted($lines) {
2163 foreach ($lines as $line) {
2164 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2165 htmlspecialchars ( $line ) . '</del>' ) .
2166 $this->emptyLine() . "</tr>\n";
2170 function _context( $lines ) {
2171 foreach ($lines as $line) {
2173 $this->contextLine( htmlspecialchars ( $line ) ) .
2174 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2178 function _changed( $orig, $closing ) {
2179 wfProfileIn( __METHOD__
);
2181 $diff = new WordLevelDiff( $orig, $closing );
2182 $del = $diff->orig();
2183 $add = $diff->closing();
2185 # Notice that WordLevelDiff returns HTML-escaped output.
2186 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2188 while ( $line = array_shift( $del ) ) {
2189 $aline = array_shift( $add );
2190 echo '<tr>' . $this->deletedLine( $line ) .
2191 $this->addedLine( $aline ) . "</tr>\n";
2193 foreach ($add as $line) { # If any leftovers
2194 echo '<tr>' . $this->emptyLine() .
2195 $this->addedLine( $line ) . "</tr>\n";
2197 wfProfileOut( __METHOD__
);