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?
34 * Set this to true to add debug info to the HTML output.
35 * Warning: this may cause RSS readers to spuriously mark articles as "new"
38 var $enableDebugComment = false;
40 // If true, line X is not displayed when X is 1, for example to increase
41 // readability and conserve space with many small diffs.
42 protected $mReducedLineNumbers = false;
44 protected $unhide = false;
49 * @param $titleObj Title object that the diff is associated with
50 * @param $old Integer: old ID we want to show and diff with.
51 * @param $new String: either 'prev' or 'next'.
52 * @param $rcid Integer: ??? FIXME (default 0)
53 * @param $refreshCache boolean If set, refreshes the diff cache
54 * @param $htmldiff boolean If set, output using HTMLDiff instead of raw wikicode diff
55 * @param $unhide boolean If set, allow viewing deleted revs
57 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0,
58 $refreshCache = false, $htmldiff = false, $unhide = false )
61 $this->mTitle
= $titleObj;
64 $this->mTitle
= $wgTitle;
66 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
68 if ( 'prev' === $new ) {
69 # Show diff between revision $old and the previous one.
70 # Get previous one from DB.
71 $this->mNewid
= intval($old);
72 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
73 } elseif ( 'next' === $new ) {
74 # Show diff between revision $old and the next one.
75 # Get next one from DB.
76 $this->mOldid
= intval($old);
77 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
78 if ( false === $this->mNewid
) {
79 # if no result, NewId points to the newest old revision. The only newer
80 # revision is cur, which is "0".
84 $this->mOldid
= intval($old);
85 $this->mNewid
= intval($new);
86 wfRunHooks( 'NewDifferenceEngine', array(&$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new) );
88 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
89 $this->mRefreshCache
= $refreshCache;
90 $this->htmldiff
= $htmldiff;
91 $this->unhide
= $unhide;
94 function setReducedLineNumbers( $value = true ) {
95 $this->mReducedLineNumbers
= $value;
102 function wasCacheHit() {
103 return $this->mCacheHit
;
106 function getOldid() {
107 return $this->mOldid
;
110 function getNewid() {
111 return $this->mNewid
;
114 function showDiffPage( $diffOnly = false ) {
115 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
116 wfProfileIn( __METHOD__
);
119 # If external diffs are enabled both globally and for the user,
120 # we'll use the application/x-external-editor interface to call
121 # an external diff tool like kompare, kdiff3, etc.
122 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
123 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
125 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
126 $url1=$this->mTitle
->getFullURL( array(
128 'oldid' => $this->mOldid
130 $url2=$this->mTitle
->getFullURL( array(
132 'oldid' => $this->mNewid
134 $special=$wgLang->getNsText(NS_SPECIAL
);
139 Script={$wgServer}{$wgScript}
140 Special namespace={$special}
154 $wgOut->setArticleFlag( false );
155 if ( !$this->loadRevisionData() ) {
156 $t = $this->mTitle
->getPrefixedText();
157 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
158 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
159 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
160 wfProfileOut( __METHOD__
);
164 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
166 if ( $this->mNewRev
->isCurrent() ) {
167 $wgOut->setArticleFlag( true );
170 # mOldid is false if the difference engine is called with a "vague" query for
171 # a diff between a version V and its previous version V' AND the version V
172 # is the first version of that article. In that case, V' does not exist.
173 if ( $this->mOldid
=== false ) {
174 $this->showFirstRevision();
175 $this->renderNewRevision(); // should we respect $diffOnly here or not?
176 wfProfileOut( __METHOD__
);
180 $wgOut->suppressQuickbar();
182 $oldTitle = $this->mOldPage
->getPrefixedText();
183 $newTitle = $this->mNewPage
->getPrefixedText();
184 if( $oldTitle == $newTitle ) {
185 $wgOut->setPageTitle( $newTitle );
187 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
189 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
190 $wgOut->setRobotPolicy( 'noindex,nofollow' );
192 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
193 $wgOut->loginToUse();
196 wfProfileOut( __METHOD__
);
200 $sk = $wgUser->getSkin();
202 // Check if page is editable
203 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
204 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
205 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
210 // Prepare a change patrol link, if applicable
211 if( $wgUseRCPatrol && $this->mTitle
->userCan('patrol') ) {
212 // If we've been given an explicit change identifier, use it; saves time
213 if( $this->mRcidMarkPatrolled
) {
214 $rcid = $this->mRcidMarkPatrolled
;
215 $rc = RecentChange
::newFromId( $rcid );
216 // Already patrolled?
217 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ?
$rcid : 0;
219 // Look for an unpatrolled change corresponding to this diff
220 $db = wfGetDB( DB_SLAVE
);
221 $change = RecentChange
::newFromConds(
223 // Redundant user,timestamp condition so we can use the existing index
224 'rc_user_text' => $this->mNewRev
->getRawUserText(),
225 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
226 'rc_this_oldid' => $this->mNewid
,
227 'rc_last_oldid' => $this->mOldid
,
232 if( $change instanceof RecentChange
) {
233 $rcid = $change->mAttribs
['rc_id'];
234 $this->mRcidMarkPatrolled
= $rcid;
242 $patrol = ' <span class="patrollink">[' . $sk->link(
244 wfMsgHtml( 'markaspatrolleddiff' ),
247 'action' => 'markpatrolled',
262 # Carry over 'diffonly' param via navigation links
263 if( $diffOnly != $wgUser->getBoolOption('diffonly') ) {
264 $query['diffonly'] = $diffOnly;
267 $htmldiffarg = $this->htmlDiffArgument();
270 $query['htmldiff'] = $htmldiffarg['htmldiff'];
273 # Make "previous revision link"
274 $query['diff'] = 'prev';
275 $query['oldid'] = $this->mOldid
;
277 $prevlink = $sk->link(
279 wfMsgHtml( 'previousdiff' ),
281 'id' => 'differences-prevlink'
289 # Make "next revision link"
290 $query['diff'] = 'next';
291 $query['oldid'] = $this->mNewid
;
293 if( $this->mNewRev
->isCurrent() ) {
294 $nextlink = ' ';
296 $nextlink = $sk->link(
298 wfMsgHtml( 'nextdiff' ),
300 'id' => 'differences-nextlink'
313 if( $this->mOldRev
->isMinor() ) {
314 $oldminor = ChangesList
::flag( 'minor' );
316 if( $this->mNewRev
->isMinor() ) {
317 $newminor = ChangesList
::flag( 'minor' );
320 $rdel = ''; $ldel = '';
321 if( $wgUser->isAllowed( 'deleterevision' ) ) {
322 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
323 // If revision was hidden from sysops
324 $ldel = Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), '(' . wfMsgHtml( 'rev-delundel' ) . ')' );
327 'type' => 'revision',
328 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
329 'ids' => $this->mOldRev
->getId()
331 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
333 $ldel = " $ldel ";
334 if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
335 // If revision was hidden from sysops
336 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
339 'type' => 'revision',
340 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
341 'ids' => $this->mNewRev
->getId()
343 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
345 $rdel = " $rdel ";
348 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
349 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
350 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
351 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
352 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
353 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
354 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
355 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
357 # Check if this user can see the revisions
358 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
)
359 && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
360 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
)
361 ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
362 # Output the diff if allowed...
363 if( $deleted && (!$this->unhide ||
!$allowed) ) {
364 $this->showDiffStyle();
365 $multi = $this->getMultiNotice();
366 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
368 # Give explanation for why revision is not visible
369 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
370 array( 'rev-deleted-no-diff' ) );
372 # Give explanation and add a link to view the diff...
373 $link = $this->mTitle
->getFullUrl( array(
374 'diff' => $this->mNewid
,
375 'oldid' => $this->mOldid
,
378 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
379 array( 'rev-deleted-unhide-diff', $link ) );
381 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
382 $multi = $this->getMultiNotice();
383 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
385 wfMsgHtml( 'wikicodecomparison' ),
387 'id' => 'differences-switchtype'
390 'diff' => $this->mNewid
,
391 'oldid' => $this->mOldid
,
399 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
400 $this->renderHtmlDiff();
402 if( $wgEnableHtmlDiff ) {
403 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
405 wfMsgHtml( 'visualcomparison' ),
407 'id' => 'differences-switchtype'
410 'diff' => $this->mNewid
,
411 'oldid' => $this->mOldid
,
420 $this->showDiff( $oldHeader, $newHeader );
422 $this->renderNewRevision();
425 wfProfileOut( __METHOD__
);
429 * Show the new revision of the page.
431 function renderNewRevision() {
432 global $wgOut, $wgUser;
433 wfProfileIn( __METHOD__
);
435 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
436 # Add deleted rev tag if needed
437 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
438 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
439 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
440 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
443 if( !$this->mNewRev
->isCurrent() ) {
444 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
447 $this->loadNewText();
448 if( is_object( $this->mNewRev
) ) {
449 $wgOut->setRevisionId( $this->mNewRev
->getId() );
452 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
453 // Stolen from Article::view --AG 2007-10-11
454 // Give hooks a chance to customise the output
455 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
456 // Wrap the whole lot in a <pre> and don't parse
458 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
459 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
460 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
461 $wgOut->addHTML( "\n</pre>\n" );
464 $wgOut->addWikiTextTidy( $this->mNewtext
);
467 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
468 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
470 # Add redundant patrol link on bottom...
471 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
472 $sk = $wgUser->getSkin();
474 "<div class='patrollink'>[" . $sk->link(
476 wfMsgHtml( 'markaspatrolleddiff' ),
479 'action' => 'markpatrolled',
480 'rcid' => $this->mRcidMarkPatrolled
486 wfProfileOut( __METHOD__
);
490 function renderHtmlDiff() {
491 global $wgOut, $wgParser, $wgDebugComments;
492 wfProfileIn( __METHOD__
);
494 $this->showDiffStyle();
496 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
497 #add deleted rev tag if needed
498 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
499 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
500 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
501 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
504 if( !$this->mNewRev
->isCurrent() ) {
505 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
511 if( is_object( $this->mOldRev
) ) {
512 $wgOut->setRevisionId( $this->mOldRev
->getId() );
515 $popts = $wgOut->parserOptions();
516 $oldTidy = $popts->setTidy( true );
517 $popts->setEditSection( false );
519 $parserOutput = $wgParser->parse( $this->mOldtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
520 $popts->setTidy( $oldTidy );
523 //$wgOut->addParserOutputNoText( $parserOutput );
524 $oldHtml = $parserOutput->getText();
525 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
528 if( is_object( $this->mNewRev
) ) {
529 $wgOut->setRevisionId( $this->mNewRev
->getId() );
532 $popts = $wgOut->parserOptions();
533 $oldTidy = $popts->setTidy( true );
535 $parserOutput = $wgParser->parse( $this->mNewtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
536 $popts->setTidy( $oldTidy );
538 $wgOut->addParserOutputNoText( $parserOutput );
539 $newHtml = $parserOutput->getText();
540 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
542 unset($parserOutput, $popts);
544 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
545 $differ->htmlDiff($oldHtml, $newHtml);
546 if ( $wgDebugComments ) {
547 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
550 wfProfileOut( __METHOD__
);
554 * Show the first revision of an article. Uses normal diff headers in
555 * contrast to normal "old revision" display style.
557 function showFirstRevision() {
558 global $wgOut, $wgUser;
559 wfProfileIn( __METHOD__
);
561 # Get article text from the DB
563 if ( ! $this->loadNewText() ) {
564 $t = $this->mTitle
->getPrefixedText();
565 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
566 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
567 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
568 wfProfileOut( __METHOD__
);
571 if ( $this->mNewRev
->isCurrent() ) {
572 $wgOut->setArticleFlag( true );
575 # Check if user is allowed to look at this page. If not, bail out.
577 if ( !$this->mTitle
->userCanRead() ) {
578 $wgOut->loginToUse();
580 wfProfileOut( __METHOD__
);
581 throw new MWException("Permission Error: you do not have access to view this page");
584 # Prepare the header box
586 $sk = $wgUser->getSkin();
588 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
592 $nextlink = '<br/>' . $sk->link(
594 wfMsgHtml( 'nextdiff' ),
596 'id' => 'differences-nextlink'
600 'oldid' => $this->mNewid
,
601 $this->htmlDiffArgument()
609 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
610 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
612 $wgOut->addHTML( $header );
614 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
615 $wgOut->setRobotPolicy( 'noindex,nofollow' );
617 wfProfileOut( __METHOD__
);
620 function htmlDiffArgument(){
621 global $wgEnableHtmlDiff;
622 if($wgEnableHtmlDiff){
624 return array( 'htmldiff' => 1 );
626 return array( 'htmldiff' => 0 );
634 * Get the diff text, send it to $wgOut
635 * Returns false if the diff could not be generated, otherwise returns true
637 function showDiff( $otitle, $ntitle ) {
639 $diff = $this->getDiff( $otitle, $ntitle );
640 if ( $diff === false ) {
641 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
644 $this->showDiffStyle();
645 $wgOut->addHTML( $diff );
651 * Add style sheets and supporting JS for diff display.
653 function showDiffStyle() {
654 global $wgStylePath, $wgStyleVersion, $wgOut;
655 $wgOut->addStyle( 'common/diff.css' );
657 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
658 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
662 * Get complete diff table, including header
664 * @param Title $otitle Old title
665 * @param Title $ntitle New title
668 function getDiff( $otitle, $ntitle ) {
669 $body = $this->getDiffBody();
670 if ( $body === false ) {
673 $multi = $this->getMultiNotice();
674 return $this->addHeader( $body, $otitle, $ntitle, $multi );
679 * Get the diff table body, without header
683 function getDiffBody() {
685 wfProfileIn( __METHOD__
);
686 $this->mCacheHit
= true;
687 // Check if the diff should be hidden from this user
688 if ( !$this->loadRevisionData() )
690 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
692 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
694 } else if ( $this->mOldRev
&& $this->mNewRev
&& $this->mOldRev
->getID() == $this->mNewRev
->getID() ) {
699 if ( $this->mOldid
&& $this->mNewid
) {
700 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
702 if ( !$this->mRefreshCache
) {
703 $difftext = $wgMemc->get( $key );
705 wfIncrStats( 'diff_cache_hit' );
706 $difftext = $this->localiseLineNumbers( $difftext );
707 $difftext .= "\n<!-- diff cache key $key -->\n";
708 wfProfileOut( __METHOD__
);
711 } // don't try to load but save the result
713 $this->mCacheHit
= false;
715 // Loadtext is permission safe, this just clears out the diff
716 if ( !$this->loadText() ) {
717 wfProfileOut( __METHOD__
);
721 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
723 // Save to cache for 7 days
724 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
725 wfIncrStats( 'diff_uncacheable' );
726 } else if ( $key !== false && $difftext !== false ) {
727 wfIncrStats( 'diff_cache_miss' );
728 $wgMemc->set( $key, $difftext, 7*86400 );
730 wfIncrStats( 'diff_uncacheable' );
732 // Replace line numbers with the text in the user's language
733 if ( $difftext !== false ) {
734 $difftext = $this->localiseLineNumbers( $difftext );
736 wfProfileOut( __METHOD__
);
741 * Make sure the proper modules are loaded before we try to
744 private function initDiffEngines() {
745 global $wgExternalDiffEngine;
746 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
747 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
748 wfSuppressWarnings();
749 dl( 'php_wikidiff.so' );
751 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
753 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
754 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
755 wfSuppressWarnings();
756 dl( 'php_wikidiff2.so' );
758 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
763 * Generate a diff, no caching
764 * $otext and $ntext must be already segmented
766 function generateDiffBody( $otext, $ntext ) {
767 global $wgExternalDiffEngine, $wgContLang;
769 $otext = str_replace( "\r\n", "\n", $otext );
770 $ntext = str_replace( "\r\n", "\n", $ntext );
772 $this->initDiffEngines();
774 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
775 # For historical reasons, external diff engine expects
776 # input text to be HTML-escaped already
777 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
778 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
779 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
780 $this->debug( 'wikidiff1' );
783 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
784 # Better external diff engine, the 2 may some day be dropped
785 # This one does the escaping and segmenting itself
786 wfProfileIn( 'wikidiff2_do_diff' );
787 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
788 $text .= $this->debug( 'wikidiff2' );
789 wfProfileOut( 'wikidiff2_do_diff' );
792 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
794 global $wgTmpDirectory;
795 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
796 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
798 $tempFile1 = fopen( $tempName1, "w" );
800 wfProfileOut( __METHOD__
);
803 $tempFile2 = fopen( $tempName2, "w" );
805 wfProfileOut( __METHOD__
);
808 fwrite( $tempFile1, $otext );
809 fwrite( $tempFile2, $ntext );
810 fclose( $tempFile1 );
811 fclose( $tempFile2 );
812 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
813 wfProfileIn( __METHOD__
. "-shellexec" );
814 $difftext = wfShellExec( $cmd );
815 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
816 wfProfileOut( __METHOD__
. "-shellexec" );
817 unlink( $tempName1 );
818 unlink( $tempName2 );
823 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
824 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
825 $diffs = new Diff( $ota, $nta );
826 $formatter = new TableDiffFormatter();
827 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
832 * Generate a debug comment indicating diff generating time,
833 * server node, and generator backend.
835 protected function debug( $generator="internal" ) {
836 global $wgShowHostnames;
837 if ( !$this->enableDebugComment
) {
840 $data = array( $generator );
841 if( $wgShowHostnames ) {
842 $data[] = wfHostname();
844 $data[] = wfTimestamp( TS_DB
);
845 return "<!-- diff generator: " .
854 * Replace line numbers with the text in the user's language
856 function localiseLineNumbers( $text ) {
857 return preg_replace_callback( '/<!--LINE (\d+)-->/',
858 array( &$this, 'localiseLineNumbersCb' ), $text );
861 function localiseLineNumbersCb( $matches ) {
863 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
864 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
869 * If there are revisions between the ones being compared, return a note saying so.
871 function getMultiNotice() {
872 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
875 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
876 // Comparing two different pages? Count would be meaningless.
880 $oldid = $this->mOldRev
->getId();
881 $newid = $this->mNewRev
->getId();
882 if ( $oldid > $newid ) {
883 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
886 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
890 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
895 * Add the header to a diff body
897 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
899 $header = "<table class='diff'>";
900 if( $diff ) { // Safari/Chrome show broken output if cols not used
902 <col class='diff-marker' />
903 <col class='diff-content' />
904 <col class='diff-marker' />
905 <col class='diff-content' />";
910 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
911 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
915 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
917 return $header . $diff . "</table>";
921 * Use specified text instead of loading from the database
923 function setText( $oldText, $newText ) {
924 $this->mOldtext
= $oldText;
925 $this->mNewtext
= $newText;
926 $this->mTextLoaded
= 2;
927 $this->mRevisionsLoaded
= true;
931 * Load revision metadata for the specified articles. If newid is 0, then compare
932 * the old article in oldid to the current article; if oldid is 0, then
933 * compare the current article to the immediately previous one (ignoring the
936 * If oldid is false, leave the corresponding revision object set
937 * to false. This is impossible via ordinary user input, and is provided for
940 function loadRevisionData() {
941 global $wgLang, $wgUser;
942 if ( $this->mRevisionsLoaded
) {
945 // Whether it succeeds or fails, we don't want to try again
946 $this->mRevisionsLoaded
= true;
949 // Load the new revision object
950 $this->mNewRev
= $this->mNewid
951 ? Revision
::newFromId( $this->mNewid
)
952 : Revision
::newFromTitle( $this->mTitle
);
953 if( !$this->mNewRev
instanceof Revision
)
956 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
957 $this->mNewid
= $this->mNewRev
->getId();
959 // Check if page is editable
960 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
962 // Set assorted variables
963 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
964 $dateofrev = $wgLang->date( $this->mNewRev
->getTimestamp(), true );
965 $timeofrev = $wgLang->time( $this->mNewRev
->getTimestamp(), true );
966 $this->mNewPage
= $this->mNewRev
->getTitle();
967 if( $this->mNewRev
->isCurrent() ) {
968 $newLink = $this->mNewPage
->escapeLocalUrl( array(
969 'oldid' => $this->mNewid
971 $this->mPagetitle
= htmlspecialchars( wfMsg(
977 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
981 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
982 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
984 $newLink = $this->mNewPage
->escapeLocalUrl( array(
985 'oldid' => $this->mNewid
987 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
989 'oldid' => $this->mNewid
991 $this->mPagetitle
= htmlspecialchars( wfMsg(
998 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
999 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1001 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
1002 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
1003 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
1004 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
1007 // Load the old revision object
1008 $this->mOldRev
= false;
1009 if( $this->mOldid
) {
1010 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1011 } elseif ( $this->mOldid
=== 0 ) {
1012 $rev = $this->mNewRev
->getPrevious();
1014 $this->mOldid
= $rev->getId();
1015 $this->mOldRev
= $rev;
1017 // No previous revision; mark to show as first-version only.
1018 $this->mOldid
= false;
1019 $this->mOldRev
= false;
1021 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
1023 if( is_null( $this->mOldRev
) ) {
1027 if ( $this->mOldRev
) {
1028 $this->mOldPage
= $this->mOldRev
->getTitle();
1030 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
1031 $dateofrev = $wgLang->date( $this->mOldRev
->getTimestamp(), true );
1032 $timeofrev = $wgLang->time( $this->mOldRev
->getTimestamp(), true );
1033 $oldLink = $this->mOldPage
->escapeLocalUrl( array(
1034 'oldid' => $this->mOldid
1036 $oldEdit = $this->mOldPage
->escapeLocalUrl( array(
1038 'oldid' => $this->mOldid
1040 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
1042 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
1043 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1044 // Add an "undo" link
1045 $newUndo = $this->mNewPage
->escapeLocalUrl( array(
1047 'undoafter' => $this->mOldid
,
1048 'undo' => $this->mNewid
1050 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
1051 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
1052 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1053 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
1056 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
1057 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
1058 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1059 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
1067 * Load the text of the revisions, as well as revision data.
1069 function loadText() {
1070 if ( $this->mTextLoaded
== 2 ) {
1073 // Whether it succeeds or fails, we don't want to try again
1074 $this->mTextLoaded
= 2;
1077 if ( !$this->loadRevisionData() ) {
1080 if ( $this->mOldRev
) {
1081 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1082 if ( $this->mOldtext
=== false ) {
1086 if ( $this->mNewRev
) {
1087 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1088 if ( $this->mNewtext
=== false ) {
1096 * Load the text of the new revision, not the old one
1098 function loadNewText() {
1099 if ( $this->mTextLoaded
>= 1 ) {
1102 $this->mTextLoaded
= 1;
1104 if ( !$this->loadRevisionData() ) {
1107 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1112 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
1114 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
1115 // You may copy this code freely under the conditions of the GPL.
1118 define('USE_ASSERTS', function_exists('assert'));
1123 * @ingroup DifferenceEngine
1130 function reverse() {
1131 trigger_error('pure virtual', E_USER_ERROR
);
1135 return $this->orig ?
sizeof($this->orig
) : 0;
1138 function nclosing() {
1139 return $this->closing ?
sizeof($this->closing
) : 0;
1146 * @ingroup DifferenceEngine
1148 class _DiffOp_Copy
extends _DiffOp
{
1151 function _DiffOp_Copy ($orig, $closing = false) {
1152 if (!is_array($closing))
1154 $this->orig
= $orig;
1155 $this->closing
= $closing;
1158 function reverse() {
1159 return new _DiffOp_Copy($this->closing
, $this->orig
);
1166 * @ingroup DifferenceEngine
1168 class _DiffOp_Delete
extends _DiffOp
{
1169 var $type = 'delete';
1171 function _DiffOp_Delete ($lines) {
1172 $this->orig
= $lines;
1173 $this->closing
= false;
1176 function reverse() {
1177 return new _DiffOp_Add($this->orig
);
1184 * @ingroup DifferenceEngine
1186 class _DiffOp_Add
extends _DiffOp
{
1189 function _DiffOp_Add ($lines) {
1190 $this->closing
= $lines;
1191 $this->orig
= false;
1194 function reverse() {
1195 return new _DiffOp_Delete($this->closing
);
1202 * @ingroup DifferenceEngine
1204 class _DiffOp_Change
extends _DiffOp
{
1205 var $type = 'change';
1207 function _DiffOp_Change ($orig, $closing) {
1208 $this->orig
= $orig;
1209 $this->closing
= $closing;
1212 function reverse() {
1213 return new _DiffOp_Change($this->closing
, $this->orig
);
1218 * Class used internally by Diff to actually compute the diffs.
1220 * The algorithm used here is mostly lifted from the perl module
1221 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1222 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1224 * More ideas are taken from:
1225 * http://www.ics.uci.edu/~eppstein/161/960229.html
1227 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1228 * diffutils-2.7, which can be found at:
1229 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1231 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1234 * Line length limits for robustness added by Tim Starling, 2005-08-31
1235 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1237 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1239 * @ingroup DifferenceEngine
1243 const MAX_XREF_LENGTH
= 10000;
1245 function diff ($from_lines, $to_lines){
1246 wfProfileIn( __METHOD__
);
1248 // Diff and store locally
1249 $this->diff_local($from_lines, $to_lines);
1251 // Merge edits when possible
1252 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1253 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1255 // Compute the edit operations.
1256 $n_from = sizeof($from_lines);
1257 $n_to = sizeof($to_lines);
1261 while ($xi < $n_from ||
$yi < $n_to) {
1262 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1263 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1265 // Skip matching "snake".
1267 while ( $xi < $n_from && $yi < $n_to
1268 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1269 $copy[] = $from_lines[$xi++
];
1273 $edits[] = new _DiffOp_Copy($copy);
1275 // Find deletes & adds.
1277 while ($xi < $n_from && $this->xchanged
[$xi])
1278 $delete[] = $from_lines[$xi++
];
1281 while ($yi < $n_to && $this->ychanged
[$yi])
1282 $add[] = $to_lines[$yi++
];
1284 if ($delete && $add)
1285 $edits[] = new _DiffOp_Change($delete, $add);
1287 $edits[] = new _DiffOp_Delete($delete);
1289 $edits[] = new _DiffOp_Add($add);
1291 wfProfileOut( __METHOD__
);
1295 function diff_local ($from_lines, $to_lines) {
1296 global $wgExternalDiffEngine;
1297 wfProfileIn( __METHOD__
);
1299 if($wgExternalDiffEngine == 'wikidiff3'){
1301 $wikidiff3 = new WikiDiff3();
1302 $wikidiff3->diff($from_lines, $to_lines);
1303 $this->xchanged
= $wikidiff3->removed
;
1304 $this->ychanged
= $wikidiff3->added
;
1308 $n_from = sizeof($from_lines);
1309 $n_to = sizeof($to_lines);
1310 $this->xchanged
= $this->ychanged
= array();
1311 $this->xv
= $this->yv
= array();
1312 $this->xind
= $this->yind
= array();
1314 unset($this->in_seq
);
1317 // Skip leading common lines.
1318 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1319 if ($from_lines[$skip] !== $to_lines[$skip])
1321 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1323 // Skip trailing common lines.
1324 $xi = $n_from; $yi = $n_to;
1325 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1326 if ($from_lines[$xi] !== $to_lines[$yi])
1328 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1331 // Ignore lines which do not exist in both files.
1332 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1333 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1336 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1337 $line = $to_lines[$yi];
1338 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1340 $yhash[$this->_line_hash($line)] = 1;
1341 $this->yv
[] = $line;
1342 $this->yind
[] = $yi;
1344 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1345 $line = $from_lines[$xi];
1346 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1348 $this->xv
[] = $line;
1349 $this->xind
[] = $xi;
1353 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1355 wfProfileOut( __METHOD__
);
1359 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1361 function _line_hash( $line ) {
1362 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1363 return md5( $line );
1369 /* Divide the Largest Common Subsequence (LCS) of the sequences
1370 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1373 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1374 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1375 * sub sequences. The first sub-sequence is contained in [X0, X1),
1376 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1377 * that (X0, Y0) == (XOFF, YOFF) and
1378 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1380 * This function assumes that the first lines of the specified portions
1381 * of the two files do not match, and likewise that the last lines do not
1382 * match. The caller must trim matching lines from the beginning and end
1383 * of the portions it is going to specify.
1385 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1388 if ($xlim - $xoff > $ylim - $yoff) {
1389 // Things seems faster (I'm not sure I understand why)
1390 // when the shortest sequence in X.
1392 list ($xoff, $xlim, $yoff, $ylim)
1393 = array( $yoff, $ylim, $xoff, $xlim);
1397 for ($i = $ylim - 1; $i >= $yoff; $i--)
1398 $ymatches[$this->xv
[$i]][] = $i;
1400 for ($i = $ylim - 1; $i >= $yoff; $i--)
1401 $ymatches[$this->yv
[$i]][] = $i;
1404 $this->seq
[0]= $yoff - 1;
1405 $this->in_seq
= array();
1406 $ymids[0] = array();
1408 $numer = $xlim - $xoff +
$nchunks - 1;
1410 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1412 for ($i = 0; $i <= $this->lcs
; $i++
)
1413 $ymids[$i][$chunk-1] = $this->seq
[$i];
1415 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1416 for ( ; $x < $x1; $x++
) {
1417 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1418 if (empty($ymatches[$line]))
1420 $matches = $ymatches[$line];
1422 while (list ($junk, $y) = each($matches))
1423 if (empty($this->in_seq
[$y])) {
1424 $k = $this->_lcs_pos($y);
1425 USE_ASSERTS
&& assert($k > 0);
1426 $ymids[$k] = $ymids[$k-1];
1429 while (list ( /* $junk */, $y) = each($matches)) {
1430 if ($y > $this->seq
[$k-1]) {
1431 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1432 // Optimization: this is a common case:
1433 // next match is just replacing previous match.
1434 $this->in_seq
[$this->seq
[$k]] = false;
1435 $this->seq
[$k] = $y;
1436 $this->in_seq
[$y] = 1;
1437 } else if (empty($this->in_seq
[$y])) {
1438 $k = $this->_lcs_pos($y);
1439 USE_ASSERTS
&& assert($k > 0);
1440 $ymids[$k] = $ymids[$k-1];
1446 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1447 $ymid = $ymids[$this->lcs
];
1448 for ($n = 0; $n < $nchunks - 1; $n++
) {
1449 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1450 $y1 = $ymid[$n] +
1;
1451 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1453 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1455 return array($this->lcs
, $seps);
1458 function _lcs_pos ($ypos) {
1460 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1461 $this->seq
[++
$this->lcs
] = $ypos;
1462 $this->in_seq
[$ypos] = 1;
1467 while ($beg < $end) {
1468 $mid = (int)(($beg +
$end) / 2);
1469 if ( $ypos > $this->seq
[$mid] )
1475 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1477 $this->in_seq
[$this->seq
[$end]] = false;
1478 $this->seq
[$end] = $ypos;
1479 $this->in_seq
[$ypos] = 1;
1483 /* Find LCS of two sequences.
1485 * The results are recorded in the vectors $this->{x,y}changed[], by
1486 * storing a 1 in the element for each line that is an insertion
1487 * or deletion (ie. is not in the LCS).
1489 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1491 * Note that XLIM, YLIM are exclusive bounds.
1492 * All line numbers are origin-0 and discarded lines are not counted.
1494 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1495 // Slide down the bottom initial diagonal.
1496 while ($xoff < $xlim && $yoff < $ylim
1497 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1502 // Slide up the top initial diagonal.
1503 while ($xlim > $xoff && $ylim > $yoff
1504 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1509 if ($xoff == $xlim ||
$yoff == $ylim)
1512 // This is ad hoc but seems to work well.
1513 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1514 //$nchunks = max(2,min(8,(int)$nchunks));
1515 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1517 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1521 // X and Y sequences have no common subsequence:
1522 // mark all changed.
1523 while ($yoff < $ylim)
1524 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1525 while ($xoff < $xlim)
1526 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1528 // Use the partitions to split this problem into subproblems.
1531 while ($pt2 = next($seps)) {
1532 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1538 /* Adjust inserts/deletes of identical lines to join changes
1539 * as much as possible.
1541 * We do something when a run of changed lines include a
1542 * line at one end and has an excluded, identical line at the other.
1543 * We are free to choose which identical line is included.
1544 * `compareseq' usually chooses the one at the beginning,
1545 * but usually it is cleaner to consider the following identical line
1546 * to be the "change".
1548 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1550 function _shift_boundaries ($lines, &$changed, $other_changed) {
1551 wfProfileIn( __METHOD__
);
1555 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1556 $len = sizeof($lines);
1557 $other_len = sizeof($other_changed);
1561 * Scan forwards to find beginning of another run of changes.
1562 * Also keep track of the corresponding point in the other file.
1564 * Throughout this code, $i and $j are adjusted together so that
1565 * the first $i elements of $changed and the first $j elements
1566 * of $other_changed both contain the same number of zeros
1567 * (unchanged lines).
1568 * Furthermore, $j is always kept so that $j == $other_len or
1569 * $other_changed[$j] == false.
1571 while ($j < $other_len && $other_changed[$j])
1574 while ($i < $len && ! $changed[$i]) {
1575 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1577 while ($j < $other_len && $other_changed[$j])
1586 // Find the end of this run of changes.
1587 while (++
$i < $len && $changed[$i])
1592 * Record the length of this run of changes, so that
1593 * we can later determine whether the run has grown.
1595 $runlength = $i - $start;
1598 * Move the changed region back, so long as the
1599 * previous unchanged line matches the last changed one.
1600 * This merges with previous changed regions.
1602 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1603 $changed[--$start] = 1;
1604 $changed[--$i] = false;
1605 while ($start > 0 && $changed[$start - 1])
1607 USE_ASSERTS
&& assert('$j > 0');
1608 while ($other_changed[--$j])
1610 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1614 * Set CORRESPONDING to the end of the changed run, at the last
1615 * point where it corresponds to a changed run in the other file.
1616 * CORRESPONDING == LEN means no such point has been found.
1618 $corresponding = $j < $other_len ?
$i : $len;
1621 * Move the changed region forward, so long as the
1622 * first changed line matches the following unchanged one.
1623 * This merges with following changed regions.
1624 * Do this second, so that if there are no merges,
1625 * the changed region is moved forward as far as possible.
1627 while ($i < $len && $lines[$start] == $lines[$i]) {
1628 $changed[$start++
] = false;
1630 while ($i < $len && $changed[$i])
1633 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1635 if ($j < $other_len && $other_changed[$j]) {
1636 $corresponding = $i;
1637 while ($j < $other_len && $other_changed[$j])
1641 } while ($runlength != $i - $start);
1644 * If possible, move the fully-merged run of changes
1645 * back to a corresponding run in the other file.
1647 while ($corresponding < $i) {
1648 $changed[--$start] = 1;
1650 USE_ASSERTS
&& assert('$j > 0');
1651 while ($other_changed[--$j])
1653 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1656 wfProfileOut( __METHOD__
);
1661 * Class representing a 'diff' between two sequences of strings.
1664 * @ingroup DifferenceEngine
1672 * Computes diff between sequences of strings.
1674 * @param $from_lines array An array of strings.
1675 * (Typically these are lines from a file.)
1676 * @param $to_lines array An array of strings.
1678 function Diff($from_lines, $to_lines) {
1679 $eng = new _DiffEngine
;
1680 $this->edits
= $eng->diff($from_lines, $to_lines);
1681 //$this->_check($from_lines, $to_lines);
1685 * Compute reversed Diff.
1689 * $diff = new Diff($lines1, $lines2);
1690 * $rev = $diff->reverse();
1691 * @return object A Diff object representing the inverse of the
1694 function reverse () {
1696 $rev->edits
= array();
1697 foreach ($this->edits
as $edit) {
1698 $rev->edits
[] = $edit->reverse();
1704 * Check for empty diff.
1706 * @return bool True iff two sequences were identical.
1708 function isEmpty () {
1709 foreach ($this->edits
as $edit) {
1710 if ($edit->type
!= 'copy')
1717 * Compute the length of the Longest Common Subsequence (LCS).
1719 * This is mostly for diagnostic purposed.
1721 * @return int The length of the LCS.
1725 foreach ($this->edits
as $edit) {
1726 if ($edit->type
== 'copy')
1727 $lcs +
= sizeof($edit->orig
);
1733 * Get the original set of lines.
1735 * This reconstructs the $from_lines parameter passed to the
1738 * @return array The original sequence of strings.
1743 foreach ($this->edits
as $edit) {
1745 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1751 * Get the closing set of lines.
1753 * This reconstructs the $to_lines parameter passed to the
1756 * @return array The sequence of strings.
1758 function closing() {
1761 foreach ($this->edits
as $edit) {
1763 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1769 * Check a Diff for validity.
1771 * This is here only for debugging purposes.
1773 function _check ($from_lines, $to_lines) {
1774 wfProfileIn( __METHOD__
);
1775 if (serialize($from_lines) != serialize($this->orig()))
1776 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1777 if (serialize($to_lines) != serialize($this->closing()))
1778 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1780 $rev = $this->reverse();
1781 if (serialize($to_lines) != serialize($rev->orig()))
1782 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1783 if (serialize($from_lines) != serialize($rev->closing()))
1784 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1788 foreach ($this->edits
as $edit) {
1789 if ( $prevtype == $edit->type
)
1790 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1791 $prevtype = $edit->type
;
1794 $lcs = $this->lcs();
1795 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1796 wfProfileOut( __METHOD__
);
1801 * @todo document, bad name.
1803 * @ingroup DifferenceEngine
1805 class MappedDiff
extends Diff
1810 * Computes diff between sequences of strings.
1812 * This can be used to compute things like
1813 * case-insensitve diffs, or diffs which ignore
1814 * changes in white-space.
1816 * @param $from_lines array An array of strings.
1817 * (Typically these are lines from a file.)
1819 * @param $to_lines array An array of strings.
1821 * @param $mapped_from_lines array This array should
1822 * have the same size number of elements as $from_lines.
1823 * The elements in $mapped_from_lines and
1824 * $mapped_to_lines are what is actually compared
1825 * when computing the diff.
1827 * @param $mapped_to_lines array This array should
1828 * have the same number of elements as $to_lines.
1830 function MappedDiff($from_lines, $to_lines,
1831 $mapped_from_lines, $mapped_to_lines) {
1832 wfProfileIn( __METHOD__
);
1834 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1835 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1837 $this->Diff($mapped_from_lines, $mapped_to_lines);
1840 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1841 $orig = &$this->edits
[$i]->orig
;
1842 if (is_array($orig)) {
1843 $orig = array_slice($from_lines, $xi, sizeof($orig));
1844 $xi +
= sizeof($orig);
1847 $closing = &$this->edits
[$i]->closing
;
1848 if (is_array($closing)) {
1849 $closing = array_slice($to_lines, $yi, sizeof($closing));
1850 $yi +
= sizeof($closing);
1853 wfProfileOut( __METHOD__
);
1858 * A class to format Diffs
1860 * This class formats the diff in classic diff format.
1861 * It is intended that this class be customized via inheritance,
1862 * to obtain fancier outputs.
1865 * @ingroup DifferenceEngine
1867 class DiffFormatter
{
1869 * Number of leading context "lines" to preserve.
1871 * This should be left at zero for this class, but subclasses
1872 * may want to set this to other values.
1874 var $leading_context_lines = 0;
1877 * Number of trailing context "lines" to preserve.
1879 * This should be left at zero for this class, but subclasses
1880 * may want to set this to other values.
1882 var $trailing_context_lines = 0;
1887 * @param $diff object A Diff object.
1888 * @return string The formatted output.
1890 function format($diff) {
1891 wfProfileIn( __METHOD__
);
1897 $nlead = $this->leading_context_lines
;
1898 $ntrail = $this->trailing_context_lines
;
1900 $this->_start_diff();
1902 foreach ($diff->edits
as $edit) {
1903 if ($edit->type
== 'copy') {
1904 if (is_array($block)) {
1905 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1910 $context = array_slice($edit->orig
, 0, $ntrail);
1911 $block[] = new _DiffOp_Copy($context);
1913 $this->_block($x0, $ntrail +
$xi - $x0,
1914 $y0, $ntrail +
$yi - $y0,
1919 $context = $edit->orig
;
1922 if (! is_array($block)) {
1923 $context = array_slice($context, sizeof($context) - $nlead);
1924 $x0 = $xi - sizeof($context);
1925 $y0 = $yi - sizeof($context);
1928 $block[] = new _DiffOp_Copy($context);
1934 $xi +
= sizeof($edit->orig
);
1936 $yi +
= sizeof($edit->closing
);
1939 if (is_array($block))
1940 $this->_block($x0, $xi - $x0,
1944 $end = $this->_end_diff();
1945 wfProfileOut( __METHOD__
);
1949 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1950 wfProfileIn( __METHOD__
);
1951 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1952 foreach ($edits as $edit) {
1953 if ($edit->type
== 'copy')
1954 $this->_context($edit->orig
);
1955 elseif ($edit->type
== 'add')
1956 $this->_added($edit->closing
);
1957 elseif ($edit->type
== 'delete')
1958 $this->_deleted($edit->orig
);
1959 elseif ($edit->type
== 'change')
1960 $this->_changed($edit->orig
, $edit->closing
);
1962 trigger_error('Unknown edit type', E_USER_ERROR
);
1964 $this->_end_block();
1965 wfProfileOut( __METHOD__
);
1968 function _start_diff() {
1972 function _end_diff() {
1973 $val = ob_get_contents();
1978 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1980 $xbeg .= "," . ($xbeg +
$xlen - 1);
1982 $ybeg .= "," . ($ybeg +
$ylen - 1);
1984 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1987 function _start_block($header) {
1988 echo $header . "\n";
1991 function _end_block() {
1994 function _lines($lines, $prefix = ' ') {
1995 foreach ($lines as $line)
1996 echo "$prefix $line\n";
1999 function _context($lines) {
2000 $this->_lines($lines);
2003 function _added($lines) {
2004 $this->_lines($lines, '>');
2006 function _deleted($lines) {
2007 $this->_lines($lines, '<');
2010 function _changed($orig, $closing) {
2011 $this->_deleted($orig);
2013 $this->_added($closing);
2018 * A formatter that outputs unified diffs
2019 * @ingroup DifferenceEngine
2022 class UnifiedDiffFormatter
extends DiffFormatter
{
2023 var $leading_context_lines = 2;
2024 var $trailing_context_lines = 2;
2026 function _added($lines) {
2027 $this->_lines($lines, '+');
2029 function _deleted($lines) {
2030 $this->_lines($lines, '-');
2032 function _changed($orig, $closing) {
2033 $this->_deleted($orig);
2034 $this->_added($closing);
2036 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
2037 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
2042 * A pseudo-formatter that just passes along the Diff::$edits array
2043 * @ingroup DifferenceEngine
2045 class ArrayDiffFormatter
extends DiffFormatter
{
2046 function format($diff) {
2050 foreach($diff->edits
as $edit)
2051 switch($edit->type
) {
2053 foreach($edit->closing
as $l) {
2057 'newline' => $newline++
2062 foreach($edit->orig
as $l) {
2064 'action' => 'delete',
2066 'oldline' => $oldline++
,
2071 foreach($edit->orig
as $i => $l) {
2073 'action' => 'change',
2075 'new' => @$edit->closing
[$i],
2076 'oldline' => $oldline++
,
2077 'newline' => $newline++
,
2082 $oldline +
= count($edit->orig
);
2083 $newline +
= count($edit->orig
);
2090 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
2094 define('NBSP', ' '); // iso-8859-x non-breaking space.
2099 * @ingroup DifferenceEngine
2101 class _HWLDF_WordAccumulator
{
2102 function _HWLDF_WordAccumulator () {
2103 $this->_lines
= array();
2109 function _flushGroup ($new_tag) {
2110 if ($this->_group
!== '') {
2111 if ($this->_tag
== 'ins')
2112 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
2113 htmlspecialchars ( $this->_group
) . '</ins>';
2114 elseif ($this->_tag
== 'del')
2115 $this->_line
.= '<del class="diffchange diffchange-inline">' .
2116 htmlspecialchars ( $this->_group
) . '</del>';
2118 $this->_line
.= htmlspecialchars ( $this->_group
);
2121 $this->_tag
= $new_tag;
2124 function _flushLine ($new_tag) {
2125 $this->_flushGroup($new_tag);
2126 if ($this->_line
!= '')
2127 array_push ( $this->_lines
, $this->_line
);
2129 # make empty lines visible by inserting an NBSP
2130 array_push ( $this->_lines
, NBSP
);
2134 function addWords ($words, $tag = '') {
2135 if ($tag != $this->_tag
)
2136 $this->_flushGroup($tag);
2138 foreach ($words as $word) {
2139 // new-line should only come as first char of word.
2142 if ($word[0] == "\n") {
2143 $this->_flushLine($tag);
2144 $word = substr($word, 1);
2146 assert(!strstr($word, "\n"));
2147 $this->_group
.= $word;
2151 function getLines() {
2152 $this->_flushLine('~done');
2153 return $this->_lines
;
2160 * @ingroup DifferenceEngine
2162 class WordLevelDiff
extends MappedDiff
{
2163 const MAX_LINE_LENGTH
= 10000;
2165 function WordLevelDiff ($orig_lines, $closing_lines) {
2166 wfProfileIn( __METHOD__
);
2168 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
2169 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
2171 $this->MappedDiff($orig_words, $closing_words,
2172 $orig_stripped, $closing_stripped);
2173 wfProfileOut( __METHOD__
);
2176 function _split($lines) {
2177 wfProfileIn( __METHOD__
);
2180 $stripped = array();
2182 foreach ( $lines as $line ) {
2183 # If the line is too long, just pretend the entire line is one big word
2184 # This prevents resource exhaustion problems
2191 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2193 $stripped[] = $line;
2196 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2199 $words = array_merge( $words, $m[0] );
2200 $stripped = array_merge( $stripped, $m[1] );
2204 wfProfileOut( __METHOD__
);
2205 return array($words, $stripped);
2209 wfProfileIn( __METHOD__
);
2210 $orig = new _HWLDF_WordAccumulator
;
2212 foreach ($this->edits
as $edit) {
2213 if ($edit->type
== 'copy')
2214 $orig->addWords($edit->orig
);
2215 elseif ($edit->orig
)
2216 $orig->addWords($edit->orig
, 'del');
2218 $lines = $orig->getLines();
2219 wfProfileOut( __METHOD__
);
2223 function closing () {
2224 wfProfileIn( __METHOD__
);
2225 $closing = new _HWLDF_WordAccumulator
;
2227 foreach ($this->edits
as $edit) {
2228 if ($edit->type
== 'copy')
2229 $closing->addWords($edit->closing
);
2230 elseif ($edit->closing
)
2231 $closing->addWords($edit->closing
, 'ins');
2233 $lines = $closing->getLines();
2234 wfProfileOut( __METHOD__
);
2240 * Wikipedia Table style diff formatter.
2243 * @ingroup DifferenceEngine
2245 class TableDiffFormatter
extends DiffFormatter
{
2246 function TableDiffFormatter() {
2247 $this->leading_context_lines
= 2;
2248 $this->trailing_context_lines
= 2;
2251 public static function escapeWhiteSpace( $msg ) {
2252 $msg = preg_replace( '/^ /m', ' ', $msg );
2253 $msg = preg_replace( '/ $/m', ' ', $msg );
2254 $msg = preg_replace( '/ /', ' ', $msg );
2258 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2259 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2260 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2264 function _start_block( $header ) {
2268 function _end_block() {
2271 function _lines( $lines, $prefix=' ', $color='white' ) {
2274 # HTML-escape parameter before calling this
2275 function addedLine( $line ) {
2276 return $this->wrapLine( '+', 'diff-addedline', $line );
2279 # HTML-escape parameter before calling this
2280 function deletedLine( $line ) {
2281 return $this->wrapLine( '-', 'diff-deletedline', $line );
2284 # HTML-escape parameter before calling this
2285 function contextLine( $line ) {
2286 return $this->wrapLine( ' ', 'diff-context', $line );
2289 private function wrapLine( $marker, $class, $line ) {
2290 if( $line !== '' ) {
2291 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2292 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2294 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2297 function emptyLine() {
2298 return '<td colspan="2"> </td>';
2301 function _added( $lines ) {
2302 foreach ($lines as $line) {
2303 echo '<tr>' . $this->emptyLine() .
2304 $this->addedLine( '<ins class="diffchange">' .
2305 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2309 function _deleted($lines) {
2310 foreach ($lines as $line) {
2311 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2312 htmlspecialchars ( $line ) . '</del>' ) .
2313 $this->emptyLine() . "</tr>\n";
2317 function _context( $lines ) {
2318 foreach ($lines as $line) {
2320 $this->contextLine( htmlspecialchars ( $line ) ) .
2321 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2325 function _changed( $orig, $closing ) {
2326 wfProfileIn( __METHOD__
);
2328 $diff = new WordLevelDiff( $orig, $closing );
2329 $del = $diff->orig();
2330 $add = $diff->closing();
2332 # Notice that WordLevelDiff returns HTML-escaped output.
2333 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2335 while ( $line = array_shift( $del ) ) {
2336 $aline = array_shift( $add );
2337 echo '<tr>' . $this->deletedLine( $line ) .
2338 $this->addedLine( $aline ) . "</tr>\n";
2340 foreach ($add as $line) { # If any leftovers
2341 echo '<tr>' . $this->emptyLine() .
2342 $this->addedLine( $line ) . "</tr>\n";
2344 wfProfileOut( __METHOD__
);