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 )
50 $this->mTitle
= $titleObj;
53 $this->mTitle
= $wgTitle;
55 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
57 if ( 'prev' === $new ) {
58 # Show diff between revision $old and the previous one.
59 # Get previous one from DB.
60 $this->mNewid
= intval($old);
61 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
62 } elseif ( 'next' === $new ) {
63 # Show diff between revision $old and the next one.
64 # Get next one from DB.
65 $this->mOldid
= intval($old);
66 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
67 if ( false === $this->mNewid
) {
68 # if no result, NewId points to the newest old revision. The only newer
69 # revision is cur, which is "0".
73 $this->mOldid
= intval($old);
74 $this->mNewid
= intval($new);
75 wfRunHooks( 'NewDifferenceEngine', array(&$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new) );
77 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
78 $this->mRefreshCache
= $refreshCache;
79 $this->htmldiff
= $htmldiff;
80 $this->unhide
= $unhide;
87 function wasCacheHit() {
88 return $this->mCacheHit
;
99 function showDiffPage( $diffOnly = false ) {
100 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
101 wfProfileIn( __METHOD__
);
104 # If external diffs are enabled both globally and for the user,
105 # we'll use the application/x-external-editor interface to call
106 # an external diff tool like kompare, kdiff3, etc.
107 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
108 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
110 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
111 $url1=$this->mTitle
->getFullURL( array(
113 'oldid' => $this->mOldid
115 $url2=$this->mTitle
->getFullURL( array(
117 'oldid' => $this->mNewid
119 $special=$wgLang->getNsText(NS_SPECIAL
);
124 Script={$wgServer}{$wgScript}
125 Special namespace={$special}
139 $wgOut->setArticleFlag( false );
140 if ( !$this->loadRevisionData() ) {
141 $t = $this->mTitle
->getPrefixedText();
142 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
143 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
144 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
145 wfProfileOut( __METHOD__
);
149 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
151 if ( $this->mNewRev
->isCurrent() ) {
152 $wgOut->setArticleFlag( true );
155 # mOldid is false if the difference engine is called with a "vague" query for
156 # a diff between a version V and its previous version V' AND the version V
157 # is the first version of that article. In that case, V' does not exist.
158 if ( $this->mOldid
=== false ) {
159 $this->showFirstRevision();
160 $this->renderNewRevision(); // should we respect $diffOnly here or not?
161 wfProfileOut( __METHOD__
);
165 $wgOut->suppressQuickbar();
167 $oldTitle = $this->mOldPage
->getPrefixedText();
168 $newTitle = $this->mNewPage
->getPrefixedText();
169 if( $oldTitle == $newTitle ) {
170 $wgOut->setPageTitle( $newTitle );
172 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
174 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
175 $wgOut->setRobotPolicy( 'noindex,nofollow' );
177 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
178 $wgOut->loginToUse();
181 wfProfileOut( __METHOD__
);
185 $sk = $wgUser->getSkin();
187 // Check if page is editable
188 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
189 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
190 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
195 // Prepare a change patrol link, if applicable
196 if( $wgUseRCPatrol && $this->mTitle
->userCan('patrol') ) {
197 // If we've been given an explicit change identifier, use it; saves time
198 if( $this->mRcidMarkPatrolled
) {
199 $rcid = $this->mRcidMarkPatrolled
;
200 $rc = RecentChange
::newFromId( $rcid );
201 // Already patrolled?
202 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ?
$rcid : 0;
204 // Look for an unpatrolled change corresponding to this diff
205 $db = wfGetDB( DB_SLAVE
);
206 $change = RecentChange
::newFromConds(
208 // Redundant user,timestamp condition so we can use the existing index
209 'rc_user_text' => $this->mNewRev
->getRawUserText(),
210 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
211 'rc_this_oldid' => $this->mNewid
,
212 'rc_last_oldid' => $this->mOldid
,
217 if( $change instanceof RecentChange
) {
218 $rcid = $change->mAttribs
['rc_id'];
219 $this->mRcidMarkPatrolled
= $rcid;
227 $patrol = ' <span class="patrollink">[' . $sk->link(
229 wfMsgHtml( 'markaspatrolleddiff' ),
232 'action' => 'markpatrolled',
247 # Carry over 'diffonly' param via navigation links
248 if( $diffOnly != $wgUser->getBoolOption('diffonly') ) {
249 $query['diffonly'] = $diffOnly;
252 $htmldiffarg = $this->htmlDiffArgument();
255 $query['htmldiff'] = $htmldiffarg['htmldiff'];
258 # Make "previous revision link"
259 $query['diff'] = 'prev';
260 $query['oldid'] = $this->mOldid
;
262 $prevlink = $sk->link(
264 wfMsgHtml( 'previousdiff' ),
266 'id' => 'differences-prevlink'
274 # Make "next revision link"
275 $query['diff'] = 'next';
276 $query['oldid'] = $this->mNewid
;
278 if( $this->mNewRev
->isCurrent() ) {
279 $nextlink = ' ';
281 $nextlink = $sk->link(
283 wfMsgHtml( 'nextdiff' ),
285 'id' => 'differences-nextlink'
298 if( $this->mOldRev
->isMinor() ) {
299 $oldminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
301 if( $this->mNewRev
->isMinor() ) {
302 $newminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
305 $rdel = ''; $ldel = '';
306 if( $wgUser->isAllowed( 'deleterevision' ) ) {
307 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
308 // If revision was hidden from sysops
309 $ldel = Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), '(' . wfMsgHtml( 'rev-delundel' ) . ')' );
312 'type' => 'revision',
313 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
314 'ids' => $this->mOldRev
->getId()
316 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
318 $ldel = " $ldel ";
319 // We don't currently handle well changing the top revision's settings
320 if( $this->mNewRev
->isCurrent() ) {
321 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
322 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
323 // If revision was hidden from sysops
324 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
327 'type' => 'revision',
328 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
329 'ids' => $this->mNewRev
->getId()
331 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
333 $rdel = " $rdel ";
336 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
337 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
338 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
339 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
340 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
341 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
342 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
343 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
345 # Check if this user can see the revisions
346 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
)
347 && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
348 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
)
349 ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
350 # Output the diff if allowed...
351 if( $deleted && (!$this->unhide ||
!$allowed) ) {
352 $this->showDiffStyle();
353 $multi = $this->getMultiNotice();
354 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
356 # Give explanation for why revision is not visible
357 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
358 array( 'rev-deleted-no-diff' ) );
360 # Give explanation and add a link to view the diff...
361 $link = $this->mTitle
->getFullUrl( array(
362 'diff' => $this->mNewid
,
363 'oldid' => $this->mOldid
,
366 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
367 array( 'rev-deleted-unhide-diff', $link ) );
369 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
370 $multi = $this->getMultiNotice();
371 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
373 wfMsgHtml( 'wikicodecomparison' ),
375 'id' => 'differences-switchtype'
378 'diff' => $this->mNewid
,
379 'oldid' => $this->mOldid
,
387 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
388 $this->renderHtmlDiff();
390 if( $wgEnableHtmlDiff ) {
391 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
393 wfMsgHtml( 'visualcomparison' ),
395 'id' => 'differences-switchtype'
398 'diff' => $this->mNewid
,
399 'oldid' => $this->mOldid
,
408 $this->showDiff( $oldHeader, $newHeader );
410 $this->renderNewRevision();
413 wfProfileOut( __METHOD__
);
417 * Show the new revision of the page.
419 function renderNewRevision() {
420 global $wgOut, $wgUser;
421 wfProfileIn( __METHOD__
);
423 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
424 # Add deleted rev tag if needed
425 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
426 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
427 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
428 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
431 if( !$this->mNewRev
->isCurrent() ) {
432 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
435 $this->loadNewText();
436 if( is_object( $this->mNewRev
) ) {
437 $wgOut->setRevisionId( $this->mNewRev
->getId() );
440 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
441 // Stolen from Article::view --AG 2007-10-11
442 // Give hooks a chance to customise the output
443 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
444 // Wrap the whole lot in a <pre> and don't parse
446 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
447 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
448 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
449 $wgOut->addHTML( "\n</pre>\n" );
452 $wgOut->addWikiTextTidy( $this->mNewtext
);
455 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
456 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
458 # Add redundant patrol link on bottom...
459 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
460 $sk = $wgUser->getSkin();
462 "<div class='patrollink'>[" . $sk->link(
464 wfMsgHtml( 'markaspatrolleddiff' ),
467 'action' => 'markpatrolled',
468 'rcid' => $this->mRcidMarkPatrolled
474 wfProfileOut( __METHOD__
);
478 function renderHtmlDiff() {
479 global $wgOut, $wgParser, $wgDebugComments;
480 wfProfileIn( __METHOD__
);
482 $this->showDiffStyle();
484 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
485 #add deleted rev tag if needed
486 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
487 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
488 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
489 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
492 if( !$this->mNewRev
->isCurrent() ) {
493 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
499 if( is_object( $this->mOldRev
) ) {
500 $wgOut->setRevisionId( $this->mOldRev
->getId() );
503 $popts = $wgOut->parserOptions();
504 $oldTidy = $popts->setTidy( true );
505 $popts->setEditSection( false );
507 $parserOutput = $wgParser->parse( $this->mOldtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
508 $popts->setTidy( $oldTidy );
511 //$wgOut->addParserOutputNoText( $parserOutput );
512 $oldHtml = $parserOutput->getText();
513 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
516 if( is_object( $this->mNewRev
) ) {
517 $wgOut->setRevisionId( $this->mNewRev
->getId() );
520 $popts = $wgOut->parserOptions();
521 $oldTidy = $popts->setTidy( true );
523 $parserOutput = $wgParser->parse( $this->mNewtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
524 $popts->setTidy( $oldTidy );
526 $wgOut->addParserOutputNoText( $parserOutput );
527 $newHtml = $parserOutput->getText();
528 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
530 unset($parserOutput, $popts);
532 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
533 $differ->htmlDiff($oldHtml, $newHtml);
534 if ( $wgDebugComments ) {
535 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
538 wfProfileOut( __METHOD__
);
542 * Show the first revision of an article. Uses normal diff headers in
543 * contrast to normal "old revision" display style.
545 function showFirstRevision() {
546 global $wgOut, $wgUser;
547 wfProfileIn( __METHOD__
);
549 # Get article text from the DB
551 if ( ! $this->loadNewText() ) {
552 $t = $this->mTitle
->getPrefixedText();
553 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
554 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
555 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
556 wfProfileOut( __METHOD__
);
559 if ( $this->mNewRev
->isCurrent() ) {
560 $wgOut->setArticleFlag( true );
563 # Check if user is allowed to look at this page. If not, bail out.
565 if ( !$this->mTitle
->userCanRead() ) {
566 $wgOut->loginToUse();
568 wfProfileOut( __METHOD__
);
569 throw new MWException("Permission Error: you do not have access to view this page");
572 # Prepare the header box
574 $sk = $wgUser->getSkin();
576 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
580 $nextlink = '<br/>' . $sk->link(
582 wfMsgHtml( 'nextdiff' ),
584 'id' => 'differences-nextlink'
588 'oldid' => $this->mNewid
,
589 $this->htmlDiffArgument()
597 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
598 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
600 $wgOut->addHTML( $header );
602 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
603 $wgOut->setRobotPolicy( 'noindex,nofollow' );
605 wfProfileOut( __METHOD__
);
608 function htmlDiffArgument(){
609 global $wgEnableHtmlDiff;
610 if($wgEnableHtmlDiff){
612 return array( 'htmldiff' => 1 );
614 return array( 'htmldiff' => 0 );
622 * Get the diff text, send it to $wgOut
623 * Returns false if the diff could not be generated, otherwise returns true
625 function showDiff( $otitle, $ntitle ) {
627 $diff = $this->getDiff( $otitle, $ntitle );
628 if ( $diff === false ) {
629 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
632 $this->showDiffStyle();
633 $wgOut->addHTML( $diff );
639 * Add style sheets and supporting JS for diff display.
641 function showDiffStyle() {
642 global $wgStylePath, $wgStyleVersion, $wgOut;
643 $wgOut->addStyle( 'common/diff.css' );
645 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
646 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
650 * Get complete diff table, including header
652 * @param Title $otitle Old title
653 * @param Title $ntitle New title
656 function getDiff( $otitle, $ntitle ) {
657 $body = $this->getDiffBody();
658 if ( $body === false ) {
661 $multi = $this->getMultiNotice();
662 return $this->addHeader( $body, $otitle, $ntitle, $multi );
667 * Get the diff table body, without header
671 function getDiffBody() {
673 wfProfileIn( __METHOD__
);
674 $this->mCacheHit
= true;
675 // Check if the diff should be hidden from this user
676 if ( !$this->loadRevisionData() )
678 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
680 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
682 } else if ( $this->mOldRev
&& $this->mNewRev
&& $this->mOldRev
->getID() == $this->mNewRev
->getID() ) {
687 if ( $this->mOldid
&& $this->mNewid
) {
688 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
690 if ( !$this->mRefreshCache
) {
691 $difftext = $wgMemc->get( $key );
693 wfIncrStats( 'diff_cache_hit' );
694 $difftext = $this->localiseLineNumbers( $difftext );
695 $difftext .= "\n<!-- diff cache key $key -->\n";
696 wfProfileOut( __METHOD__
);
699 } // don't try to load but save the result
701 $this->mCacheHit
= false;
703 // Loadtext is permission safe, this just clears out the diff
704 if ( !$this->loadText() ) {
705 wfProfileOut( __METHOD__
);
709 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
711 // Save to cache for 7 days
712 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
713 wfIncrStats( 'diff_uncacheable' );
714 } else if ( $key !== false && $difftext !== false ) {
715 wfIncrStats( 'diff_cache_miss' );
716 $wgMemc->set( $key, $difftext, 7*86400 );
718 wfIncrStats( 'diff_uncacheable' );
720 // Replace line numbers with the text in the user's language
721 if ( $difftext !== false ) {
722 $difftext = $this->localiseLineNumbers( $difftext );
724 wfProfileOut( __METHOD__
);
729 * Make sure the proper modules are loaded before we try to
732 private function initDiffEngines() {
733 global $wgExternalDiffEngine;
734 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
735 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
736 wfSuppressWarnings();
737 dl( 'php_wikidiff.so' );
739 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
741 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
742 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
743 wfSuppressWarnings();
744 dl( 'php_wikidiff2.so' );
746 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
751 * Generate a diff, no caching
752 * $otext and $ntext must be already segmented
754 function generateDiffBody( $otext, $ntext ) {
755 global $wgExternalDiffEngine, $wgContLang;
757 $otext = str_replace( "\r\n", "\n", $otext );
758 $ntext = str_replace( "\r\n", "\n", $ntext );
760 $this->initDiffEngines();
762 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
763 # For historical reasons, external diff engine expects
764 # input text to be HTML-escaped already
765 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
766 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
767 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
768 $this->debug( 'wikidiff1' );
771 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
772 # Better external diff engine, the 2 may some day be dropped
773 # This one does the escaping and segmenting itself
774 wfProfileIn( 'wikidiff2_do_diff' );
775 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
776 $text .= $this->debug( 'wikidiff2' );
777 wfProfileOut( 'wikidiff2_do_diff' );
780 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
782 global $wgTmpDirectory;
783 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
784 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
786 $tempFile1 = fopen( $tempName1, "w" );
788 wfProfileOut( __METHOD__
);
791 $tempFile2 = fopen( $tempName2, "w" );
793 wfProfileOut( __METHOD__
);
796 fwrite( $tempFile1, $otext );
797 fwrite( $tempFile2, $ntext );
798 fclose( $tempFile1 );
799 fclose( $tempFile2 );
800 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
801 wfProfileIn( __METHOD__
. "-shellexec" );
802 $difftext = wfShellExec( $cmd );
803 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
804 wfProfileOut( __METHOD__
. "-shellexec" );
805 unlink( $tempName1 );
806 unlink( $tempName2 );
811 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
812 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
813 $diffs = new Diff( $ota, $nta );
814 $formatter = new TableDiffFormatter();
815 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
820 * Generate a debug comment indicating diff generating time,
821 * server node, and generator backend.
823 protected function debug( $generator="internal" ) {
824 global $wgShowHostnames;
825 $data = array( $generator );
826 if( $wgShowHostnames ) {
827 $data[] = wfHostname();
829 $data[] = wfTimestamp( TS_DB
);
830 return "<!-- diff generator: " .
839 * Replace line numbers with the text in the user's language
841 function localiseLineNumbers( $text ) {
842 return preg_replace_callback( '/<!--LINE (\d+)-->/',
843 array( &$this, 'localiseLineNumbersCb' ), $text );
846 function localiseLineNumbersCb( $matches ) {
848 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
853 * If there are revisions between the ones being compared, return a note saying so.
855 function getMultiNotice() {
856 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
859 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
860 // Comparing two different pages? Count would be meaningless.
864 $oldid = $this->mOldRev
->getId();
865 $newid = $this->mNewRev
->getId();
866 if ( $oldid > $newid ) {
867 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
870 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
874 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
879 * Add the header to a diff body
881 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
883 $header = "<table class='diff'>";
884 if( $diff ) { // Safari/Chrome show broken output if cols not used
886 <col class='diff-marker' />
887 <col class='diff-content' />
888 <col class='diff-marker' />
889 <col class='diff-content' />";
894 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
895 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
899 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
901 return $header . $diff . "</table>";
905 * Use specified text instead of loading from the database
907 function setText( $oldText, $newText ) {
908 $this->mOldtext
= $oldText;
909 $this->mNewtext
= $newText;
910 $this->mTextLoaded
= 2;
911 $this->mRevisionsLoaded
= true;
915 * Load revision metadata for the specified articles. If newid is 0, then compare
916 * the old article in oldid to the current article; if oldid is 0, then
917 * compare the current article to the immediately previous one (ignoring the
920 * If oldid is false, leave the corresponding revision object set
921 * to false. This is impossible via ordinary user input, and is provided for
924 function loadRevisionData() {
925 global $wgLang, $wgUser;
926 if ( $this->mRevisionsLoaded
) {
929 // Whether it succeeds or fails, we don't want to try again
930 $this->mRevisionsLoaded
= true;
933 // Load the new revision object
934 $this->mNewRev
= $this->mNewid
935 ? Revision
::newFromId( $this->mNewid
)
936 : Revision
::newFromTitle( $this->mTitle
);
937 if( !$this->mNewRev
instanceof Revision
)
940 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
941 $this->mNewid
= $this->mNewRev
->getId();
943 // Check if page is editable
944 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
946 // Set assorted variables
947 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
948 $dateofrev = $wgLang->date( $this->mNewRev
->getTimestamp(), true );
949 $timeofrev = $wgLang->time( $this->mNewRev
->getTimestamp(), true );
950 $this->mNewPage
= $this->mNewRev
->getTitle();
951 if( $this->mNewRev
->isCurrent() ) {
952 $newLink = $this->mNewPage
->escapeLocalUrl( array(
953 'oldid' => $this->mNewid
955 $this->mPagetitle
= htmlspecialchars( wfMsg(
961 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
965 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
966 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
968 $newLink = $this->mNewPage
->escapeLocalUrl( array(
969 'oldid' => $this->mNewid
971 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
973 'oldid' => $this->mNewid
975 $this->mPagetitle
= htmlspecialchars( wfMsg(
982 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
983 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
985 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
986 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
987 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
988 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
991 // Load the old revision object
992 $this->mOldRev
= false;
993 if( $this->mOldid
) {
994 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
995 } elseif ( $this->mOldid
=== 0 ) {
996 $rev = $this->mNewRev
->getPrevious();
998 $this->mOldid
= $rev->getId();
999 $this->mOldRev
= $rev;
1001 // No previous revision; mark to show as first-version only.
1002 $this->mOldid
= false;
1003 $this->mOldRev
= false;
1005 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
1007 if( is_null( $this->mOldRev
) ) {
1011 if ( $this->mOldRev
) {
1012 $this->mOldPage
= $this->mOldRev
->getTitle();
1014 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
1015 $dateofrev = $wgLang->date( $this->mOldRev
->getTimestamp(), true );
1016 $timeofrev = $wgLang->time( $this->mOldRev
->getTimestamp(), true );
1017 $oldLink = $this->mOldPage
->escapeLocalUrl( array(
1018 'oldid' => $this->mOldid
1020 $oldEdit = $this->mOldPage
->escapeLocalUrl( array(
1022 'oldid' => $this->mOldid
1024 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
1026 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
1027 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1028 // Add an "undo" link
1029 $newUndo = $this->mNewPage
->escapeLocalUrl( array(
1031 'undoafter' => $this->mOldid
,
1032 'undo' => $this->mNewid
1034 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
1035 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
1036 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1037 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
1040 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
1041 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
1042 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1043 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
1051 * Load the text of the revisions, as well as revision data.
1053 function loadText() {
1054 if ( $this->mTextLoaded
== 2 ) {
1057 // Whether it succeeds or fails, we don't want to try again
1058 $this->mTextLoaded
= 2;
1061 if ( !$this->loadRevisionData() ) {
1064 if ( $this->mOldRev
) {
1065 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1066 if ( $this->mOldtext
=== false ) {
1070 if ( $this->mNewRev
) {
1071 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1072 if ( $this->mNewtext
=== false ) {
1080 * Load the text of the new revision, not the old one
1082 function loadNewText() {
1083 if ( $this->mTextLoaded
>= 1 ) {
1086 $this->mTextLoaded
= 1;
1088 if ( !$this->loadRevisionData() ) {
1091 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1096 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
1098 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
1099 // You may copy this code freely under the conditions of the GPL.
1102 define('USE_ASSERTS', function_exists('assert'));
1107 * @ingroup DifferenceEngine
1114 function reverse() {
1115 trigger_error('pure virtual', E_USER_ERROR
);
1119 return $this->orig ?
sizeof($this->orig
) : 0;
1122 function nclosing() {
1123 return $this->closing ?
sizeof($this->closing
) : 0;
1130 * @ingroup DifferenceEngine
1132 class _DiffOp_Copy
extends _DiffOp
{
1135 function _DiffOp_Copy ($orig, $closing = false) {
1136 if (!is_array($closing))
1138 $this->orig
= $orig;
1139 $this->closing
= $closing;
1142 function reverse() {
1143 return new _DiffOp_Copy($this->closing
, $this->orig
);
1150 * @ingroup DifferenceEngine
1152 class _DiffOp_Delete
extends _DiffOp
{
1153 var $type = 'delete';
1155 function _DiffOp_Delete ($lines) {
1156 $this->orig
= $lines;
1157 $this->closing
= false;
1160 function reverse() {
1161 return new _DiffOp_Add($this->orig
);
1168 * @ingroup DifferenceEngine
1170 class _DiffOp_Add
extends _DiffOp
{
1173 function _DiffOp_Add ($lines) {
1174 $this->closing
= $lines;
1175 $this->orig
= false;
1178 function reverse() {
1179 return new _DiffOp_Delete($this->closing
);
1186 * @ingroup DifferenceEngine
1188 class _DiffOp_Change
extends _DiffOp
{
1189 var $type = 'change';
1191 function _DiffOp_Change ($orig, $closing) {
1192 $this->orig
= $orig;
1193 $this->closing
= $closing;
1196 function reverse() {
1197 return new _DiffOp_Change($this->closing
, $this->orig
);
1202 * Class used internally by Diff to actually compute the diffs.
1204 * The algorithm used here is mostly lifted from the perl module
1205 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1206 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1208 * More ideas are taken from:
1209 * http://www.ics.uci.edu/~eppstein/161/960229.html
1211 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1212 * diffutils-2.7, which can be found at:
1213 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1215 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1218 * Line length limits for robustness added by Tim Starling, 2005-08-31
1219 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1221 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1223 * @ingroup DifferenceEngine
1227 const MAX_XREF_LENGTH
= 10000;
1229 function diff ($from_lines, $to_lines){
1230 wfProfileIn( __METHOD__
);
1232 // Diff and store locally
1233 $this->diff_local($from_lines, $to_lines);
1235 // Merge edits when possible
1236 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1237 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1239 // Compute the edit operations.
1240 $n_from = sizeof($from_lines);
1241 $n_to = sizeof($to_lines);
1245 while ($xi < $n_from ||
$yi < $n_to) {
1246 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1247 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1249 // Skip matching "snake".
1251 while ( $xi < $n_from && $yi < $n_to
1252 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1253 $copy[] = $from_lines[$xi++
];
1257 $edits[] = new _DiffOp_Copy($copy);
1259 // Find deletes & adds.
1261 while ($xi < $n_from && $this->xchanged
[$xi])
1262 $delete[] = $from_lines[$xi++
];
1265 while ($yi < $n_to && $this->ychanged
[$yi])
1266 $add[] = $to_lines[$yi++
];
1268 if ($delete && $add)
1269 $edits[] = new _DiffOp_Change($delete, $add);
1271 $edits[] = new _DiffOp_Delete($delete);
1273 $edits[] = new _DiffOp_Add($add);
1275 wfProfileOut( __METHOD__
);
1279 function diff_local ($from_lines, $to_lines) {
1280 global $wgExternalDiffEngine;
1281 wfProfileIn( __METHOD__
);
1283 if($wgExternalDiffEngine == 'wikidiff3'){
1285 $wikidiff3 = new WikiDiff3();
1286 $wikidiff3->diff($from_lines, $to_lines);
1287 $this->xchanged
= $wikidiff3->removed
;
1288 $this->ychanged
= $wikidiff3->added
;
1292 $n_from = sizeof($from_lines);
1293 $n_to = sizeof($to_lines);
1294 $this->xchanged
= $this->ychanged
= array();
1295 $this->xv
= $this->yv
= array();
1296 $this->xind
= $this->yind
= array();
1298 unset($this->in_seq
);
1301 // Skip leading common lines.
1302 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1303 if ($from_lines[$skip] !== $to_lines[$skip])
1305 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1307 // Skip trailing common lines.
1308 $xi = $n_from; $yi = $n_to;
1309 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1310 if ($from_lines[$xi] !== $to_lines[$yi])
1312 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1315 // Ignore lines which do not exist in both files.
1316 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1317 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1320 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1321 $line = $to_lines[$yi];
1322 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1324 $yhash[$this->_line_hash($line)] = 1;
1325 $this->yv
[] = $line;
1326 $this->yind
[] = $yi;
1328 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1329 $line = $from_lines[$xi];
1330 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1332 $this->xv
[] = $line;
1333 $this->xind
[] = $xi;
1337 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1339 wfProfileOut( __METHOD__
);
1343 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1345 function _line_hash( $line ) {
1346 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1347 return md5( $line );
1353 /* Divide the Largest Common Subsequence (LCS) of the sequences
1354 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1357 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1358 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1359 * sub sequences. The first sub-sequence is contained in [X0, X1),
1360 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1361 * that (X0, Y0) == (XOFF, YOFF) and
1362 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1364 * This function assumes that the first lines of the specified portions
1365 * of the two files do not match, and likewise that the last lines do not
1366 * match. The caller must trim matching lines from the beginning and end
1367 * of the portions it is going to specify.
1369 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1372 if ($xlim - $xoff > $ylim - $yoff) {
1373 // Things seems faster (I'm not sure I understand why)
1374 // when the shortest sequence in X.
1376 list ($xoff, $xlim, $yoff, $ylim)
1377 = array( $yoff, $ylim, $xoff, $xlim);
1381 for ($i = $ylim - 1; $i >= $yoff; $i--)
1382 $ymatches[$this->xv
[$i]][] = $i;
1384 for ($i = $ylim - 1; $i >= $yoff; $i--)
1385 $ymatches[$this->yv
[$i]][] = $i;
1388 $this->seq
[0]= $yoff - 1;
1389 $this->in_seq
= array();
1390 $ymids[0] = array();
1392 $numer = $xlim - $xoff +
$nchunks - 1;
1394 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1396 for ($i = 0; $i <= $this->lcs
; $i++
)
1397 $ymids[$i][$chunk-1] = $this->seq
[$i];
1399 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1400 for ( ; $x < $x1; $x++
) {
1401 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1402 if (empty($ymatches[$line]))
1404 $matches = $ymatches[$line];
1406 while (list ($junk, $y) = each($matches))
1407 if (empty($this->in_seq
[$y])) {
1408 $k = $this->_lcs_pos($y);
1409 USE_ASSERTS
&& assert($k > 0);
1410 $ymids[$k] = $ymids[$k-1];
1413 while (list ( /* $junk */, $y) = each($matches)) {
1414 if ($y > $this->seq
[$k-1]) {
1415 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1416 // Optimization: this is a common case:
1417 // next match is just replacing previous match.
1418 $this->in_seq
[$this->seq
[$k]] = false;
1419 $this->seq
[$k] = $y;
1420 $this->in_seq
[$y] = 1;
1421 } else if (empty($this->in_seq
[$y])) {
1422 $k = $this->_lcs_pos($y);
1423 USE_ASSERTS
&& assert($k > 0);
1424 $ymids[$k] = $ymids[$k-1];
1430 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1431 $ymid = $ymids[$this->lcs
];
1432 for ($n = 0; $n < $nchunks - 1; $n++
) {
1433 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1434 $y1 = $ymid[$n] +
1;
1435 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1437 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1439 return array($this->lcs
, $seps);
1442 function _lcs_pos ($ypos) {
1444 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1445 $this->seq
[++
$this->lcs
] = $ypos;
1446 $this->in_seq
[$ypos] = 1;
1451 while ($beg < $end) {
1452 $mid = (int)(($beg +
$end) / 2);
1453 if ( $ypos > $this->seq
[$mid] )
1459 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1461 $this->in_seq
[$this->seq
[$end]] = false;
1462 $this->seq
[$end] = $ypos;
1463 $this->in_seq
[$ypos] = 1;
1467 /* Find LCS of two sequences.
1469 * The results are recorded in the vectors $this->{x,y}changed[], by
1470 * storing a 1 in the element for each line that is an insertion
1471 * or deletion (ie. is not in the LCS).
1473 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1475 * Note that XLIM, YLIM are exclusive bounds.
1476 * All line numbers are origin-0 and discarded lines are not counted.
1478 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1479 // Slide down the bottom initial diagonal.
1480 while ($xoff < $xlim && $yoff < $ylim
1481 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1486 // Slide up the top initial diagonal.
1487 while ($xlim > $xoff && $ylim > $yoff
1488 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1493 if ($xoff == $xlim ||
$yoff == $ylim)
1496 // This is ad hoc but seems to work well.
1497 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1498 //$nchunks = max(2,min(8,(int)$nchunks));
1499 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1501 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1505 // X and Y sequences have no common subsequence:
1506 // mark all changed.
1507 while ($yoff < $ylim)
1508 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1509 while ($xoff < $xlim)
1510 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1512 // Use the partitions to split this problem into subproblems.
1515 while ($pt2 = next($seps)) {
1516 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1522 /* Adjust inserts/deletes of identical lines to join changes
1523 * as much as possible.
1525 * We do something when a run of changed lines include a
1526 * line at one end and has an excluded, identical line at the other.
1527 * We are free to choose which identical line is included.
1528 * `compareseq' usually chooses the one at the beginning,
1529 * but usually it is cleaner to consider the following identical line
1530 * to be the "change".
1532 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1534 function _shift_boundaries ($lines, &$changed, $other_changed) {
1535 wfProfileIn( __METHOD__
);
1539 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1540 $len = sizeof($lines);
1541 $other_len = sizeof($other_changed);
1545 * Scan forwards to find beginning of another run of changes.
1546 * Also keep track of the corresponding point in the other file.
1548 * Throughout this code, $i and $j are adjusted together so that
1549 * the first $i elements of $changed and the first $j elements
1550 * of $other_changed both contain the same number of zeros
1551 * (unchanged lines).
1552 * Furthermore, $j is always kept so that $j == $other_len or
1553 * $other_changed[$j] == false.
1555 while ($j < $other_len && $other_changed[$j])
1558 while ($i < $len && ! $changed[$i]) {
1559 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1561 while ($j < $other_len && $other_changed[$j])
1570 // Find the end of this run of changes.
1571 while (++
$i < $len && $changed[$i])
1576 * Record the length of this run of changes, so that
1577 * we can later determine whether the run has grown.
1579 $runlength = $i - $start;
1582 * Move the changed region back, so long as the
1583 * previous unchanged line matches the last changed one.
1584 * This merges with previous changed regions.
1586 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1587 $changed[--$start] = 1;
1588 $changed[--$i] = false;
1589 while ($start > 0 && $changed[$start - 1])
1591 USE_ASSERTS
&& assert('$j > 0');
1592 while ($other_changed[--$j])
1594 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1598 * Set CORRESPONDING to the end of the changed run, at the last
1599 * point where it corresponds to a changed run in the other file.
1600 * CORRESPONDING == LEN means no such point has been found.
1602 $corresponding = $j < $other_len ?
$i : $len;
1605 * Move the changed region forward, so long as the
1606 * first changed line matches the following unchanged one.
1607 * This merges with following changed regions.
1608 * Do this second, so that if there are no merges,
1609 * the changed region is moved forward as far as possible.
1611 while ($i < $len && $lines[$start] == $lines[$i]) {
1612 $changed[$start++
] = false;
1614 while ($i < $len && $changed[$i])
1617 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1619 if ($j < $other_len && $other_changed[$j]) {
1620 $corresponding = $i;
1621 while ($j < $other_len && $other_changed[$j])
1625 } while ($runlength != $i - $start);
1628 * If possible, move the fully-merged run of changes
1629 * back to a corresponding run in the other file.
1631 while ($corresponding < $i) {
1632 $changed[--$start] = 1;
1634 USE_ASSERTS
&& assert('$j > 0');
1635 while ($other_changed[--$j])
1637 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1640 wfProfileOut( __METHOD__
);
1645 * Class representing a 'diff' between two sequences of strings.
1648 * @ingroup DifferenceEngine
1656 * Computes diff between sequences of strings.
1658 * @param $from_lines array An array of strings.
1659 * (Typically these are lines from a file.)
1660 * @param $to_lines array An array of strings.
1662 function Diff($from_lines, $to_lines) {
1663 $eng = new _DiffEngine
;
1664 $this->edits
= $eng->diff($from_lines, $to_lines);
1665 //$this->_check($from_lines, $to_lines);
1669 * Compute reversed Diff.
1673 * $diff = new Diff($lines1, $lines2);
1674 * $rev = $diff->reverse();
1675 * @return object A Diff object representing the inverse of the
1678 function reverse () {
1680 $rev->edits
= array();
1681 foreach ($this->edits
as $edit) {
1682 $rev->edits
[] = $edit->reverse();
1688 * Check for empty diff.
1690 * @return bool True iff two sequences were identical.
1692 function isEmpty () {
1693 foreach ($this->edits
as $edit) {
1694 if ($edit->type
!= 'copy')
1701 * Compute the length of the Longest Common Subsequence (LCS).
1703 * This is mostly for diagnostic purposed.
1705 * @return int The length of the LCS.
1709 foreach ($this->edits
as $edit) {
1710 if ($edit->type
== 'copy')
1711 $lcs +
= sizeof($edit->orig
);
1717 * Get the original set of lines.
1719 * This reconstructs the $from_lines parameter passed to the
1722 * @return array The original sequence of strings.
1727 foreach ($this->edits
as $edit) {
1729 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1735 * Get the closing set of lines.
1737 * This reconstructs the $to_lines parameter passed to the
1740 * @return array The sequence of strings.
1742 function closing() {
1745 foreach ($this->edits
as $edit) {
1747 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1753 * Check a Diff for validity.
1755 * This is here only for debugging purposes.
1757 function _check ($from_lines, $to_lines) {
1758 wfProfileIn( __METHOD__
);
1759 if (serialize($from_lines) != serialize($this->orig()))
1760 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1761 if (serialize($to_lines) != serialize($this->closing()))
1762 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1764 $rev = $this->reverse();
1765 if (serialize($to_lines) != serialize($rev->orig()))
1766 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1767 if (serialize($from_lines) != serialize($rev->closing()))
1768 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1772 foreach ($this->edits
as $edit) {
1773 if ( $prevtype == $edit->type
)
1774 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1775 $prevtype = $edit->type
;
1778 $lcs = $this->lcs();
1779 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1780 wfProfileOut( __METHOD__
);
1785 * @todo document, bad name.
1787 * @ingroup DifferenceEngine
1789 class MappedDiff
extends Diff
1794 * Computes diff between sequences of strings.
1796 * This can be used to compute things like
1797 * case-insensitve diffs, or diffs which ignore
1798 * changes in white-space.
1800 * @param $from_lines array An array of strings.
1801 * (Typically these are lines from a file.)
1803 * @param $to_lines array An array of strings.
1805 * @param $mapped_from_lines array This array should
1806 * have the same size number of elements as $from_lines.
1807 * The elements in $mapped_from_lines and
1808 * $mapped_to_lines are what is actually compared
1809 * when computing the diff.
1811 * @param $mapped_to_lines array This array should
1812 * have the same number of elements as $to_lines.
1814 function MappedDiff($from_lines, $to_lines,
1815 $mapped_from_lines, $mapped_to_lines) {
1816 wfProfileIn( __METHOD__
);
1818 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1819 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1821 $this->Diff($mapped_from_lines, $mapped_to_lines);
1824 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1825 $orig = &$this->edits
[$i]->orig
;
1826 if (is_array($orig)) {
1827 $orig = array_slice($from_lines, $xi, sizeof($orig));
1828 $xi +
= sizeof($orig);
1831 $closing = &$this->edits
[$i]->closing
;
1832 if (is_array($closing)) {
1833 $closing = array_slice($to_lines, $yi, sizeof($closing));
1834 $yi +
= sizeof($closing);
1837 wfProfileOut( __METHOD__
);
1842 * A class to format Diffs
1844 * This class formats the diff in classic diff format.
1845 * It is intended that this class be customized via inheritance,
1846 * to obtain fancier outputs.
1849 * @ingroup DifferenceEngine
1851 class DiffFormatter
{
1853 * Number of leading context "lines" to preserve.
1855 * This should be left at zero for this class, but subclasses
1856 * may want to set this to other values.
1858 var $leading_context_lines = 0;
1861 * Number of trailing context "lines" to preserve.
1863 * This should be left at zero for this class, but subclasses
1864 * may want to set this to other values.
1866 var $trailing_context_lines = 0;
1871 * @param $diff object A Diff object.
1872 * @return string The formatted output.
1874 function format($diff) {
1875 wfProfileIn( __METHOD__
);
1881 $nlead = $this->leading_context_lines
;
1882 $ntrail = $this->trailing_context_lines
;
1884 $this->_start_diff();
1886 foreach ($diff->edits
as $edit) {
1887 if ($edit->type
== 'copy') {
1888 if (is_array($block)) {
1889 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1894 $context = array_slice($edit->orig
, 0, $ntrail);
1895 $block[] = new _DiffOp_Copy($context);
1897 $this->_block($x0, $ntrail +
$xi - $x0,
1898 $y0, $ntrail +
$yi - $y0,
1903 $context = $edit->orig
;
1906 if (! is_array($block)) {
1907 $context = array_slice($context, sizeof($context) - $nlead);
1908 $x0 = $xi - sizeof($context);
1909 $y0 = $yi - sizeof($context);
1912 $block[] = new _DiffOp_Copy($context);
1918 $xi +
= sizeof($edit->orig
);
1920 $yi +
= sizeof($edit->closing
);
1923 if (is_array($block))
1924 $this->_block($x0, $xi - $x0,
1928 $end = $this->_end_diff();
1929 wfProfileOut( __METHOD__
);
1933 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1934 wfProfileIn( __METHOD__
);
1935 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1936 foreach ($edits as $edit) {
1937 if ($edit->type
== 'copy')
1938 $this->_context($edit->orig
);
1939 elseif ($edit->type
== 'add')
1940 $this->_added($edit->closing
);
1941 elseif ($edit->type
== 'delete')
1942 $this->_deleted($edit->orig
);
1943 elseif ($edit->type
== 'change')
1944 $this->_changed($edit->orig
, $edit->closing
);
1946 trigger_error('Unknown edit type', E_USER_ERROR
);
1948 $this->_end_block();
1949 wfProfileOut( __METHOD__
);
1952 function _start_diff() {
1956 function _end_diff() {
1957 $val = ob_get_contents();
1962 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1964 $xbeg .= "," . ($xbeg +
$xlen - 1);
1966 $ybeg .= "," . ($ybeg +
$ylen - 1);
1968 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1971 function _start_block($header) {
1972 echo $header . "\n";
1975 function _end_block() {
1978 function _lines($lines, $prefix = ' ') {
1979 foreach ($lines as $line)
1980 echo "$prefix $line\n";
1983 function _context($lines) {
1984 $this->_lines($lines);
1987 function _added($lines) {
1988 $this->_lines($lines, '>');
1990 function _deleted($lines) {
1991 $this->_lines($lines, '<');
1994 function _changed($orig, $closing) {
1995 $this->_deleted($orig);
1997 $this->_added($closing);
2002 * A formatter that outputs unified diffs
2003 * @ingroup DifferenceEngine
2006 class UnifiedDiffFormatter
extends DiffFormatter
{
2007 var $leading_context_lines = 2;
2008 var $trailing_context_lines = 2;
2010 function _added($lines) {
2011 $this->_lines($lines, '+');
2013 function _deleted($lines) {
2014 $this->_lines($lines, '-');
2016 function _changed($orig, $closing) {
2017 $this->_deleted($orig);
2018 $this->_added($closing);
2020 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
2021 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
2026 * A pseudo-formatter that just passes along the Diff::$edits array
2027 * @ingroup DifferenceEngine
2029 class ArrayDiffFormatter
extends DiffFormatter
{
2030 function format($diff) {
2034 foreach($diff->edits
as $edit)
2035 switch($edit->type
) {
2037 foreach($edit->closing
as $l) {
2041 'newline' => $newline++
2046 foreach($edit->orig
as $l) {
2048 'action' => 'delete',
2050 'oldline' => $oldline++
,
2055 foreach($edit->orig
as $i => $l) {
2057 'action' => 'change',
2059 'new' => @$edit->closing
[$i],
2060 'oldline' => $oldline++
,
2061 'newline' => $newline++
,
2066 $oldline +
= count($edit->orig
);
2067 $newline +
= count($edit->orig
);
2074 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
2078 define('NBSP', ' '); // iso-8859-x non-breaking space.
2083 * @ingroup DifferenceEngine
2085 class _HWLDF_WordAccumulator
{
2086 function _HWLDF_WordAccumulator () {
2087 $this->_lines
= array();
2093 function _flushGroup ($new_tag) {
2094 if ($this->_group
!== '') {
2095 if ($this->_tag
== 'ins')
2096 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
2097 htmlspecialchars ( $this->_group
) . '</ins>';
2098 elseif ($this->_tag
== 'del')
2099 $this->_line
.= '<del class="diffchange diffchange-inline">' .
2100 htmlspecialchars ( $this->_group
) . '</del>';
2102 $this->_line
.= htmlspecialchars ( $this->_group
);
2105 $this->_tag
= $new_tag;
2108 function _flushLine ($new_tag) {
2109 $this->_flushGroup($new_tag);
2110 if ($this->_line
!= '')
2111 array_push ( $this->_lines
, $this->_line
);
2113 # make empty lines visible by inserting an NBSP
2114 array_push ( $this->_lines
, NBSP
);
2118 function addWords ($words, $tag = '') {
2119 if ($tag != $this->_tag
)
2120 $this->_flushGroup($tag);
2122 foreach ($words as $word) {
2123 // new-line should only come as first char of word.
2126 if ($word[0] == "\n") {
2127 $this->_flushLine($tag);
2128 $word = substr($word, 1);
2130 assert(!strstr($word, "\n"));
2131 $this->_group
.= $word;
2135 function getLines() {
2136 $this->_flushLine('~done');
2137 return $this->_lines
;
2144 * @ingroup DifferenceEngine
2146 class WordLevelDiff
extends MappedDiff
{
2147 const MAX_LINE_LENGTH
= 10000;
2149 function WordLevelDiff ($orig_lines, $closing_lines) {
2150 wfProfileIn( __METHOD__
);
2152 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
2153 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
2155 $this->MappedDiff($orig_words, $closing_words,
2156 $orig_stripped, $closing_stripped);
2157 wfProfileOut( __METHOD__
);
2160 function _split($lines) {
2161 wfProfileIn( __METHOD__
);
2164 $stripped = array();
2166 foreach ( $lines as $line ) {
2167 # If the line is too long, just pretend the entire line is one big word
2168 # This prevents resource exhaustion problems
2175 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2177 $stripped[] = $line;
2180 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2183 $words = array_merge( $words, $m[0] );
2184 $stripped = array_merge( $stripped, $m[1] );
2188 wfProfileOut( __METHOD__
);
2189 return array($words, $stripped);
2193 wfProfileIn( __METHOD__
);
2194 $orig = new _HWLDF_WordAccumulator
;
2196 foreach ($this->edits
as $edit) {
2197 if ($edit->type
== 'copy')
2198 $orig->addWords($edit->orig
);
2199 elseif ($edit->orig
)
2200 $orig->addWords($edit->orig
, 'del');
2202 $lines = $orig->getLines();
2203 wfProfileOut( __METHOD__
);
2207 function closing () {
2208 wfProfileIn( __METHOD__
);
2209 $closing = new _HWLDF_WordAccumulator
;
2211 foreach ($this->edits
as $edit) {
2212 if ($edit->type
== 'copy')
2213 $closing->addWords($edit->closing
);
2214 elseif ($edit->closing
)
2215 $closing->addWords($edit->closing
, 'ins');
2217 $lines = $closing->getLines();
2218 wfProfileOut( __METHOD__
);
2224 * Wikipedia Table style diff formatter.
2227 * @ingroup DifferenceEngine
2229 class TableDiffFormatter
extends DiffFormatter
{
2230 function TableDiffFormatter() {
2231 $this->leading_context_lines
= 2;
2232 $this->trailing_context_lines
= 2;
2235 public static function escapeWhiteSpace( $msg ) {
2236 $msg = preg_replace( '/^ /m', ' ', $msg );
2237 $msg = preg_replace( '/ $/m', ' ', $msg );
2238 $msg = preg_replace( '/ /', ' ', $msg );
2242 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2243 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2244 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2248 function _start_block( $header ) {
2252 function _end_block() {
2255 function _lines( $lines, $prefix=' ', $color='white' ) {
2258 # HTML-escape parameter before calling this
2259 function addedLine( $line ) {
2260 return $this->wrapLine( '+', 'diff-addedline', $line );
2263 # HTML-escape parameter before calling this
2264 function deletedLine( $line ) {
2265 return $this->wrapLine( '-', 'diff-deletedline', $line );
2268 # HTML-escape parameter before calling this
2269 function contextLine( $line ) {
2270 return $this->wrapLine( ' ', 'diff-context', $line );
2273 private function wrapLine( $marker, $class, $line ) {
2274 if( $line !== '' ) {
2275 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2276 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2278 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2281 function emptyLine() {
2282 return '<td colspan="2"> </td>';
2285 function _added( $lines ) {
2286 foreach ($lines as $line) {
2287 echo '<tr>' . $this->emptyLine() .
2288 $this->addedLine( '<ins class="diffchange">' .
2289 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2293 function _deleted($lines) {
2294 foreach ($lines as $line) {
2295 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2296 htmlspecialchars ( $line ) . '</del>' ) .
2297 $this->emptyLine() . "</tr>\n";
2301 function _context( $lines ) {
2302 foreach ($lines as $line) {
2304 $this->contextLine( htmlspecialchars ( $line ) ) .
2305 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2309 function _changed( $orig, $closing ) {
2310 wfProfileIn( __METHOD__
);
2312 $diff = new WordLevelDiff( $orig, $closing );
2313 $del = $diff->orig();
2314 $add = $diff->closing();
2316 # Notice that WordLevelDiff returns HTML-escaped output.
2317 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2319 while ( $line = array_shift( $del ) ) {
2320 $aline = array_shift( $add );
2321 echo '<tr>' . $this->deletedLine( $line ) .
2322 $this->addedLine( $aline ) . "</tr>\n";
2324 foreach ($add as $line) { # If any leftovers
2325 echo '<tr>' . $this->emptyLine() .
2326 $this->addedLine( $line ) . "</tr>\n";
2328 wfProfileOut( __METHOD__
);