343be247e7e73c2e4bf30536066bc02bc5bb20c1
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 @dl
( 'php_wikidiff.so' );
629 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
631 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
632 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
633 @dl
( 'php_wikidiff2.so' );
634 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
639 * Generate a diff, no caching
640 * $otext and $ntext must be already segmented
642 function generateDiffBody( $otext, $ntext ) {
643 global $wgExternalDiffEngine, $wgContLang;
645 $otext = str_replace( "\r\n", "\n", $otext );
646 $ntext = str_replace( "\r\n", "\n", $ntext );
648 $this->initDiffEngines();
650 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
651 # For historical reasons, external diff engine expects
652 # input text to be HTML-escaped already
653 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
654 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
655 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
656 $this->debug( 'wikidiff1' );
659 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
660 # Better external diff engine, the 2 may some day be dropped
661 # This one does the escaping and segmenting itself
662 wfProfileIn( 'wikidiff2_do_diff' );
663 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
664 $text .= $this->debug( 'wikidiff2' );
665 wfProfileOut( 'wikidiff2_do_diff' );
668 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
670 global $wgTmpDirectory;
671 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
672 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
674 $tempFile1 = fopen( $tempName1, "w" );
676 wfProfileOut( __METHOD__
);
679 $tempFile2 = fopen( $tempName2, "w" );
681 wfProfileOut( __METHOD__
);
684 fwrite( $tempFile1, $otext );
685 fwrite( $tempFile2, $ntext );
686 fclose( $tempFile1 );
687 fclose( $tempFile2 );
688 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
689 wfProfileIn( __METHOD__
. "-shellexec" );
690 $difftext = wfShellExec( $cmd );
691 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
692 wfProfileOut( __METHOD__
. "-shellexec" );
693 unlink( $tempName1 );
694 unlink( $tempName2 );
699 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
700 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
701 $diffs = new Diff( $ota, $nta );
702 $formatter = new TableDiffFormatter();
703 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
708 * Generate a debug comment indicating diff generating time,
709 * server node, and generator backend.
711 protected function debug( $generator="internal" ) {
712 global $wgShowHostnames;
713 $data = array( $generator );
714 if( $wgShowHostnames ) {
715 $data[] = wfHostname();
717 $data[] = wfTimestamp( TS_DB
);
718 return "<!-- diff generator: " .
727 * Replace line numbers with the text in the user's language
729 function localiseLineNumbers( $text ) {
730 return preg_replace_callback( '/<!--LINE (\d+)-->/',
731 array( &$this, 'localiseLineNumbersCb' ), $text );
734 function localiseLineNumbersCb( $matches ) {
736 return wfMsgExt( 'lineno', array (), $wgLang->formatNum( $matches[1] ) );
741 * If there are revisions between the ones being compared, return a note saying so.
743 function getMultiNotice() {
744 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
747 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
748 // Comparing two different pages? Count would be meaningless.
752 $oldid = $this->mOldRev
->getId();
753 $newid = $this->mNewRev
->getId();
754 if ( $oldid > $newid ) {
755 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
758 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
762 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
767 * Add the header to a diff body
769 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
771 $header = "<table class='diff'>";
772 if( $diff ) { // Safari/Chrome show broken output if cols not used
774 <col class='diff-marker' />
775 <col class='diff-content' />
776 <col class='diff-marker' />
777 <col class='diff-content' />";
782 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
783 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
787 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
789 return $header . $diff . "</table>";
793 * Use specified text instead of loading from the database
795 function setText( $oldText, $newText ) {
796 $this->mOldtext
= $oldText;
797 $this->mNewtext
= $newText;
798 $this->mTextLoaded
= 2;
799 $this->mRevisionsLoaded
= true;
803 * Load revision metadata for the specified articles. If newid is 0, then compare
804 * the old article in oldid to the current article; if oldid is 0, then
805 * compare the current article to the immediately previous one (ignoring the
808 * If oldid is false, leave the corresponding revision object set
809 * to false. This is impossible via ordinary user input, and is provided for
812 function loadRevisionData() {
813 global $wgLang, $wgUser;
814 if ( $this->mRevisionsLoaded
) {
817 // Whether it succeeds or fails, we don't want to try again
818 $this->mRevisionsLoaded
= true;
821 // Load the new revision object
822 $this->mNewRev
= $this->mNewid
823 ? Revision
::newFromId( $this->mNewid
)
824 : Revision
::newFromTitle( $this->mTitle
);
825 if( !$this->mNewRev
instanceof Revision
)
828 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
829 $this->mNewid
= $this->mNewRev
->getId();
831 // Check if page is editable
832 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
834 // Set assorted variables
835 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
836 $this->mNewPage
= $this->mNewRev
->getTitle();
837 if( $this->mNewRev
->isCurrent() ) {
838 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
839 $this->mPagetitle
= wfMsgHTML( 'currentrev-asof', $timestamp );
840 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
842 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
843 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
845 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
846 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
847 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
849 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
850 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
852 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
853 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
854 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
855 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
858 // Load the old revision object
859 $this->mOldRev
= false;
860 if( $this->mOldid
) {
861 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
862 } elseif ( $this->mOldid
=== 0 ) {
863 $rev = $this->mNewRev
->getPrevious();
865 $this->mOldid
= $rev->getId();
866 $this->mOldRev
= $rev;
868 // No previous revision; mark to show as first-version only.
869 $this->mOldid
= false;
870 $this->mOldRev
= false;
872 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
874 if( is_null( $this->mOldRev
) ) {
878 if ( $this->mOldRev
) {
879 $this->mOldPage
= $this->mOldRev
->getTitle();
881 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
882 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
883 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
884 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
886 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
887 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
888 // Add an "undo" link
889 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
890 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
891 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
892 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
893 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
896 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
897 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
898 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
899 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
907 * Load the text of the revisions, as well as revision data.
909 function loadText() {
910 if ( $this->mTextLoaded
== 2 ) {
913 // Whether it succeeds or fails, we don't want to try again
914 $this->mTextLoaded
= 2;
917 if ( !$this->loadRevisionData() ) {
920 if ( $this->mOldRev
) {
921 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
922 if ( $this->mOldtext
=== false ) {
926 if ( $this->mNewRev
) {
927 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
928 if ( $this->mNewtext
=== false ) {
936 * Load the text of the new revision, not the old one
938 function loadNewText() {
939 if ( $this->mTextLoaded
>= 1 ) {
942 $this->mTextLoaded
= 1;
944 if ( !$this->loadRevisionData() ) {
947 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
954 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
956 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
957 // You may copy this code freely under the conditions of the GPL.
960 define('USE_ASSERTS', function_exists('assert'));
965 * @ingroup DifferenceEngine
973 trigger_error('pure virtual', E_USER_ERROR
);
977 return $this->orig ?
sizeof($this->orig
) : 0;
980 function nclosing() {
981 return $this->closing ?
sizeof($this->closing
) : 0;
988 * @ingroup DifferenceEngine
990 class _DiffOp_Copy
extends _DiffOp
{
993 function _DiffOp_Copy ($orig, $closing = false) {
994 if (!is_array($closing))
997 $this->closing
= $closing;
1000 function reverse() {
1001 return new _DiffOp_Copy($this->closing
, $this->orig
);
1008 * @ingroup DifferenceEngine
1010 class _DiffOp_Delete
extends _DiffOp
{
1011 var $type = 'delete';
1013 function _DiffOp_Delete ($lines) {
1014 $this->orig
= $lines;
1015 $this->closing
= false;
1018 function reverse() {
1019 return new _DiffOp_Add($this->orig
);
1026 * @ingroup DifferenceEngine
1028 class _DiffOp_Add
extends _DiffOp
{
1031 function _DiffOp_Add ($lines) {
1032 $this->closing
= $lines;
1033 $this->orig
= false;
1036 function reverse() {
1037 return new _DiffOp_Delete($this->closing
);
1044 * @ingroup DifferenceEngine
1046 class _DiffOp_Change
extends _DiffOp
{
1047 var $type = 'change';
1049 function _DiffOp_Change ($orig, $closing) {
1050 $this->orig
= $orig;
1051 $this->closing
= $closing;
1054 function reverse() {
1055 return new _DiffOp_Change($this->closing
, $this->orig
);
1060 * Class used internally by Diff to actually compute the diffs.
1062 * The algorithm used here is mostly lifted from the perl module
1063 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1064 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1066 * More ideas are taken from:
1067 * http://www.ics.uci.edu/~eppstein/161/960229.html
1069 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1070 * diffutils-2.7, which can be found at:
1071 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1073 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1076 * Line length limits for robustness added by Tim Starling, 2005-08-31
1077 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1079 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1081 * @ingroup DifferenceEngine
1085 const MAX_XREF_LENGTH
= 10000;
1087 function diff ($from_lines, $to_lines){
1088 wfProfileIn( __METHOD__
);
1090 // Diff and store locally
1091 $this->diff_local($from_lines, $to_lines);
1093 // Merge edits when possible
1094 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1095 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1097 // Compute the edit operations.
1098 $n_from = sizeof($from_lines);
1099 $n_to = sizeof($to_lines);
1103 while ($xi < $n_from ||
$yi < $n_to) {
1104 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1105 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1107 // Skip matching "snake".
1109 while ( $xi < $n_from && $yi < $n_to
1110 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1111 $copy[] = $from_lines[$xi++
];
1115 $edits[] = new _DiffOp_Copy($copy);
1117 // Find deletes & adds.
1119 while ($xi < $n_from && $this->xchanged
[$xi])
1120 $delete[] = $from_lines[$xi++
];
1123 while ($yi < $n_to && $this->ychanged
[$yi])
1124 $add[] = $to_lines[$yi++
];
1126 if ($delete && $add)
1127 $edits[] = new _DiffOp_Change($delete, $add);
1129 $edits[] = new _DiffOp_Delete($delete);
1131 $edits[] = new _DiffOp_Add($add);
1133 wfProfileOut( __METHOD__
);
1137 function diff_local ($from_lines, $to_lines) {
1138 global $wgExternalDiffEngine;
1139 wfProfileIn( __METHOD__
);
1141 if($wgExternalDiffEngine == 'wikidiff3'){
1143 $wikidiff3 = new WikiDiff3();
1144 $wikidiff3->diff($from_lines, $to_lines);
1145 $this->xchanged
= $wikidiff3->removed
;
1146 $this->ychanged
= $wikidiff3->added
;
1150 $n_from = sizeof($from_lines);
1151 $n_to = sizeof($to_lines);
1152 $this->xchanged
= $this->ychanged
= array();
1153 $this->xv
= $this->yv
= array();
1154 $this->xind
= $this->yind
= array();
1156 unset($this->in_seq
);
1159 // Skip leading common lines.
1160 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1161 if ($from_lines[$skip] !== $to_lines[$skip])
1163 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1165 // Skip trailing common lines.
1166 $xi = $n_from; $yi = $n_to;
1167 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1168 if ($from_lines[$xi] !== $to_lines[$yi])
1170 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1173 // Ignore lines which do not exist in both files.
1174 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1175 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1178 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1179 $line = $to_lines[$yi];
1180 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1182 $yhash[$this->_line_hash($line)] = 1;
1183 $this->yv
[] = $line;
1184 $this->yind
[] = $yi;
1186 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1187 $line = $from_lines[$xi];
1188 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1190 $this->xv
[] = $line;
1191 $this->xind
[] = $xi;
1195 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1197 wfProfileOut( __METHOD__
);
1201 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1203 function _line_hash( $line ) {
1204 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1205 return md5( $line );
1211 /* Divide the Largest Common Subsequence (LCS) of the sequences
1212 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1215 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1216 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1217 * sub sequences. The first sub-sequence is contained in [X0, X1),
1218 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1219 * that (X0, Y0) == (XOFF, YOFF) and
1220 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1222 * This function assumes that the first lines of the specified portions
1223 * of the two files do not match, and likewise that the last lines do not
1224 * match. The caller must trim matching lines from the beginning and end
1225 * of the portions it is going to specify.
1227 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1230 if ($xlim - $xoff > $ylim - $yoff) {
1231 // Things seems faster (I'm not sure I understand why)
1232 // when the shortest sequence in X.
1234 list ($xoff, $xlim, $yoff, $ylim)
1235 = array( $yoff, $ylim, $xoff, $xlim);
1239 for ($i = $ylim - 1; $i >= $yoff; $i--)
1240 $ymatches[$this->xv
[$i]][] = $i;
1242 for ($i = $ylim - 1; $i >= $yoff; $i--)
1243 $ymatches[$this->yv
[$i]][] = $i;
1246 $this->seq
[0]= $yoff - 1;
1247 $this->in_seq
= array();
1248 $ymids[0] = array();
1250 $numer = $xlim - $xoff +
$nchunks - 1;
1252 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1254 for ($i = 0; $i <= $this->lcs
; $i++
)
1255 $ymids[$i][$chunk-1] = $this->seq
[$i];
1257 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1258 for ( ; $x < $x1; $x++
) {
1259 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1260 if (empty($ymatches[$line]))
1262 $matches = $ymatches[$line];
1264 while (list ($junk, $y) = each($matches))
1265 if (empty($this->in_seq
[$y])) {
1266 $k = $this->_lcs_pos($y);
1267 USE_ASSERTS
&& assert($k > 0);
1268 $ymids[$k] = $ymids[$k-1];
1271 while (list ( /* $junk */, $y) = each($matches)) {
1272 if ($y > $this->seq
[$k-1]) {
1273 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1274 // Optimization: this is a common case:
1275 // next match is just replacing previous match.
1276 $this->in_seq
[$this->seq
[$k]] = false;
1277 $this->seq
[$k] = $y;
1278 $this->in_seq
[$y] = 1;
1279 } else if (empty($this->in_seq
[$y])) {
1280 $k = $this->_lcs_pos($y);
1281 USE_ASSERTS
&& assert($k > 0);
1282 $ymids[$k] = $ymids[$k-1];
1288 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1289 $ymid = $ymids[$this->lcs
];
1290 for ($n = 0; $n < $nchunks - 1; $n++
) {
1291 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1292 $y1 = $ymid[$n] +
1;
1293 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1295 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1297 return array($this->lcs
, $seps);
1300 function _lcs_pos ($ypos) {
1302 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1303 $this->seq
[++
$this->lcs
] = $ypos;
1304 $this->in_seq
[$ypos] = 1;
1309 while ($beg < $end) {
1310 $mid = (int)(($beg +
$end) / 2);
1311 if ( $ypos > $this->seq
[$mid] )
1317 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1319 $this->in_seq
[$this->seq
[$end]] = false;
1320 $this->seq
[$end] = $ypos;
1321 $this->in_seq
[$ypos] = 1;
1325 /* Find LCS of two sequences.
1327 * The results are recorded in the vectors $this->{x,y}changed[], by
1328 * storing a 1 in the element for each line that is an insertion
1329 * or deletion (ie. is not in the LCS).
1331 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1333 * Note that XLIM, YLIM are exclusive bounds.
1334 * All line numbers are origin-0 and discarded lines are not counted.
1336 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1337 // Slide down the bottom initial diagonal.
1338 while ($xoff < $xlim && $yoff < $ylim
1339 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1344 // Slide up the top initial diagonal.
1345 while ($xlim > $xoff && $ylim > $yoff
1346 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1351 if ($xoff == $xlim ||
$yoff == $ylim)
1354 // This is ad hoc but seems to work well.
1355 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1356 //$nchunks = max(2,min(8,(int)$nchunks));
1357 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1359 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1363 // X and Y sequences have no common subsequence:
1364 // mark all changed.
1365 while ($yoff < $ylim)
1366 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1367 while ($xoff < $xlim)
1368 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1370 // Use the partitions to split this problem into subproblems.
1373 while ($pt2 = next($seps)) {
1374 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1380 /* Adjust inserts/deletes of identical lines to join changes
1381 * as much as possible.
1383 * We do something when a run of changed lines include a
1384 * line at one end and has an excluded, identical line at the other.
1385 * We are free to choose which identical line is included.
1386 * `compareseq' usually chooses the one at the beginning,
1387 * but usually it is cleaner to consider the following identical line
1388 * to be the "change".
1390 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1392 function _shift_boundaries ($lines, &$changed, $other_changed) {
1393 wfProfileIn( __METHOD__
);
1397 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1398 $len = sizeof($lines);
1399 $other_len = sizeof($other_changed);
1403 * Scan forwards to find beginning of another run of changes.
1404 * Also keep track of the corresponding point in the other file.
1406 * Throughout this code, $i and $j are adjusted together so that
1407 * the first $i elements of $changed and the first $j elements
1408 * of $other_changed both contain the same number of zeros
1409 * (unchanged lines).
1410 * Furthermore, $j is always kept so that $j == $other_len or
1411 * $other_changed[$j] == false.
1413 while ($j < $other_len && $other_changed[$j])
1416 while ($i < $len && ! $changed[$i]) {
1417 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1419 while ($j < $other_len && $other_changed[$j])
1428 // Find the end of this run of changes.
1429 while (++
$i < $len && $changed[$i])
1434 * Record the length of this run of changes, so that
1435 * we can later determine whether the run has grown.
1437 $runlength = $i - $start;
1440 * Move the changed region back, so long as the
1441 * previous unchanged line matches the last changed one.
1442 * This merges with previous changed regions.
1444 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1445 $changed[--$start] = 1;
1446 $changed[--$i] = false;
1447 while ($start > 0 && $changed[$start - 1])
1449 USE_ASSERTS
&& assert('$j > 0');
1450 while ($other_changed[--$j])
1452 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1456 * Set CORRESPONDING to the end of the changed run, at the last
1457 * point where it corresponds to a changed run in the other file.
1458 * CORRESPONDING == LEN means no such point has been found.
1460 $corresponding = $j < $other_len ?
$i : $len;
1463 * Move the changed region forward, so long as the
1464 * first changed line matches the following unchanged one.
1465 * This merges with following changed regions.
1466 * Do this second, so that if there are no merges,
1467 * the changed region is moved forward as far as possible.
1469 while ($i < $len && $lines[$start] == $lines[$i]) {
1470 $changed[$start++
] = false;
1472 while ($i < $len && $changed[$i])
1475 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1477 if ($j < $other_len && $other_changed[$j]) {
1478 $corresponding = $i;
1479 while ($j < $other_len && $other_changed[$j])
1483 } while ($runlength != $i - $start);
1486 * If possible, move the fully-merged run of changes
1487 * back to a corresponding run in the other file.
1489 while ($corresponding < $i) {
1490 $changed[--$start] = 1;
1492 USE_ASSERTS
&& assert('$j > 0');
1493 while ($other_changed[--$j])
1495 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1498 wfProfileOut( __METHOD__
);
1503 * Class representing a 'diff' between two sequences of strings.
1506 * @ingroup DifferenceEngine
1514 * Computes diff between sequences of strings.
1516 * @param $from_lines array An array of strings.
1517 * (Typically these are lines from a file.)
1518 * @param $to_lines array An array of strings.
1520 function Diff($from_lines, $to_lines) {
1521 $eng = new _DiffEngine
;
1522 $this->edits
= $eng->diff($from_lines, $to_lines);
1523 //$this->_check($from_lines, $to_lines);
1527 * Compute reversed Diff.
1531 * $diff = new Diff($lines1, $lines2);
1532 * $rev = $diff->reverse();
1533 * @return object A Diff object representing the inverse of the
1536 function reverse () {
1538 $rev->edits
= array();
1539 foreach ($this->edits
as $edit) {
1540 $rev->edits
[] = $edit->reverse();
1546 * Check for empty diff.
1548 * @return bool True iff two sequences were identical.
1550 function isEmpty () {
1551 foreach ($this->edits
as $edit) {
1552 if ($edit->type
!= 'copy')
1559 * Compute the length of the Longest Common Subsequence (LCS).
1561 * This is mostly for diagnostic purposed.
1563 * @return int The length of the LCS.
1567 foreach ($this->edits
as $edit) {
1568 if ($edit->type
== 'copy')
1569 $lcs +
= sizeof($edit->orig
);
1575 * Get the original set of lines.
1577 * This reconstructs the $from_lines parameter passed to the
1580 * @return array The original sequence of strings.
1585 foreach ($this->edits
as $edit) {
1587 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1593 * Get the closing set of lines.
1595 * This reconstructs the $to_lines parameter passed to the
1598 * @return array The sequence of strings.
1600 function closing() {
1603 foreach ($this->edits
as $edit) {
1605 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1611 * Check a Diff for validity.
1613 * This is here only for debugging purposes.
1615 function _check ($from_lines, $to_lines) {
1616 wfProfileIn( __METHOD__
);
1617 if (serialize($from_lines) != serialize($this->orig()))
1618 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1619 if (serialize($to_lines) != serialize($this->closing()))
1620 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1622 $rev = $this->reverse();
1623 if (serialize($to_lines) != serialize($rev->orig()))
1624 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1625 if (serialize($from_lines) != serialize($rev->closing()))
1626 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1630 foreach ($this->edits
as $edit) {
1631 if ( $prevtype == $edit->type
)
1632 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1633 $prevtype = $edit->type
;
1636 $lcs = $this->lcs();
1637 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1638 wfProfileOut( __METHOD__
);
1643 * @todo document, bad name.
1645 * @ingroup DifferenceEngine
1647 class MappedDiff
extends Diff
1652 * Computes diff between sequences of strings.
1654 * This can be used to compute things like
1655 * case-insensitve diffs, or diffs which ignore
1656 * changes in white-space.
1658 * @param $from_lines array An array of strings.
1659 * (Typically these are lines from a file.)
1661 * @param $to_lines array An array of strings.
1663 * @param $mapped_from_lines array This array should
1664 * have the same size number of elements as $from_lines.
1665 * The elements in $mapped_from_lines and
1666 * $mapped_to_lines are what is actually compared
1667 * when computing the diff.
1669 * @param $mapped_to_lines array This array should
1670 * have the same number of elements as $to_lines.
1672 function MappedDiff($from_lines, $to_lines,
1673 $mapped_from_lines, $mapped_to_lines) {
1674 wfProfileIn( __METHOD__
);
1676 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1677 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1679 $this->Diff($mapped_from_lines, $mapped_to_lines);
1682 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1683 $orig = &$this->edits
[$i]->orig
;
1684 if (is_array($orig)) {
1685 $orig = array_slice($from_lines, $xi, sizeof($orig));
1686 $xi +
= sizeof($orig);
1689 $closing = &$this->edits
[$i]->closing
;
1690 if (is_array($closing)) {
1691 $closing = array_slice($to_lines, $yi, sizeof($closing));
1692 $yi +
= sizeof($closing);
1695 wfProfileOut( __METHOD__
);
1700 * A class to format Diffs
1702 * This class formats the diff in classic diff format.
1703 * It is intended that this class be customized via inheritance,
1704 * to obtain fancier outputs.
1707 * @ingroup DifferenceEngine
1709 class DiffFormatter
{
1711 * Number of leading context "lines" to preserve.
1713 * This should be left at zero for this class, but subclasses
1714 * may want to set this to other values.
1716 var $leading_context_lines = 0;
1719 * Number of trailing context "lines" to preserve.
1721 * This should be left at zero for this class, but subclasses
1722 * may want to set this to other values.
1724 var $trailing_context_lines = 0;
1729 * @param $diff object A Diff object.
1730 * @return string The formatted output.
1732 function format($diff) {
1733 wfProfileIn( __METHOD__
);
1739 $nlead = $this->leading_context_lines
;
1740 $ntrail = $this->trailing_context_lines
;
1742 $this->_start_diff();
1744 foreach ($diff->edits
as $edit) {
1745 if ($edit->type
== 'copy') {
1746 if (is_array($block)) {
1747 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1752 $context = array_slice($edit->orig
, 0, $ntrail);
1753 $block[] = new _DiffOp_Copy($context);
1755 $this->_block($x0, $ntrail +
$xi - $x0,
1756 $y0, $ntrail +
$yi - $y0,
1761 $context = $edit->orig
;
1764 if (! is_array($block)) {
1765 $context = array_slice($context, sizeof($context) - $nlead);
1766 $x0 = $xi - sizeof($context);
1767 $y0 = $yi - sizeof($context);
1770 $block[] = new _DiffOp_Copy($context);
1776 $xi +
= sizeof($edit->orig
);
1778 $yi +
= sizeof($edit->closing
);
1781 if (is_array($block))
1782 $this->_block($x0, $xi - $x0,
1786 $end = $this->_end_diff();
1787 wfProfileOut( __METHOD__
);
1791 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1792 wfProfileIn( __METHOD__
);
1793 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1794 foreach ($edits as $edit) {
1795 if ($edit->type
== 'copy')
1796 $this->_context($edit->orig
);
1797 elseif ($edit->type
== 'add')
1798 $this->_added($edit->closing
);
1799 elseif ($edit->type
== 'delete')
1800 $this->_deleted($edit->orig
);
1801 elseif ($edit->type
== 'change')
1802 $this->_changed($edit->orig
, $edit->closing
);
1804 trigger_error('Unknown edit type', E_USER_ERROR
);
1806 $this->_end_block();
1807 wfProfileOut( __METHOD__
);
1810 function _start_diff() {
1814 function _end_diff() {
1815 $val = ob_get_contents();
1820 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1822 $xbeg .= "," . ($xbeg +
$xlen - 1);
1824 $ybeg .= "," . ($ybeg +
$ylen - 1);
1826 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1829 function _start_block($header) {
1830 echo $header . "\n";
1833 function _end_block() {
1836 function _lines($lines, $prefix = ' ') {
1837 foreach ($lines as $line)
1838 echo "$prefix $line\n";
1841 function _context($lines) {
1842 $this->_lines($lines);
1845 function _added($lines) {
1846 $this->_lines($lines, '>');
1848 function _deleted($lines) {
1849 $this->_lines($lines, '<');
1852 function _changed($orig, $closing) {
1853 $this->_deleted($orig);
1855 $this->_added($closing);
1860 * A formatter that outputs unified diffs
1861 * @ingroup DifferenceEngine
1864 class UnifiedDiffFormatter
extends DiffFormatter
{
1865 var $leading_context_lines = 2;
1866 var $trailing_context_lines = 2;
1868 function _added($lines) {
1869 $this->_lines($lines, '+');
1871 function _deleted($lines) {
1872 $this->_lines($lines, '-');
1874 function _changed($orig, $closing) {
1875 $this->_deleted($orig);
1876 $this->_added($closing);
1878 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1879 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1884 * A pseudo-formatter that just passes along the Diff::$edits array
1885 * @ingroup DifferenceEngine
1887 class ArrayDiffFormatter
extends DiffFormatter
{
1888 function format($diff) {
1892 foreach($diff->edits
as $edit)
1893 switch($edit->type
) {
1895 foreach($edit->closing
as $l) {
1899 'newline' => $newline++
1904 foreach($edit->orig
as $l) {
1906 'action' => 'delete',
1908 'oldline' => $oldline++
,
1913 foreach($edit->orig
as $i => $l) {
1915 'action' => 'change',
1917 'new' => @$edit->closing
[$i],
1918 'oldline' => $oldline++
,
1919 'newline' => $newline++
,
1924 $oldline +
= count($edit->orig
);
1925 $newline +
= count($edit->orig
);
1932 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1936 define('NBSP', ' '); // iso-8859-x non-breaking space.
1941 * @ingroup DifferenceEngine
1943 class _HWLDF_WordAccumulator
{
1944 function _HWLDF_WordAccumulator () {
1945 $this->_lines
= array();
1951 function _flushGroup ($new_tag) {
1952 if ($this->_group
!== '') {
1953 if ($this->_tag
== 'ins')
1954 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1955 htmlspecialchars ( $this->_group
) . '</ins>';
1956 elseif ($this->_tag
== 'del')
1957 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1958 htmlspecialchars ( $this->_group
) . '</del>';
1960 $this->_line
.= htmlspecialchars ( $this->_group
);
1963 $this->_tag
= $new_tag;
1966 function _flushLine ($new_tag) {
1967 $this->_flushGroup($new_tag);
1968 if ($this->_line
!= '')
1969 array_push ( $this->_lines
, $this->_line
);
1971 # make empty lines visible by inserting an NBSP
1972 array_push ( $this->_lines
, NBSP
);
1976 function addWords ($words, $tag = '') {
1977 if ($tag != $this->_tag
)
1978 $this->_flushGroup($tag);
1980 foreach ($words as $word) {
1981 // new-line should only come as first char of word.
1984 if ($word[0] == "\n") {
1985 $this->_flushLine($tag);
1986 $word = substr($word, 1);
1988 assert(!strstr($word, "\n"));
1989 $this->_group
.= $word;
1993 function getLines() {
1994 $this->_flushLine('~done');
1995 return $this->_lines
;
2002 * @ingroup DifferenceEngine
2004 class WordLevelDiff
extends MappedDiff
{
2005 const MAX_LINE_LENGTH
= 10000;
2007 function WordLevelDiff ($orig_lines, $closing_lines) {
2008 wfProfileIn( __METHOD__
);
2010 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
2011 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
2013 $this->MappedDiff($orig_words, $closing_words,
2014 $orig_stripped, $closing_stripped);
2015 wfProfileOut( __METHOD__
);
2018 function _split($lines) {
2019 wfProfileIn( __METHOD__
);
2022 $stripped = array();
2024 foreach ( $lines as $line ) {
2025 # If the line is too long, just pretend the entire line is one big word
2026 # This prevents resource exhaustion problems
2033 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2035 $stripped[] = $line;
2038 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2041 $words = array_merge( $words, $m[0] );
2042 $stripped = array_merge( $stripped, $m[1] );
2046 wfProfileOut( __METHOD__
);
2047 return array($words, $stripped);
2051 wfProfileIn( __METHOD__
);
2052 $orig = new _HWLDF_WordAccumulator
;
2054 foreach ($this->edits
as $edit) {
2055 if ($edit->type
== 'copy')
2056 $orig->addWords($edit->orig
);
2057 elseif ($edit->orig
)
2058 $orig->addWords($edit->orig
, 'del');
2060 $lines = $orig->getLines();
2061 wfProfileOut( __METHOD__
);
2065 function closing () {
2066 wfProfileIn( __METHOD__
);
2067 $closing = new _HWLDF_WordAccumulator
;
2069 foreach ($this->edits
as $edit) {
2070 if ($edit->type
== 'copy')
2071 $closing->addWords($edit->closing
);
2072 elseif ($edit->closing
)
2073 $closing->addWords($edit->closing
, 'ins');
2075 $lines = $closing->getLines();
2076 wfProfileOut( __METHOD__
);
2082 * Wikipedia Table style diff formatter.
2085 * @ingroup DifferenceEngine
2087 class TableDiffFormatter
extends DiffFormatter
{
2088 function TableDiffFormatter() {
2089 $this->leading_context_lines
= 2;
2090 $this->trailing_context_lines
= 2;
2093 public static function escapeWhiteSpace( $msg ) {
2094 $msg = preg_replace( '/^ /m', ' ', $msg );
2095 $msg = preg_replace( '/ $/m', ' ', $msg );
2096 $msg = preg_replace( '/ /', ' ', $msg );
2100 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2101 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2102 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2106 function _start_block( $header ) {
2110 function _end_block() {
2113 function _lines( $lines, $prefix=' ', $color='white' ) {
2116 # HTML-escape parameter before calling this
2117 function addedLine( $line ) {
2118 return $this->wrapLine( '+', 'diff-addedline', $line );
2121 # HTML-escape parameter before calling this
2122 function deletedLine( $line ) {
2123 return $this->wrapLine( '-', 'diff-deletedline', $line );
2126 # HTML-escape parameter before calling this
2127 function contextLine( $line ) {
2128 return $this->wrapLine( ' ', 'diff-context', $line );
2131 private function wrapLine( $marker, $class, $line ) {
2132 if( $line !== '' ) {
2133 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2134 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2136 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2139 function emptyLine() {
2140 return '<td colspan="2"> </td>';
2143 function _added( $lines ) {
2144 foreach ($lines as $line) {
2145 echo '<tr>' . $this->emptyLine() .
2146 $this->addedLine( '<ins class="diffchange">' .
2147 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2151 function _deleted($lines) {
2152 foreach ($lines as $line) {
2153 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2154 htmlspecialchars ( $line ) . '</del>' ) .
2155 $this->emptyLine() . "</tr>\n";
2159 function _context( $lines ) {
2160 foreach ($lines as $line) {
2162 $this->contextLine( htmlspecialchars ( $line ) ) .
2163 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2167 function _changed( $orig, $closing ) {
2168 wfProfileIn( __METHOD__
);
2170 $diff = new WordLevelDiff( $orig, $closing );
2171 $del = $diff->orig();
2172 $add = $diff->closing();
2174 # Notice that WordLevelDiff returns HTML-escaped output.
2175 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2177 while ( $line = array_shift( $del ) ) {
2178 $aline = array_shift( $add );
2179 echo '<tr>' . $this->deletedLine( $line ) .
2180 $this->addedLine( $aline ) . "</tr>\n";
2182 foreach ($add as $line) { # If any leftovers
2183 echo '<tr>' . $this->emptyLine() .
2184 $this->addedLine( $line ) . "</tr>\n";
2186 wfProfileOut( __METHOD__
);