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 if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
320 // If revision was hidden from sysops
321 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
324 'type' => 'revision',
325 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
326 'ids' => $this->mNewRev
->getId()
328 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
330 $rdel = " $rdel ";
333 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
334 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
335 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
336 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
337 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
338 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
339 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
340 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
342 # Check if this user can see the revisions
343 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
)
344 && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
345 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
)
346 ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
347 # Output the diff if allowed...
348 if( $deleted && (!$this->unhide ||
!$allowed) ) {
349 $this->showDiffStyle();
350 $multi = $this->getMultiNotice();
351 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
353 # Give explanation for why revision is not visible
354 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
355 array( 'rev-deleted-no-diff' ) );
357 # Give explanation and add a link to view the diff...
358 $link = $this->mTitle
->getFullUrl( array(
359 'diff' => $this->mNewid
,
360 'oldid' => $this->mOldid
,
363 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
364 array( 'rev-deleted-unhide-diff', $link ) );
366 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
367 $multi = $this->getMultiNotice();
368 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
370 wfMsgHtml( 'wikicodecomparison' ),
372 'id' => 'differences-switchtype'
375 'diff' => $this->mNewid
,
376 'oldid' => $this->mOldid
,
384 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
385 $this->renderHtmlDiff();
387 if( $wgEnableHtmlDiff ) {
388 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
390 wfMsgHtml( 'visualcomparison' ),
392 'id' => 'differences-switchtype'
395 'diff' => $this->mNewid
,
396 'oldid' => $this->mOldid
,
405 $this->showDiff( $oldHeader, $newHeader );
407 $this->renderNewRevision();
410 wfProfileOut( __METHOD__
);
414 * Show the new revision of the page.
416 function renderNewRevision() {
417 global $wgOut, $wgUser;
418 wfProfileIn( __METHOD__
);
420 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
421 # Add deleted rev tag if needed
422 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
423 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
424 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
425 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
428 if( !$this->mNewRev
->isCurrent() ) {
429 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
432 $this->loadNewText();
433 if( is_object( $this->mNewRev
) ) {
434 $wgOut->setRevisionId( $this->mNewRev
->getId() );
437 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
438 // Stolen from Article::view --AG 2007-10-11
439 // Give hooks a chance to customise the output
440 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
441 // Wrap the whole lot in a <pre> and don't parse
443 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
444 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
445 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
446 $wgOut->addHTML( "\n</pre>\n" );
449 $wgOut->addWikiTextTidy( $this->mNewtext
);
452 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
453 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
455 # Add redundant patrol link on bottom...
456 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
457 $sk = $wgUser->getSkin();
459 "<div class='patrollink'>[" . $sk->link(
461 wfMsgHtml( 'markaspatrolleddiff' ),
464 'action' => 'markpatrolled',
465 'rcid' => $this->mRcidMarkPatrolled
471 wfProfileOut( __METHOD__
);
475 function renderHtmlDiff() {
476 global $wgOut, $wgParser, $wgDebugComments;
477 wfProfileIn( __METHOD__
);
479 $this->showDiffStyle();
481 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
482 #add deleted rev tag if needed
483 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
484 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
485 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
486 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
489 if( !$this->mNewRev
->isCurrent() ) {
490 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
496 if( is_object( $this->mOldRev
) ) {
497 $wgOut->setRevisionId( $this->mOldRev
->getId() );
500 $popts = $wgOut->parserOptions();
501 $oldTidy = $popts->setTidy( true );
502 $popts->setEditSection( false );
504 $parserOutput = $wgParser->parse( $this->mOldtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
505 $popts->setTidy( $oldTidy );
508 //$wgOut->addParserOutputNoText( $parserOutput );
509 $oldHtml = $parserOutput->getText();
510 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
513 if( is_object( $this->mNewRev
) ) {
514 $wgOut->setRevisionId( $this->mNewRev
->getId() );
517 $popts = $wgOut->parserOptions();
518 $oldTidy = $popts->setTidy( true );
520 $parserOutput = $wgParser->parse( $this->mNewtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
521 $popts->setTidy( $oldTidy );
523 $wgOut->addParserOutputNoText( $parserOutput );
524 $newHtml = $parserOutput->getText();
525 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
527 unset($parserOutput, $popts);
529 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
530 $differ->htmlDiff($oldHtml, $newHtml);
531 if ( $wgDebugComments ) {
532 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
535 wfProfileOut( __METHOD__
);
539 * Show the first revision of an article. Uses normal diff headers in
540 * contrast to normal "old revision" display style.
542 function showFirstRevision() {
543 global $wgOut, $wgUser;
544 wfProfileIn( __METHOD__
);
546 # Get article text from the DB
548 if ( ! $this->loadNewText() ) {
549 $t = $this->mTitle
->getPrefixedText();
550 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
551 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
552 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
553 wfProfileOut( __METHOD__
);
556 if ( $this->mNewRev
->isCurrent() ) {
557 $wgOut->setArticleFlag( true );
560 # Check if user is allowed to look at this page. If not, bail out.
562 if ( !$this->mTitle
->userCanRead() ) {
563 $wgOut->loginToUse();
565 wfProfileOut( __METHOD__
);
566 throw new MWException("Permission Error: you do not have access to view this page");
569 # Prepare the header box
571 $sk = $wgUser->getSkin();
573 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
577 $nextlink = '<br/>' . $sk->link(
579 wfMsgHtml( 'nextdiff' ),
581 'id' => 'differences-nextlink'
585 'oldid' => $this->mNewid
,
586 $this->htmlDiffArgument()
594 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
595 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
597 $wgOut->addHTML( $header );
599 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
600 $wgOut->setRobotPolicy( 'noindex,nofollow' );
602 wfProfileOut( __METHOD__
);
605 function htmlDiffArgument(){
606 global $wgEnableHtmlDiff;
607 if($wgEnableHtmlDiff){
609 return array( 'htmldiff' => 1 );
611 return array( 'htmldiff' => 0 );
619 * Get the diff text, send it to $wgOut
620 * Returns false if the diff could not be generated, otherwise returns true
622 function showDiff( $otitle, $ntitle ) {
624 $diff = $this->getDiff( $otitle, $ntitle );
625 if ( $diff === false ) {
626 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
629 $this->showDiffStyle();
630 $wgOut->addHTML( $diff );
636 * Add style sheets and supporting JS for diff display.
638 function showDiffStyle() {
639 global $wgStylePath, $wgStyleVersion, $wgOut;
640 $wgOut->addStyle( 'common/diff.css' );
642 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
643 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
647 * Get complete diff table, including header
649 * @param Title $otitle Old title
650 * @param Title $ntitle New title
653 function getDiff( $otitle, $ntitle ) {
654 $body = $this->getDiffBody();
655 if ( $body === false ) {
658 $multi = $this->getMultiNotice();
659 return $this->addHeader( $body, $otitle, $ntitle, $multi );
664 * Get the diff table body, without header
668 function getDiffBody() {
670 wfProfileIn( __METHOD__
);
671 $this->mCacheHit
= true;
672 // Check if the diff should be hidden from this user
673 if ( !$this->loadRevisionData() )
675 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
677 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
679 } else if ( $this->mOldRev
&& $this->mNewRev
&& $this->mOldRev
->getID() == $this->mNewRev
->getID() ) {
684 if ( $this->mOldid
&& $this->mNewid
) {
685 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
687 if ( !$this->mRefreshCache
) {
688 $difftext = $wgMemc->get( $key );
690 wfIncrStats( 'diff_cache_hit' );
691 $difftext = $this->localiseLineNumbers( $difftext );
692 $difftext .= "\n<!-- diff cache key $key -->\n";
693 wfProfileOut( __METHOD__
);
696 } // don't try to load but save the result
698 $this->mCacheHit
= false;
700 // Loadtext is permission safe, this just clears out the diff
701 if ( !$this->loadText() ) {
702 wfProfileOut( __METHOD__
);
706 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
708 // Save to cache for 7 days
709 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
710 wfIncrStats( 'diff_uncacheable' );
711 } else if ( $key !== false && $difftext !== false ) {
712 wfIncrStats( 'diff_cache_miss' );
713 $wgMemc->set( $key, $difftext, 7*86400 );
715 wfIncrStats( 'diff_uncacheable' );
717 // Replace line numbers with the text in the user's language
718 if ( $difftext !== false ) {
719 $difftext = $this->localiseLineNumbers( $difftext );
721 wfProfileOut( __METHOD__
);
726 * Make sure the proper modules are loaded before we try to
729 private function initDiffEngines() {
730 global $wgExternalDiffEngine;
731 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
732 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
733 wfSuppressWarnings();
734 dl( 'php_wikidiff.so' );
736 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
738 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
739 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
740 wfSuppressWarnings();
741 dl( 'php_wikidiff2.so' );
743 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
748 * Generate a diff, no caching
749 * $otext and $ntext must be already segmented
751 function generateDiffBody( $otext, $ntext ) {
752 global $wgExternalDiffEngine, $wgContLang;
754 $otext = str_replace( "\r\n", "\n", $otext );
755 $ntext = str_replace( "\r\n", "\n", $ntext );
757 $this->initDiffEngines();
759 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
760 # For historical reasons, external diff engine expects
761 # input text to be HTML-escaped already
762 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
763 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
764 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
765 $this->debug( 'wikidiff1' );
768 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
769 # Better external diff engine, the 2 may some day be dropped
770 # This one does the escaping and segmenting itself
771 wfProfileIn( 'wikidiff2_do_diff' );
772 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
773 $text .= $this->debug( 'wikidiff2' );
774 wfProfileOut( 'wikidiff2_do_diff' );
777 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
779 global $wgTmpDirectory;
780 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
781 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
783 $tempFile1 = fopen( $tempName1, "w" );
785 wfProfileOut( __METHOD__
);
788 $tempFile2 = fopen( $tempName2, "w" );
790 wfProfileOut( __METHOD__
);
793 fwrite( $tempFile1, $otext );
794 fwrite( $tempFile2, $ntext );
795 fclose( $tempFile1 );
796 fclose( $tempFile2 );
797 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
798 wfProfileIn( __METHOD__
. "-shellexec" );
799 $difftext = wfShellExec( $cmd );
800 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
801 wfProfileOut( __METHOD__
. "-shellexec" );
802 unlink( $tempName1 );
803 unlink( $tempName2 );
808 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
809 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
810 $diffs = new Diff( $ota, $nta );
811 $formatter = new TableDiffFormatter();
812 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
817 * Generate a debug comment indicating diff generating time,
818 * server node, and generator backend.
820 protected function debug( $generator="internal" ) {
821 global $wgShowHostnames;
822 $data = array( $generator );
823 if( $wgShowHostnames ) {
824 $data[] = wfHostname();
826 $data[] = wfTimestamp( TS_DB
);
827 return "<!-- diff generator: " .
836 * Replace line numbers with the text in the user's language
838 function localiseLineNumbers( $text ) {
839 return preg_replace_callback( '/<!--LINE (\d+)-->/',
840 array( &$this, 'localiseLineNumbersCb' ), $text );
843 function localiseLineNumbersCb( $matches ) {
845 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
850 * If there are revisions between the ones being compared, return a note saying so.
852 function getMultiNotice() {
853 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
856 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
857 // Comparing two different pages? Count would be meaningless.
861 $oldid = $this->mOldRev
->getId();
862 $newid = $this->mNewRev
->getId();
863 if ( $oldid > $newid ) {
864 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
867 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
871 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
876 * Add the header to a diff body
878 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
880 $header = "<table class='diff'>";
881 if( $diff ) { // Safari/Chrome show broken output if cols not used
883 <col class='diff-marker' />
884 <col class='diff-content' />
885 <col class='diff-marker' />
886 <col class='diff-content' />";
891 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
892 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
896 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
898 return $header . $diff . "</table>";
902 * Use specified text instead of loading from the database
904 function setText( $oldText, $newText ) {
905 $this->mOldtext
= $oldText;
906 $this->mNewtext
= $newText;
907 $this->mTextLoaded
= 2;
908 $this->mRevisionsLoaded
= true;
912 * Load revision metadata for the specified articles. If newid is 0, then compare
913 * the old article in oldid to the current article; if oldid is 0, then
914 * compare the current article to the immediately previous one (ignoring the
917 * If oldid is false, leave the corresponding revision object set
918 * to false. This is impossible via ordinary user input, and is provided for
921 function loadRevisionData() {
922 global $wgLang, $wgUser;
923 if ( $this->mRevisionsLoaded
) {
926 // Whether it succeeds or fails, we don't want to try again
927 $this->mRevisionsLoaded
= true;
930 // Load the new revision object
931 $this->mNewRev
= $this->mNewid
932 ? Revision
::newFromId( $this->mNewid
)
933 : Revision
::newFromTitle( $this->mTitle
);
934 if( !$this->mNewRev
instanceof Revision
)
937 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
938 $this->mNewid
= $this->mNewRev
->getId();
940 // Check if page is editable
941 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
943 // Set assorted variables
944 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
945 $dateofrev = $wgLang->date( $this->mNewRev
->getTimestamp(), true );
946 $timeofrev = $wgLang->time( $this->mNewRev
->getTimestamp(), true );
947 $this->mNewPage
= $this->mNewRev
->getTitle();
948 if( $this->mNewRev
->isCurrent() ) {
949 $newLink = $this->mNewPage
->escapeLocalUrl( array(
950 'oldid' => $this->mNewid
952 $this->mPagetitle
= htmlspecialchars( wfMsg(
958 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
962 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
963 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
965 $newLink = $this->mNewPage
->escapeLocalUrl( array(
966 'oldid' => $this->mNewid
968 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
970 'oldid' => $this->mNewid
972 $this->mPagetitle
= htmlspecialchars( wfMsg(
979 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
980 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
982 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
983 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
984 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
985 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
988 // Load the old revision object
989 $this->mOldRev
= false;
990 if( $this->mOldid
) {
991 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
992 } elseif ( $this->mOldid
=== 0 ) {
993 $rev = $this->mNewRev
->getPrevious();
995 $this->mOldid
= $rev->getId();
996 $this->mOldRev
= $rev;
998 // No previous revision; mark to show as first-version only.
999 $this->mOldid
= false;
1000 $this->mOldRev
= false;
1002 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
1004 if( is_null( $this->mOldRev
) ) {
1008 if ( $this->mOldRev
) {
1009 $this->mOldPage
= $this->mOldRev
->getTitle();
1011 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
1012 $dateofrev = $wgLang->date( $this->mOldRev
->getTimestamp(), true );
1013 $timeofrev = $wgLang->time( $this->mOldRev
->getTimestamp(), true );
1014 $oldLink = $this->mOldPage
->escapeLocalUrl( array(
1015 'oldid' => $this->mOldid
1017 $oldEdit = $this->mOldPage
->escapeLocalUrl( array(
1019 'oldid' => $this->mOldid
1021 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
1023 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
1024 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1025 // Add an "undo" link
1026 $newUndo = $this->mNewPage
->escapeLocalUrl( array(
1028 'undoafter' => $this->mOldid
,
1029 'undo' => $this->mNewid
1031 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
1032 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
1033 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1034 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
1037 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
1038 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
1039 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1040 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
1048 * Load the text of the revisions, as well as revision data.
1050 function loadText() {
1051 if ( $this->mTextLoaded
== 2 ) {
1054 // Whether it succeeds or fails, we don't want to try again
1055 $this->mTextLoaded
= 2;
1058 if ( !$this->loadRevisionData() ) {
1061 if ( $this->mOldRev
) {
1062 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1063 if ( $this->mOldtext
=== false ) {
1067 if ( $this->mNewRev
) {
1068 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1069 if ( $this->mNewtext
=== false ) {
1077 * Load the text of the new revision, not the old one
1079 function loadNewText() {
1080 if ( $this->mTextLoaded
>= 1 ) {
1083 $this->mTextLoaded
= 1;
1085 if ( !$this->loadRevisionData() ) {
1088 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1093 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
1095 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
1096 // You may copy this code freely under the conditions of the GPL.
1099 define('USE_ASSERTS', function_exists('assert'));
1104 * @ingroup DifferenceEngine
1111 function reverse() {
1112 trigger_error('pure virtual', E_USER_ERROR
);
1116 return $this->orig ?
sizeof($this->orig
) : 0;
1119 function nclosing() {
1120 return $this->closing ?
sizeof($this->closing
) : 0;
1127 * @ingroup DifferenceEngine
1129 class _DiffOp_Copy
extends _DiffOp
{
1132 function _DiffOp_Copy ($orig, $closing = false) {
1133 if (!is_array($closing))
1135 $this->orig
= $orig;
1136 $this->closing
= $closing;
1139 function reverse() {
1140 return new _DiffOp_Copy($this->closing
, $this->orig
);
1147 * @ingroup DifferenceEngine
1149 class _DiffOp_Delete
extends _DiffOp
{
1150 var $type = 'delete';
1152 function _DiffOp_Delete ($lines) {
1153 $this->orig
= $lines;
1154 $this->closing
= false;
1157 function reverse() {
1158 return new _DiffOp_Add($this->orig
);
1165 * @ingroup DifferenceEngine
1167 class _DiffOp_Add
extends _DiffOp
{
1170 function _DiffOp_Add ($lines) {
1171 $this->closing
= $lines;
1172 $this->orig
= false;
1175 function reverse() {
1176 return new _DiffOp_Delete($this->closing
);
1183 * @ingroup DifferenceEngine
1185 class _DiffOp_Change
extends _DiffOp
{
1186 var $type = 'change';
1188 function _DiffOp_Change ($orig, $closing) {
1189 $this->orig
= $orig;
1190 $this->closing
= $closing;
1193 function reverse() {
1194 return new _DiffOp_Change($this->closing
, $this->orig
);
1199 * Class used internally by Diff to actually compute the diffs.
1201 * The algorithm used here is mostly lifted from the perl module
1202 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1203 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1205 * More ideas are taken from:
1206 * http://www.ics.uci.edu/~eppstein/161/960229.html
1208 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1209 * diffutils-2.7, which can be found at:
1210 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1212 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1215 * Line length limits for robustness added by Tim Starling, 2005-08-31
1216 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1218 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1220 * @ingroup DifferenceEngine
1224 const MAX_XREF_LENGTH
= 10000;
1226 function diff ($from_lines, $to_lines){
1227 wfProfileIn( __METHOD__
);
1229 // Diff and store locally
1230 $this->diff_local($from_lines, $to_lines);
1232 // Merge edits when possible
1233 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1234 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1236 // Compute the edit operations.
1237 $n_from = sizeof($from_lines);
1238 $n_to = sizeof($to_lines);
1242 while ($xi < $n_from ||
$yi < $n_to) {
1243 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1244 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1246 // Skip matching "snake".
1248 while ( $xi < $n_from && $yi < $n_to
1249 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1250 $copy[] = $from_lines[$xi++
];
1254 $edits[] = new _DiffOp_Copy($copy);
1256 // Find deletes & adds.
1258 while ($xi < $n_from && $this->xchanged
[$xi])
1259 $delete[] = $from_lines[$xi++
];
1262 while ($yi < $n_to && $this->ychanged
[$yi])
1263 $add[] = $to_lines[$yi++
];
1265 if ($delete && $add)
1266 $edits[] = new _DiffOp_Change($delete, $add);
1268 $edits[] = new _DiffOp_Delete($delete);
1270 $edits[] = new _DiffOp_Add($add);
1272 wfProfileOut( __METHOD__
);
1276 function diff_local ($from_lines, $to_lines) {
1277 global $wgExternalDiffEngine;
1278 wfProfileIn( __METHOD__
);
1280 if($wgExternalDiffEngine == 'wikidiff3'){
1282 $wikidiff3 = new WikiDiff3();
1283 $wikidiff3->diff($from_lines, $to_lines);
1284 $this->xchanged
= $wikidiff3->removed
;
1285 $this->ychanged
= $wikidiff3->added
;
1289 $n_from = sizeof($from_lines);
1290 $n_to = sizeof($to_lines);
1291 $this->xchanged
= $this->ychanged
= array();
1292 $this->xv
= $this->yv
= array();
1293 $this->xind
= $this->yind
= array();
1295 unset($this->in_seq
);
1298 // Skip leading common lines.
1299 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1300 if ($from_lines[$skip] !== $to_lines[$skip])
1302 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1304 // Skip trailing common lines.
1305 $xi = $n_from; $yi = $n_to;
1306 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1307 if ($from_lines[$xi] !== $to_lines[$yi])
1309 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1312 // Ignore lines which do not exist in both files.
1313 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1314 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1317 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1318 $line = $to_lines[$yi];
1319 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1321 $yhash[$this->_line_hash($line)] = 1;
1322 $this->yv
[] = $line;
1323 $this->yind
[] = $yi;
1325 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1326 $line = $from_lines[$xi];
1327 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1329 $this->xv
[] = $line;
1330 $this->xind
[] = $xi;
1334 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1336 wfProfileOut( __METHOD__
);
1340 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1342 function _line_hash( $line ) {
1343 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1344 return md5( $line );
1350 /* Divide the Largest Common Subsequence (LCS) of the sequences
1351 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1354 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1355 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1356 * sub sequences. The first sub-sequence is contained in [X0, X1),
1357 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1358 * that (X0, Y0) == (XOFF, YOFF) and
1359 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1361 * This function assumes that the first lines of the specified portions
1362 * of the two files do not match, and likewise that the last lines do not
1363 * match. The caller must trim matching lines from the beginning and end
1364 * of the portions it is going to specify.
1366 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1369 if ($xlim - $xoff > $ylim - $yoff) {
1370 // Things seems faster (I'm not sure I understand why)
1371 // when the shortest sequence in X.
1373 list ($xoff, $xlim, $yoff, $ylim)
1374 = array( $yoff, $ylim, $xoff, $xlim);
1378 for ($i = $ylim - 1; $i >= $yoff; $i--)
1379 $ymatches[$this->xv
[$i]][] = $i;
1381 for ($i = $ylim - 1; $i >= $yoff; $i--)
1382 $ymatches[$this->yv
[$i]][] = $i;
1385 $this->seq
[0]= $yoff - 1;
1386 $this->in_seq
= array();
1387 $ymids[0] = array();
1389 $numer = $xlim - $xoff +
$nchunks - 1;
1391 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1393 for ($i = 0; $i <= $this->lcs
; $i++
)
1394 $ymids[$i][$chunk-1] = $this->seq
[$i];
1396 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1397 for ( ; $x < $x1; $x++
) {
1398 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1399 if (empty($ymatches[$line]))
1401 $matches = $ymatches[$line];
1403 while (list ($junk, $y) = each($matches))
1404 if (empty($this->in_seq
[$y])) {
1405 $k = $this->_lcs_pos($y);
1406 USE_ASSERTS
&& assert($k > 0);
1407 $ymids[$k] = $ymids[$k-1];
1410 while (list ( /* $junk */, $y) = each($matches)) {
1411 if ($y > $this->seq
[$k-1]) {
1412 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1413 // Optimization: this is a common case:
1414 // next match is just replacing previous match.
1415 $this->in_seq
[$this->seq
[$k]] = false;
1416 $this->seq
[$k] = $y;
1417 $this->in_seq
[$y] = 1;
1418 } else if (empty($this->in_seq
[$y])) {
1419 $k = $this->_lcs_pos($y);
1420 USE_ASSERTS
&& assert($k > 0);
1421 $ymids[$k] = $ymids[$k-1];
1427 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1428 $ymid = $ymids[$this->lcs
];
1429 for ($n = 0; $n < $nchunks - 1; $n++
) {
1430 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1431 $y1 = $ymid[$n] +
1;
1432 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1434 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1436 return array($this->lcs
, $seps);
1439 function _lcs_pos ($ypos) {
1441 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1442 $this->seq
[++
$this->lcs
] = $ypos;
1443 $this->in_seq
[$ypos] = 1;
1448 while ($beg < $end) {
1449 $mid = (int)(($beg +
$end) / 2);
1450 if ( $ypos > $this->seq
[$mid] )
1456 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1458 $this->in_seq
[$this->seq
[$end]] = false;
1459 $this->seq
[$end] = $ypos;
1460 $this->in_seq
[$ypos] = 1;
1464 /* Find LCS of two sequences.
1466 * The results are recorded in the vectors $this->{x,y}changed[], by
1467 * storing a 1 in the element for each line that is an insertion
1468 * or deletion (ie. is not in the LCS).
1470 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1472 * Note that XLIM, YLIM are exclusive bounds.
1473 * All line numbers are origin-0 and discarded lines are not counted.
1475 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1476 // Slide down the bottom initial diagonal.
1477 while ($xoff < $xlim && $yoff < $ylim
1478 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1483 // Slide up the top initial diagonal.
1484 while ($xlim > $xoff && $ylim > $yoff
1485 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1490 if ($xoff == $xlim ||
$yoff == $ylim)
1493 // This is ad hoc but seems to work well.
1494 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1495 //$nchunks = max(2,min(8,(int)$nchunks));
1496 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1498 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1502 // X and Y sequences have no common subsequence:
1503 // mark all changed.
1504 while ($yoff < $ylim)
1505 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1506 while ($xoff < $xlim)
1507 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1509 // Use the partitions to split this problem into subproblems.
1512 while ($pt2 = next($seps)) {
1513 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1519 /* Adjust inserts/deletes of identical lines to join changes
1520 * as much as possible.
1522 * We do something when a run of changed lines include a
1523 * line at one end and has an excluded, identical line at the other.
1524 * We are free to choose which identical line is included.
1525 * `compareseq' usually chooses the one at the beginning,
1526 * but usually it is cleaner to consider the following identical line
1527 * to be the "change".
1529 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1531 function _shift_boundaries ($lines, &$changed, $other_changed) {
1532 wfProfileIn( __METHOD__
);
1536 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1537 $len = sizeof($lines);
1538 $other_len = sizeof($other_changed);
1542 * Scan forwards to find beginning of another run of changes.
1543 * Also keep track of the corresponding point in the other file.
1545 * Throughout this code, $i and $j are adjusted together so that
1546 * the first $i elements of $changed and the first $j elements
1547 * of $other_changed both contain the same number of zeros
1548 * (unchanged lines).
1549 * Furthermore, $j is always kept so that $j == $other_len or
1550 * $other_changed[$j] == false.
1552 while ($j < $other_len && $other_changed[$j])
1555 while ($i < $len && ! $changed[$i]) {
1556 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1558 while ($j < $other_len && $other_changed[$j])
1567 // Find the end of this run of changes.
1568 while (++
$i < $len && $changed[$i])
1573 * Record the length of this run of changes, so that
1574 * we can later determine whether the run has grown.
1576 $runlength = $i - $start;
1579 * Move the changed region back, so long as the
1580 * previous unchanged line matches the last changed one.
1581 * This merges with previous changed regions.
1583 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1584 $changed[--$start] = 1;
1585 $changed[--$i] = false;
1586 while ($start > 0 && $changed[$start - 1])
1588 USE_ASSERTS
&& assert('$j > 0');
1589 while ($other_changed[--$j])
1591 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1595 * Set CORRESPONDING to the end of the changed run, at the last
1596 * point where it corresponds to a changed run in the other file.
1597 * CORRESPONDING == LEN means no such point has been found.
1599 $corresponding = $j < $other_len ?
$i : $len;
1602 * Move the changed region forward, so long as the
1603 * first changed line matches the following unchanged one.
1604 * This merges with following changed regions.
1605 * Do this second, so that if there are no merges,
1606 * the changed region is moved forward as far as possible.
1608 while ($i < $len && $lines[$start] == $lines[$i]) {
1609 $changed[$start++
] = false;
1611 while ($i < $len && $changed[$i])
1614 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1616 if ($j < $other_len && $other_changed[$j]) {
1617 $corresponding = $i;
1618 while ($j < $other_len && $other_changed[$j])
1622 } while ($runlength != $i - $start);
1625 * If possible, move the fully-merged run of changes
1626 * back to a corresponding run in the other file.
1628 while ($corresponding < $i) {
1629 $changed[--$start] = 1;
1631 USE_ASSERTS
&& assert('$j > 0');
1632 while ($other_changed[--$j])
1634 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1637 wfProfileOut( __METHOD__
);
1642 * Class representing a 'diff' between two sequences of strings.
1645 * @ingroup DifferenceEngine
1653 * Computes diff between sequences of strings.
1655 * @param $from_lines array An array of strings.
1656 * (Typically these are lines from a file.)
1657 * @param $to_lines array An array of strings.
1659 function Diff($from_lines, $to_lines) {
1660 $eng = new _DiffEngine
;
1661 $this->edits
= $eng->diff($from_lines, $to_lines);
1662 //$this->_check($from_lines, $to_lines);
1666 * Compute reversed Diff.
1670 * $diff = new Diff($lines1, $lines2);
1671 * $rev = $diff->reverse();
1672 * @return object A Diff object representing the inverse of the
1675 function reverse () {
1677 $rev->edits
= array();
1678 foreach ($this->edits
as $edit) {
1679 $rev->edits
[] = $edit->reverse();
1685 * Check for empty diff.
1687 * @return bool True iff two sequences were identical.
1689 function isEmpty () {
1690 foreach ($this->edits
as $edit) {
1691 if ($edit->type
!= 'copy')
1698 * Compute the length of the Longest Common Subsequence (LCS).
1700 * This is mostly for diagnostic purposed.
1702 * @return int The length of the LCS.
1706 foreach ($this->edits
as $edit) {
1707 if ($edit->type
== 'copy')
1708 $lcs +
= sizeof($edit->orig
);
1714 * Get the original set of lines.
1716 * This reconstructs the $from_lines parameter passed to the
1719 * @return array The original sequence of strings.
1724 foreach ($this->edits
as $edit) {
1726 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1732 * Get the closing set of lines.
1734 * This reconstructs the $to_lines parameter passed to the
1737 * @return array The sequence of strings.
1739 function closing() {
1742 foreach ($this->edits
as $edit) {
1744 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1750 * Check a Diff for validity.
1752 * This is here only for debugging purposes.
1754 function _check ($from_lines, $to_lines) {
1755 wfProfileIn( __METHOD__
);
1756 if (serialize($from_lines) != serialize($this->orig()))
1757 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1758 if (serialize($to_lines) != serialize($this->closing()))
1759 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1761 $rev = $this->reverse();
1762 if (serialize($to_lines) != serialize($rev->orig()))
1763 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1764 if (serialize($from_lines) != serialize($rev->closing()))
1765 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1769 foreach ($this->edits
as $edit) {
1770 if ( $prevtype == $edit->type
)
1771 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1772 $prevtype = $edit->type
;
1775 $lcs = $this->lcs();
1776 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1777 wfProfileOut( __METHOD__
);
1782 * @todo document, bad name.
1784 * @ingroup DifferenceEngine
1786 class MappedDiff
extends Diff
1791 * Computes diff between sequences of strings.
1793 * This can be used to compute things like
1794 * case-insensitve diffs, or diffs which ignore
1795 * changes in white-space.
1797 * @param $from_lines array An array of strings.
1798 * (Typically these are lines from a file.)
1800 * @param $to_lines array An array of strings.
1802 * @param $mapped_from_lines array This array should
1803 * have the same size number of elements as $from_lines.
1804 * The elements in $mapped_from_lines and
1805 * $mapped_to_lines are what is actually compared
1806 * when computing the diff.
1808 * @param $mapped_to_lines array This array should
1809 * have the same number of elements as $to_lines.
1811 function MappedDiff($from_lines, $to_lines,
1812 $mapped_from_lines, $mapped_to_lines) {
1813 wfProfileIn( __METHOD__
);
1815 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1816 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1818 $this->Diff($mapped_from_lines, $mapped_to_lines);
1821 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1822 $orig = &$this->edits
[$i]->orig
;
1823 if (is_array($orig)) {
1824 $orig = array_slice($from_lines, $xi, sizeof($orig));
1825 $xi +
= sizeof($orig);
1828 $closing = &$this->edits
[$i]->closing
;
1829 if (is_array($closing)) {
1830 $closing = array_slice($to_lines, $yi, sizeof($closing));
1831 $yi +
= sizeof($closing);
1834 wfProfileOut( __METHOD__
);
1839 * A class to format Diffs
1841 * This class formats the diff in classic diff format.
1842 * It is intended that this class be customized via inheritance,
1843 * to obtain fancier outputs.
1846 * @ingroup DifferenceEngine
1848 class DiffFormatter
{
1850 * Number of leading context "lines" to preserve.
1852 * This should be left at zero for this class, but subclasses
1853 * may want to set this to other values.
1855 var $leading_context_lines = 0;
1858 * Number of trailing context "lines" to preserve.
1860 * This should be left at zero for this class, but subclasses
1861 * may want to set this to other values.
1863 var $trailing_context_lines = 0;
1868 * @param $diff object A Diff object.
1869 * @return string The formatted output.
1871 function format($diff) {
1872 wfProfileIn( __METHOD__
);
1878 $nlead = $this->leading_context_lines
;
1879 $ntrail = $this->trailing_context_lines
;
1881 $this->_start_diff();
1883 foreach ($diff->edits
as $edit) {
1884 if ($edit->type
== 'copy') {
1885 if (is_array($block)) {
1886 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1891 $context = array_slice($edit->orig
, 0, $ntrail);
1892 $block[] = new _DiffOp_Copy($context);
1894 $this->_block($x0, $ntrail +
$xi - $x0,
1895 $y0, $ntrail +
$yi - $y0,
1900 $context = $edit->orig
;
1903 if (! is_array($block)) {
1904 $context = array_slice($context, sizeof($context) - $nlead);
1905 $x0 = $xi - sizeof($context);
1906 $y0 = $yi - sizeof($context);
1909 $block[] = new _DiffOp_Copy($context);
1915 $xi +
= sizeof($edit->orig
);
1917 $yi +
= sizeof($edit->closing
);
1920 if (is_array($block))
1921 $this->_block($x0, $xi - $x0,
1925 $end = $this->_end_diff();
1926 wfProfileOut( __METHOD__
);
1930 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1931 wfProfileIn( __METHOD__
);
1932 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1933 foreach ($edits as $edit) {
1934 if ($edit->type
== 'copy')
1935 $this->_context($edit->orig
);
1936 elseif ($edit->type
== 'add')
1937 $this->_added($edit->closing
);
1938 elseif ($edit->type
== 'delete')
1939 $this->_deleted($edit->orig
);
1940 elseif ($edit->type
== 'change')
1941 $this->_changed($edit->orig
, $edit->closing
);
1943 trigger_error('Unknown edit type', E_USER_ERROR
);
1945 $this->_end_block();
1946 wfProfileOut( __METHOD__
);
1949 function _start_diff() {
1953 function _end_diff() {
1954 $val = ob_get_contents();
1959 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1961 $xbeg .= "," . ($xbeg +
$xlen - 1);
1963 $ybeg .= "," . ($ybeg +
$ylen - 1);
1965 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1968 function _start_block($header) {
1969 echo $header . "\n";
1972 function _end_block() {
1975 function _lines($lines, $prefix = ' ') {
1976 foreach ($lines as $line)
1977 echo "$prefix $line\n";
1980 function _context($lines) {
1981 $this->_lines($lines);
1984 function _added($lines) {
1985 $this->_lines($lines, '>');
1987 function _deleted($lines) {
1988 $this->_lines($lines, '<');
1991 function _changed($orig, $closing) {
1992 $this->_deleted($orig);
1994 $this->_added($closing);
1999 * A formatter that outputs unified diffs
2000 * @ingroup DifferenceEngine
2003 class UnifiedDiffFormatter
extends DiffFormatter
{
2004 var $leading_context_lines = 2;
2005 var $trailing_context_lines = 2;
2007 function _added($lines) {
2008 $this->_lines($lines, '+');
2010 function _deleted($lines) {
2011 $this->_lines($lines, '-');
2013 function _changed($orig, $closing) {
2014 $this->_deleted($orig);
2015 $this->_added($closing);
2017 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
2018 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
2023 * A pseudo-formatter that just passes along the Diff::$edits array
2024 * @ingroup DifferenceEngine
2026 class ArrayDiffFormatter
extends DiffFormatter
{
2027 function format($diff) {
2031 foreach($diff->edits
as $edit)
2032 switch($edit->type
) {
2034 foreach($edit->closing
as $l) {
2038 'newline' => $newline++
2043 foreach($edit->orig
as $l) {
2045 'action' => 'delete',
2047 'oldline' => $oldline++
,
2052 foreach($edit->orig
as $i => $l) {
2054 'action' => 'change',
2056 'new' => @$edit->closing
[$i],
2057 'oldline' => $oldline++
,
2058 'newline' => $newline++
,
2063 $oldline +
= count($edit->orig
);
2064 $newline +
= count($edit->orig
);
2071 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
2075 define('NBSP', ' '); // iso-8859-x non-breaking space.
2080 * @ingroup DifferenceEngine
2082 class _HWLDF_WordAccumulator
{
2083 function _HWLDF_WordAccumulator () {
2084 $this->_lines
= array();
2090 function _flushGroup ($new_tag) {
2091 if ($this->_group
!== '') {
2092 if ($this->_tag
== 'ins')
2093 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
2094 htmlspecialchars ( $this->_group
) . '</ins>';
2095 elseif ($this->_tag
== 'del')
2096 $this->_line
.= '<del class="diffchange diffchange-inline">' .
2097 htmlspecialchars ( $this->_group
) . '</del>';
2099 $this->_line
.= htmlspecialchars ( $this->_group
);
2102 $this->_tag
= $new_tag;
2105 function _flushLine ($new_tag) {
2106 $this->_flushGroup($new_tag);
2107 if ($this->_line
!= '')
2108 array_push ( $this->_lines
, $this->_line
);
2110 # make empty lines visible by inserting an NBSP
2111 array_push ( $this->_lines
, NBSP
);
2115 function addWords ($words, $tag = '') {
2116 if ($tag != $this->_tag
)
2117 $this->_flushGroup($tag);
2119 foreach ($words as $word) {
2120 // new-line should only come as first char of word.
2123 if ($word[0] == "\n") {
2124 $this->_flushLine($tag);
2125 $word = substr($word, 1);
2127 assert(!strstr($word, "\n"));
2128 $this->_group
.= $word;
2132 function getLines() {
2133 $this->_flushLine('~done');
2134 return $this->_lines
;
2141 * @ingroup DifferenceEngine
2143 class WordLevelDiff
extends MappedDiff
{
2144 const MAX_LINE_LENGTH
= 10000;
2146 function WordLevelDiff ($orig_lines, $closing_lines) {
2147 wfProfileIn( __METHOD__
);
2149 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
2150 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
2152 $this->MappedDiff($orig_words, $closing_words,
2153 $orig_stripped, $closing_stripped);
2154 wfProfileOut( __METHOD__
);
2157 function _split($lines) {
2158 wfProfileIn( __METHOD__
);
2161 $stripped = array();
2163 foreach ( $lines as $line ) {
2164 # If the line is too long, just pretend the entire line is one big word
2165 # This prevents resource exhaustion problems
2172 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2174 $stripped[] = $line;
2177 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2180 $words = array_merge( $words, $m[0] );
2181 $stripped = array_merge( $stripped, $m[1] );
2185 wfProfileOut( __METHOD__
);
2186 return array($words, $stripped);
2190 wfProfileIn( __METHOD__
);
2191 $orig = new _HWLDF_WordAccumulator
;
2193 foreach ($this->edits
as $edit) {
2194 if ($edit->type
== 'copy')
2195 $orig->addWords($edit->orig
);
2196 elseif ($edit->orig
)
2197 $orig->addWords($edit->orig
, 'del');
2199 $lines = $orig->getLines();
2200 wfProfileOut( __METHOD__
);
2204 function closing () {
2205 wfProfileIn( __METHOD__
);
2206 $closing = new _HWLDF_WordAccumulator
;
2208 foreach ($this->edits
as $edit) {
2209 if ($edit->type
== 'copy')
2210 $closing->addWords($edit->closing
);
2211 elseif ($edit->closing
)
2212 $closing->addWords($edit->closing
, 'ins');
2214 $lines = $closing->getLines();
2215 wfProfileOut( __METHOD__
);
2221 * Wikipedia Table style diff formatter.
2224 * @ingroup DifferenceEngine
2226 class TableDiffFormatter
extends DiffFormatter
{
2227 function TableDiffFormatter() {
2228 $this->leading_context_lines
= 2;
2229 $this->trailing_context_lines
= 2;
2232 public static function escapeWhiteSpace( $msg ) {
2233 $msg = preg_replace( '/^ /m', ' ', $msg );
2234 $msg = preg_replace( '/ $/m', ' ', $msg );
2235 $msg = preg_replace( '/ /', ' ', $msg );
2239 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2240 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2241 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2245 function _start_block( $header ) {
2249 function _end_block() {
2252 function _lines( $lines, $prefix=' ', $color='white' ) {
2255 # HTML-escape parameter before calling this
2256 function addedLine( $line ) {
2257 return $this->wrapLine( '+', 'diff-addedline', $line );
2260 # HTML-escape parameter before calling this
2261 function deletedLine( $line ) {
2262 return $this->wrapLine( '-', 'diff-deletedline', $line );
2265 # HTML-escape parameter before calling this
2266 function contextLine( $line ) {
2267 return $this->wrapLine( ' ', 'diff-context', $line );
2270 private function wrapLine( $marker, $class, $line ) {
2271 if( $line !== '' ) {
2272 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2273 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2275 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2278 function emptyLine() {
2279 return '<td colspan="2"> </td>';
2282 function _added( $lines ) {
2283 foreach ($lines as $line) {
2284 echo '<tr>' . $this->emptyLine() .
2285 $this->addedLine( '<ins class="diffchange">' .
2286 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2290 function _deleted($lines) {
2291 foreach ($lines as $line) {
2292 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2293 htmlspecialchars ( $line ) . '</del>' ) .
2294 $this->emptyLine() . "</tr>\n";
2298 function _context( $lines ) {
2299 foreach ($lines as $line) {
2301 $this->contextLine( htmlspecialchars ( $line ) ) .
2302 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2306 function _changed( $orig, $closing ) {
2307 wfProfileIn( __METHOD__
);
2309 $diff = new WordLevelDiff( $orig, $closing );
2310 $del = $diff->orig();
2311 $add = $diff->closing();
2313 # Notice that WordLevelDiff returns HTML-escaped output.
2314 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2316 while ( $line = array_shift( $del ) ) {
2317 $aline = array_shift( $add );
2318 echo '<tr>' . $this->deletedLine( $line ) .
2319 $this->addedLine( $aline ) . "</tr>\n";
2321 foreach ($add as $line) { # If any leftovers
2322 echo '<tr>' . $this->emptyLine() .
2323 $this->addedLine( $line ) . "</tr>\n";
2325 wfProfileOut( __METHOD__
);