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( 'deletedrevision' ) ) {
322 // Don't show useless link to people who cannot hide revisions
323 if( $this->mOldRev
->getVisibility() ||
$wgUser->isAllowed( 'deleterevision' ) ) {
324 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
325 // If revision was hidden from sysops
326 $ldel = Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ),
327 '(' . wfMsgHtml( 'rev-delundel' ) . ')' );
330 'type' => 'revision',
331 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
332 'ids' => $this->mOldRev
->getId()
334 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
336 $ldel = " $ldel ";
338 // Don't show useless link to people who cannot hide revisions
339 if( $this->mNewRev
->getVisibility() ||
$wgUser->isAllowed( 'deleterevision' ) ) {
340 if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
341 // If revision was hidden from sysops
342 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
345 'type' => 'revision',
346 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
347 'ids' => $this->mNewRev
->getId()
349 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
351 $rdel = " $rdel ";
355 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
356 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
357 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
358 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
359 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
360 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
361 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
362 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
364 # Check if this user can see the revisions
365 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
)
366 && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
367 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
)
368 ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
369 # Output the diff if allowed...
370 if( $deleted && (!$this->unhide ||
!$allowed) ) {
371 $this->showDiffStyle();
372 $multi = $this->getMultiNotice();
373 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
375 # Give explanation for why revision is not visible
376 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
377 array( 'rev-deleted-no-diff' ) );
379 # Give explanation and add a link to view the diff...
380 $link = $this->mTitle
->getFullUrl( array(
381 'diff' => $this->mNewid
,
382 'oldid' => $this->mOldid
,
385 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
386 array( 'rev-deleted-unhide-diff', $link ) );
388 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
389 $multi = $this->getMultiNotice();
390 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
392 wfMsgHtml( 'wikicodecomparison' ),
394 'id' => 'differences-switchtype'
397 'diff' => $this->mNewid
,
398 'oldid' => $this->mOldid
,
406 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
407 $this->renderHtmlDiff();
409 if( $wgEnableHtmlDiff ) {
410 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
412 wfMsgHtml( 'visualcomparison' ),
414 'id' => 'differences-switchtype'
417 'diff' => $this->mNewid
,
418 'oldid' => $this->mOldid
,
427 $this->showDiff( $oldHeader, $newHeader );
429 $this->renderNewRevision();
432 wfProfileOut( __METHOD__
);
436 * Show the new revision of the page.
438 function renderNewRevision() {
439 global $wgOut, $wgUser;
440 wfProfileIn( __METHOD__
);
442 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
443 # Add deleted rev tag if needed
444 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
445 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
446 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
447 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
450 if( !$this->mNewRev
->isCurrent() ) {
451 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
454 $this->loadNewText();
455 if( is_object( $this->mNewRev
) ) {
456 $wgOut->setRevisionId( $this->mNewRev
->getId() );
459 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
460 // Stolen from Article::view --AG 2007-10-11
461 // Give hooks a chance to customise the output
462 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
463 // Wrap the whole lot in a <pre> and don't parse
465 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
466 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
467 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
468 $wgOut->addHTML( "\n</pre>\n" );
471 $wgOut->addWikiTextTidy( $this->mNewtext
);
474 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
475 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
477 # Add redundant patrol link on bottom...
478 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
479 $sk = $wgUser->getSkin();
481 "<div class='patrollink'>[" . $sk->link(
483 wfMsgHtml( 'markaspatrolleddiff' ),
486 'action' => 'markpatrolled',
487 'rcid' => $this->mRcidMarkPatrolled
493 wfProfileOut( __METHOD__
);
497 function renderHtmlDiff() {
498 global $wgOut, $wgParser, $wgDebugComments;
499 wfProfileIn( __METHOD__
);
501 $this->showDiffStyle();
503 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
504 #add deleted rev tag if needed
505 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
506 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
507 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
508 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
511 if( !$this->mNewRev
->isCurrent() ) {
512 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
518 if( is_object( $this->mOldRev
) ) {
519 $wgOut->setRevisionId( $this->mOldRev
->getId() );
522 $popts = $wgOut->parserOptions();
523 $oldTidy = $popts->setTidy( true );
524 $popts->setEditSection( false );
526 $parserOutput = $wgParser->parse( $this->mOldtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
527 $popts->setTidy( $oldTidy );
530 //$wgOut->addParserOutputNoText( $parserOutput );
531 $oldHtml = $parserOutput->getText();
532 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
535 if( is_object( $this->mNewRev
) ) {
536 $wgOut->setRevisionId( $this->mNewRev
->getId() );
539 $popts = $wgOut->parserOptions();
540 $oldTidy = $popts->setTidy( true );
542 $parserOutput = $wgParser->parse( $this->mNewtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
543 $popts->setTidy( $oldTidy );
545 $wgOut->addParserOutputNoText( $parserOutput );
546 $newHtml = $parserOutput->getText();
547 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
549 unset($parserOutput, $popts);
551 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
552 $differ->htmlDiff($oldHtml, $newHtml);
553 if ( $wgDebugComments ) {
554 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
557 wfProfileOut( __METHOD__
);
561 * Show the first revision of an article. Uses normal diff headers in
562 * contrast to normal "old revision" display style.
564 function showFirstRevision() {
565 global $wgOut, $wgUser;
566 wfProfileIn( __METHOD__
);
568 # Get article text from the DB
570 if ( ! $this->loadNewText() ) {
571 $t = $this->mTitle
->getPrefixedText();
572 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
573 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
574 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
575 wfProfileOut( __METHOD__
);
578 if ( $this->mNewRev
->isCurrent() ) {
579 $wgOut->setArticleFlag( true );
582 # Check if user is allowed to look at this page. If not, bail out.
584 if ( !$this->mTitle
->userCanRead() ) {
585 $wgOut->loginToUse();
587 wfProfileOut( __METHOD__
);
588 throw new MWException("Permission Error: you do not have access to view this page");
591 # Prepare the header box
593 $sk = $wgUser->getSkin();
595 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
599 $nextlink = '<br/>' . $sk->link(
601 wfMsgHtml( 'nextdiff' ),
603 'id' => 'differences-nextlink'
607 'oldid' => $this->mNewid
,
608 $this->htmlDiffArgument()
616 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
617 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
619 $wgOut->addHTML( $header );
621 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
622 $wgOut->setRobotPolicy( 'noindex,nofollow' );
624 wfProfileOut( __METHOD__
);
627 function htmlDiffArgument(){
628 global $wgEnableHtmlDiff;
629 if($wgEnableHtmlDiff){
631 return array( 'htmldiff' => 1 );
633 return array( 'htmldiff' => 0 );
641 * Get the diff text, send it to $wgOut
642 * Returns false if the diff could not be generated, otherwise returns true
644 function showDiff( $otitle, $ntitle ) {
646 $diff = $this->getDiff( $otitle, $ntitle );
647 if ( $diff === false ) {
648 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
651 $this->showDiffStyle();
652 $wgOut->addHTML( $diff );
658 * Add style sheets and supporting JS for diff display.
660 function showDiffStyle() {
661 global $wgStylePath, $wgStyleVersion, $wgOut;
662 $wgOut->addStyle( 'common/diff.css' );
664 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
665 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
669 * Get complete diff table, including header
671 * @param Title $otitle Old title
672 * @param Title $ntitle New title
675 function getDiff( $otitle, $ntitle ) {
676 $body = $this->getDiffBody();
677 if ( $body === false ) {
680 $multi = $this->getMultiNotice();
681 return $this->addHeader( $body, $otitle, $ntitle, $multi );
686 * Get the diff table body, without header
690 function getDiffBody() {
692 wfProfileIn( __METHOD__
);
693 $this->mCacheHit
= true;
694 // Check if the diff should be hidden from this user
695 if ( !$this->loadRevisionData() )
697 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
699 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
701 } else if ( $this->mOldRev
&& $this->mNewRev
&& $this->mOldRev
->getID() == $this->mNewRev
->getID() ) {
706 if ( $this->mOldid
&& $this->mNewid
) {
707 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
709 if ( !$this->mRefreshCache
) {
710 $difftext = $wgMemc->get( $key );
712 wfIncrStats( 'diff_cache_hit' );
713 $difftext = $this->localiseLineNumbers( $difftext );
714 $difftext .= "\n<!-- diff cache key $key -->\n";
715 wfProfileOut( __METHOD__
);
718 } // don't try to load but save the result
720 $this->mCacheHit
= false;
722 // Loadtext is permission safe, this just clears out the diff
723 if ( !$this->loadText() ) {
724 wfProfileOut( __METHOD__
);
728 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
730 // Save to cache for 7 days
731 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
732 wfIncrStats( 'diff_uncacheable' );
733 } else if ( $key !== false && $difftext !== false ) {
734 wfIncrStats( 'diff_cache_miss' );
735 $wgMemc->set( $key, $difftext, 7*86400 );
737 wfIncrStats( 'diff_uncacheable' );
739 // Replace line numbers with the text in the user's language
740 if ( $difftext !== false ) {
741 $difftext = $this->localiseLineNumbers( $difftext );
743 wfProfileOut( __METHOD__
);
748 * Make sure the proper modules are loaded before we try to
751 private function initDiffEngines() {
752 global $wgExternalDiffEngine;
753 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
754 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
755 wfSuppressWarnings();
756 dl( 'php_wikidiff.so' );
758 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
760 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
761 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
762 wfSuppressWarnings();
763 dl( 'php_wikidiff2.so' );
765 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
770 * Generate a diff, no caching
771 * $otext and $ntext must be already segmented
773 function generateDiffBody( $otext, $ntext ) {
774 global $wgExternalDiffEngine, $wgContLang;
776 $otext = str_replace( "\r\n", "\n", $otext );
777 $ntext = str_replace( "\r\n", "\n", $ntext );
779 $this->initDiffEngines();
781 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
782 # For historical reasons, external diff engine expects
783 # input text to be HTML-escaped already
784 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
785 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
786 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
787 $this->debug( 'wikidiff1' );
790 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
791 # Better external diff engine, the 2 may some day be dropped
792 # This one does the escaping and segmenting itself
793 wfProfileIn( 'wikidiff2_do_diff' );
794 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
795 $text .= $this->debug( 'wikidiff2' );
796 wfProfileOut( 'wikidiff2_do_diff' );
799 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
801 global $wgTmpDirectory;
802 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
803 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
805 $tempFile1 = fopen( $tempName1, "w" );
807 wfProfileOut( __METHOD__
);
810 $tempFile2 = fopen( $tempName2, "w" );
812 wfProfileOut( __METHOD__
);
815 fwrite( $tempFile1, $otext );
816 fwrite( $tempFile2, $ntext );
817 fclose( $tempFile1 );
818 fclose( $tempFile2 );
819 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
820 wfProfileIn( __METHOD__
. "-shellexec" );
821 $difftext = wfShellExec( $cmd );
822 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
823 wfProfileOut( __METHOD__
. "-shellexec" );
824 unlink( $tempName1 );
825 unlink( $tempName2 );
830 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
831 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
832 $diffs = new Diff( $ota, $nta );
833 $formatter = new TableDiffFormatter();
834 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
839 * Generate a debug comment indicating diff generating time,
840 * server node, and generator backend.
842 protected function debug( $generator="internal" ) {
843 global $wgShowHostnames;
844 if ( !$this->enableDebugComment
) {
847 $data = array( $generator );
848 if( $wgShowHostnames ) {
849 $data[] = wfHostname();
851 $data[] = wfTimestamp( TS_DB
);
852 return "<!-- diff generator: " .
861 * Replace line numbers with the text in the user's language
863 function localiseLineNumbers( $text ) {
864 return preg_replace_callback( '/<!--LINE (\d+)-->/',
865 array( &$this, 'localiseLineNumbersCb' ), $text );
868 function localiseLineNumbersCb( $matches ) {
870 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
871 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
876 * If there are revisions between the ones being compared, return a note saying so.
878 function getMultiNotice() {
879 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
882 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
883 // Comparing two different pages? Count would be meaningless.
887 $oldid = $this->mOldRev
->getId();
888 $newid = $this->mNewRev
->getId();
889 if ( $oldid > $newid ) {
890 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
893 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
897 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
902 * Add the header to a diff body
904 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
906 $header = "<table class='diff'>";
907 if( $diff ) { // Safari/Chrome show broken output if cols not used
909 <col class='diff-marker' />
910 <col class='diff-content' />
911 <col class='diff-marker' />
912 <col class='diff-content' />";
917 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
918 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
922 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
924 return $header . $diff . "</table>";
928 * Use specified text instead of loading from the database
930 function setText( $oldText, $newText ) {
931 $this->mOldtext
= $oldText;
932 $this->mNewtext
= $newText;
933 $this->mTextLoaded
= 2;
934 $this->mRevisionsLoaded
= true;
938 * Load revision metadata for the specified articles. If newid is 0, then compare
939 * the old article in oldid to the current article; if oldid is 0, then
940 * compare the current article to the immediately previous one (ignoring the
943 * If oldid is false, leave the corresponding revision object set
944 * to false. This is impossible via ordinary user input, and is provided for
947 function loadRevisionData() {
948 global $wgLang, $wgUser;
949 if ( $this->mRevisionsLoaded
) {
952 // Whether it succeeds or fails, we don't want to try again
953 $this->mRevisionsLoaded
= true;
956 // Load the new revision object
957 $this->mNewRev
= $this->mNewid
958 ? Revision
::newFromId( $this->mNewid
)
959 : Revision
::newFromTitle( $this->mTitle
);
960 if( !$this->mNewRev
instanceof Revision
)
963 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
964 $this->mNewid
= $this->mNewRev
->getId();
966 // Check if page is editable
967 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
969 // Set assorted variables
970 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
971 $dateofrev = $wgLang->date( $this->mNewRev
->getTimestamp(), true );
972 $timeofrev = $wgLang->time( $this->mNewRev
->getTimestamp(), true );
973 $this->mNewPage
= $this->mNewRev
->getTitle();
974 if( $this->mNewRev
->isCurrent() ) {
975 $newLink = $this->mNewPage
->escapeLocalUrl( array(
976 'oldid' => $this->mNewid
978 $this->mPagetitle
= htmlspecialchars( wfMsg(
984 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
988 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
989 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
991 $newLink = $this->mNewPage
->escapeLocalUrl( array(
992 'oldid' => $this->mNewid
994 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
996 'oldid' => $this->mNewid
998 $this->mPagetitle
= htmlspecialchars( wfMsg(
1005 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
1006 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1008 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
1009 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
1010 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
1011 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
1014 // Load the old revision object
1015 $this->mOldRev
= false;
1016 if( $this->mOldid
) {
1017 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1018 } elseif ( $this->mOldid
=== 0 ) {
1019 $rev = $this->mNewRev
->getPrevious();
1021 $this->mOldid
= $rev->getId();
1022 $this->mOldRev
= $rev;
1024 // No previous revision; mark to show as first-version only.
1025 $this->mOldid
= false;
1026 $this->mOldRev
= false;
1028 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
1030 if( is_null( $this->mOldRev
) ) {
1034 if ( $this->mOldRev
) {
1035 $this->mOldPage
= $this->mOldRev
->getTitle();
1037 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
1038 $dateofrev = $wgLang->date( $this->mOldRev
->getTimestamp(), true );
1039 $timeofrev = $wgLang->time( $this->mOldRev
->getTimestamp(), true );
1040 $oldLink = $this->mOldPage
->escapeLocalUrl( array(
1041 'oldid' => $this->mOldid
1043 $oldEdit = $this->mOldPage
->escapeLocalUrl( array(
1045 'oldid' => $this->mOldid
1047 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
1049 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
1050 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1051 // Add an "undo" link
1052 $newUndo = $this->mNewPage
->escapeLocalUrl( array(
1054 'undoafter' => $this->mOldid
,
1055 'undo' => $this->mNewid
1057 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
1058 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
1059 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1060 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
1063 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
1064 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
1065 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1066 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
1074 * Load the text of the revisions, as well as revision data.
1076 function loadText() {
1077 if ( $this->mTextLoaded
== 2 ) {
1080 // Whether it succeeds or fails, we don't want to try again
1081 $this->mTextLoaded
= 2;
1084 if ( !$this->loadRevisionData() ) {
1087 if ( $this->mOldRev
) {
1088 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1089 if ( $this->mOldtext
=== false ) {
1093 if ( $this->mNewRev
) {
1094 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1095 if ( $this->mNewtext
=== false ) {
1103 * Load the text of the new revision, not the old one
1105 function loadNewText() {
1106 if ( $this->mTextLoaded
>= 1 ) {
1109 $this->mTextLoaded
= 1;
1111 if ( !$this->loadRevisionData() ) {
1114 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1119 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
1121 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
1122 // You may copy this code freely under the conditions of the GPL.
1125 define('USE_ASSERTS', function_exists('assert'));
1130 * @ingroup DifferenceEngine
1137 function reverse() {
1138 trigger_error('pure virtual', E_USER_ERROR
);
1142 return $this->orig ?
sizeof($this->orig
) : 0;
1145 function nclosing() {
1146 return $this->closing ?
sizeof($this->closing
) : 0;
1153 * @ingroup DifferenceEngine
1155 class _DiffOp_Copy
extends _DiffOp
{
1158 function _DiffOp_Copy ($orig, $closing = false) {
1159 if (!is_array($closing))
1161 $this->orig
= $orig;
1162 $this->closing
= $closing;
1165 function reverse() {
1166 return new _DiffOp_Copy($this->closing
, $this->orig
);
1173 * @ingroup DifferenceEngine
1175 class _DiffOp_Delete
extends _DiffOp
{
1176 var $type = 'delete';
1178 function _DiffOp_Delete ($lines) {
1179 $this->orig
= $lines;
1180 $this->closing
= false;
1183 function reverse() {
1184 return new _DiffOp_Add($this->orig
);
1191 * @ingroup DifferenceEngine
1193 class _DiffOp_Add
extends _DiffOp
{
1196 function _DiffOp_Add ($lines) {
1197 $this->closing
= $lines;
1198 $this->orig
= false;
1201 function reverse() {
1202 return new _DiffOp_Delete($this->closing
);
1209 * @ingroup DifferenceEngine
1211 class _DiffOp_Change
extends _DiffOp
{
1212 var $type = 'change';
1214 function _DiffOp_Change ($orig, $closing) {
1215 $this->orig
= $orig;
1216 $this->closing
= $closing;
1219 function reverse() {
1220 return new _DiffOp_Change($this->closing
, $this->orig
);
1225 * Class used internally by Diff to actually compute the diffs.
1227 * The algorithm used here is mostly lifted from the perl module
1228 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1229 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1231 * More ideas are taken from:
1232 * http://www.ics.uci.edu/~eppstein/161/960229.html
1234 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1235 * diffutils-2.7, which can be found at:
1236 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1238 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1241 * Line length limits for robustness added by Tim Starling, 2005-08-31
1242 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1244 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1246 * @ingroup DifferenceEngine
1250 const MAX_XREF_LENGTH
= 10000;
1252 function diff ($from_lines, $to_lines){
1253 wfProfileIn( __METHOD__
);
1255 // Diff and store locally
1256 $this->diff_local($from_lines, $to_lines);
1258 // Merge edits when possible
1259 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1260 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1262 // Compute the edit operations.
1263 $n_from = sizeof($from_lines);
1264 $n_to = sizeof($to_lines);
1268 while ($xi < $n_from ||
$yi < $n_to) {
1269 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1270 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1272 // Skip matching "snake".
1274 while ( $xi < $n_from && $yi < $n_to
1275 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1276 $copy[] = $from_lines[$xi++
];
1280 $edits[] = new _DiffOp_Copy($copy);
1282 // Find deletes & adds.
1284 while ($xi < $n_from && $this->xchanged
[$xi])
1285 $delete[] = $from_lines[$xi++
];
1288 while ($yi < $n_to && $this->ychanged
[$yi])
1289 $add[] = $to_lines[$yi++
];
1291 if ($delete && $add)
1292 $edits[] = new _DiffOp_Change($delete, $add);
1294 $edits[] = new _DiffOp_Delete($delete);
1296 $edits[] = new _DiffOp_Add($add);
1298 wfProfileOut( __METHOD__
);
1302 function diff_local ($from_lines, $to_lines) {
1303 global $wgExternalDiffEngine;
1304 wfProfileIn( __METHOD__
);
1306 if($wgExternalDiffEngine == 'wikidiff3'){
1308 $wikidiff3 = new WikiDiff3();
1309 $wikidiff3->diff($from_lines, $to_lines);
1310 $this->xchanged
= $wikidiff3->removed
;
1311 $this->ychanged
= $wikidiff3->added
;
1315 $n_from = sizeof($from_lines);
1316 $n_to = sizeof($to_lines);
1317 $this->xchanged
= $this->ychanged
= array();
1318 $this->xv
= $this->yv
= array();
1319 $this->xind
= $this->yind
= array();
1321 unset($this->in_seq
);
1324 // Skip leading common lines.
1325 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1326 if ($from_lines[$skip] !== $to_lines[$skip])
1328 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1330 // Skip trailing common lines.
1331 $xi = $n_from; $yi = $n_to;
1332 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1333 if ($from_lines[$xi] !== $to_lines[$yi])
1335 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1338 // Ignore lines which do not exist in both files.
1339 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1340 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1343 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1344 $line = $to_lines[$yi];
1345 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1347 $yhash[$this->_line_hash($line)] = 1;
1348 $this->yv
[] = $line;
1349 $this->yind
[] = $yi;
1351 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1352 $line = $from_lines[$xi];
1353 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1355 $this->xv
[] = $line;
1356 $this->xind
[] = $xi;
1360 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1362 wfProfileOut( __METHOD__
);
1366 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1368 function _line_hash( $line ) {
1369 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1370 return md5( $line );
1376 /* Divide the Largest Common Subsequence (LCS) of the sequences
1377 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1380 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1381 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1382 * sub sequences. The first sub-sequence is contained in [X0, X1),
1383 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1384 * that (X0, Y0) == (XOFF, YOFF) and
1385 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1387 * This function assumes that the first lines of the specified portions
1388 * of the two files do not match, and likewise that the last lines do not
1389 * match. The caller must trim matching lines from the beginning and end
1390 * of the portions it is going to specify.
1392 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1395 if ($xlim - $xoff > $ylim - $yoff) {
1396 // Things seems faster (I'm not sure I understand why)
1397 // when the shortest sequence in X.
1399 list ($xoff, $xlim, $yoff, $ylim)
1400 = array( $yoff, $ylim, $xoff, $xlim);
1404 for ($i = $ylim - 1; $i >= $yoff; $i--)
1405 $ymatches[$this->xv
[$i]][] = $i;
1407 for ($i = $ylim - 1; $i >= $yoff; $i--)
1408 $ymatches[$this->yv
[$i]][] = $i;
1411 $this->seq
[0]= $yoff - 1;
1412 $this->in_seq
= array();
1413 $ymids[0] = array();
1415 $numer = $xlim - $xoff +
$nchunks - 1;
1417 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1419 for ($i = 0; $i <= $this->lcs
; $i++
)
1420 $ymids[$i][$chunk-1] = $this->seq
[$i];
1422 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1423 for ( ; $x < $x1; $x++
) {
1424 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1425 if (empty($ymatches[$line]))
1427 $matches = $ymatches[$line];
1429 while (list ($junk, $y) = each($matches))
1430 if (empty($this->in_seq
[$y])) {
1431 $k = $this->_lcs_pos($y);
1432 USE_ASSERTS
&& assert($k > 0);
1433 $ymids[$k] = $ymids[$k-1];
1436 while (list ( /* $junk */, $y) = each($matches)) {
1437 if ($y > $this->seq
[$k-1]) {
1438 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1439 // Optimization: this is a common case:
1440 // next match is just replacing previous match.
1441 $this->in_seq
[$this->seq
[$k]] = false;
1442 $this->seq
[$k] = $y;
1443 $this->in_seq
[$y] = 1;
1444 } else if (empty($this->in_seq
[$y])) {
1445 $k = $this->_lcs_pos($y);
1446 USE_ASSERTS
&& assert($k > 0);
1447 $ymids[$k] = $ymids[$k-1];
1453 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1454 $ymid = $ymids[$this->lcs
];
1455 for ($n = 0; $n < $nchunks - 1; $n++
) {
1456 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1457 $y1 = $ymid[$n] +
1;
1458 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1460 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1462 return array($this->lcs
, $seps);
1465 function _lcs_pos ($ypos) {
1467 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1468 $this->seq
[++
$this->lcs
] = $ypos;
1469 $this->in_seq
[$ypos] = 1;
1474 while ($beg < $end) {
1475 $mid = (int)(($beg +
$end) / 2);
1476 if ( $ypos > $this->seq
[$mid] )
1482 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1484 $this->in_seq
[$this->seq
[$end]] = false;
1485 $this->seq
[$end] = $ypos;
1486 $this->in_seq
[$ypos] = 1;
1490 /* Find LCS of two sequences.
1492 * The results are recorded in the vectors $this->{x,y}changed[], by
1493 * storing a 1 in the element for each line that is an insertion
1494 * or deletion (ie. is not in the LCS).
1496 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1498 * Note that XLIM, YLIM are exclusive bounds.
1499 * All line numbers are origin-0 and discarded lines are not counted.
1501 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1502 // Slide down the bottom initial diagonal.
1503 while ($xoff < $xlim && $yoff < $ylim
1504 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1509 // Slide up the top initial diagonal.
1510 while ($xlim > $xoff && $ylim > $yoff
1511 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1516 if ($xoff == $xlim ||
$yoff == $ylim)
1519 // This is ad hoc but seems to work well.
1520 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1521 //$nchunks = max(2,min(8,(int)$nchunks));
1522 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1524 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1528 // X and Y sequences have no common subsequence:
1529 // mark all changed.
1530 while ($yoff < $ylim)
1531 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1532 while ($xoff < $xlim)
1533 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1535 // Use the partitions to split this problem into subproblems.
1538 while ($pt2 = next($seps)) {
1539 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1545 /* Adjust inserts/deletes of identical lines to join changes
1546 * as much as possible.
1548 * We do something when a run of changed lines include a
1549 * line at one end and has an excluded, identical line at the other.
1550 * We are free to choose which identical line is included.
1551 * `compareseq' usually chooses the one at the beginning,
1552 * but usually it is cleaner to consider the following identical line
1553 * to be the "change".
1555 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1557 function _shift_boundaries ($lines, &$changed, $other_changed) {
1558 wfProfileIn( __METHOD__
);
1562 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1563 $len = sizeof($lines);
1564 $other_len = sizeof($other_changed);
1568 * Scan forwards to find beginning of another run of changes.
1569 * Also keep track of the corresponding point in the other file.
1571 * Throughout this code, $i and $j are adjusted together so that
1572 * the first $i elements of $changed and the first $j elements
1573 * of $other_changed both contain the same number of zeros
1574 * (unchanged lines).
1575 * Furthermore, $j is always kept so that $j == $other_len or
1576 * $other_changed[$j] == false.
1578 while ($j < $other_len && $other_changed[$j])
1581 while ($i < $len && ! $changed[$i]) {
1582 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1584 while ($j < $other_len && $other_changed[$j])
1593 // Find the end of this run of changes.
1594 while (++
$i < $len && $changed[$i])
1599 * Record the length of this run of changes, so that
1600 * we can later determine whether the run has grown.
1602 $runlength = $i - $start;
1605 * Move the changed region back, so long as the
1606 * previous unchanged line matches the last changed one.
1607 * This merges with previous changed regions.
1609 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1610 $changed[--$start] = 1;
1611 $changed[--$i] = false;
1612 while ($start > 0 && $changed[$start - 1])
1614 USE_ASSERTS
&& assert('$j > 0');
1615 while ($other_changed[--$j])
1617 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1621 * Set CORRESPONDING to the end of the changed run, at the last
1622 * point where it corresponds to a changed run in the other file.
1623 * CORRESPONDING == LEN means no such point has been found.
1625 $corresponding = $j < $other_len ?
$i : $len;
1628 * Move the changed region forward, so long as the
1629 * first changed line matches the following unchanged one.
1630 * This merges with following changed regions.
1631 * Do this second, so that if there are no merges,
1632 * the changed region is moved forward as far as possible.
1634 while ($i < $len && $lines[$start] == $lines[$i]) {
1635 $changed[$start++
] = false;
1637 while ($i < $len && $changed[$i])
1640 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1642 if ($j < $other_len && $other_changed[$j]) {
1643 $corresponding = $i;
1644 while ($j < $other_len && $other_changed[$j])
1648 } while ($runlength != $i - $start);
1651 * If possible, move the fully-merged run of changes
1652 * back to a corresponding run in the other file.
1654 while ($corresponding < $i) {
1655 $changed[--$start] = 1;
1657 USE_ASSERTS
&& assert('$j > 0');
1658 while ($other_changed[--$j])
1660 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1663 wfProfileOut( __METHOD__
);
1668 * Class representing a 'diff' between two sequences of strings.
1671 * @ingroup DifferenceEngine
1679 * Computes diff between sequences of strings.
1681 * @param $from_lines array An array of strings.
1682 * (Typically these are lines from a file.)
1683 * @param $to_lines array An array of strings.
1685 function Diff($from_lines, $to_lines) {
1686 $eng = new _DiffEngine
;
1687 $this->edits
= $eng->diff($from_lines, $to_lines);
1688 //$this->_check($from_lines, $to_lines);
1692 * Compute reversed Diff.
1696 * $diff = new Diff($lines1, $lines2);
1697 * $rev = $diff->reverse();
1698 * @return object A Diff object representing the inverse of the
1701 function reverse () {
1703 $rev->edits
= array();
1704 foreach ($this->edits
as $edit) {
1705 $rev->edits
[] = $edit->reverse();
1711 * Check for empty diff.
1713 * @return bool True iff two sequences were identical.
1715 function isEmpty () {
1716 foreach ($this->edits
as $edit) {
1717 if ($edit->type
!= 'copy')
1724 * Compute the length of the Longest Common Subsequence (LCS).
1726 * This is mostly for diagnostic purposed.
1728 * @return int The length of the LCS.
1732 foreach ($this->edits
as $edit) {
1733 if ($edit->type
== 'copy')
1734 $lcs +
= sizeof($edit->orig
);
1740 * Get the original set of lines.
1742 * This reconstructs the $from_lines parameter passed to the
1745 * @return array The original sequence of strings.
1750 foreach ($this->edits
as $edit) {
1752 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1758 * Get the closing set of lines.
1760 * This reconstructs the $to_lines parameter passed to the
1763 * @return array The sequence of strings.
1765 function closing() {
1768 foreach ($this->edits
as $edit) {
1770 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1776 * Check a Diff for validity.
1778 * This is here only for debugging purposes.
1780 function _check ($from_lines, $to_lines) {
1781 wfProfileIn( __METHOD__
);
1782 if (serialize($from_lines) != serialize($this->orig()))
1783 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1784 if (serialize($to_lines) != serialize($this->closing()))
1785 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1787 $rev = $this->reverse();
1788 if (serialize($to_lines) != serialize($rev->orig()))
1789 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1790 if (serialize($from_lines) != serialize($rev->closing()))
1791 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1795 foreach ($this->edits
as $edit) {
1796 if ( $prevtype == $edit->type
)
1797 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1798 $prevtype = $edit->type
;
1801 $lcs = $this->lcs();
1802 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1803 wfProfileOut( __METHOD__
);
1808 * @todo document, bad name.
1810 * @ingroup DifferenceEngine
1812 class MappedDiff
extends Diff
1817 * Computes diff between sequences of strings.
1819 * This can be used to compute things like
1820 * case-insensitve diffs, or diffs which ignore
1821 * changes in white-space.
1823 * @param $from_lines array An array of strings.
1824 * (Typically these are lines from a file.)
1826 * @param $to_lines array An array of strings.
1828 * @param $mapped_from_lines array This array should
1829 * have the same size number of elements as $from_lines.
1830 * The elements in $mapped_from_lines and
1831 * $mapped_to_lines are what is actually compared
1832 * when computing the diff.
1834 * @param $mapped_to_lines array This array should
1835 * have the same number of elements as $to_lines.
1837 function MappedDiff($from_lines, $to_lines,
1838 $mapped_from_lines, $mapped_to_lines) {
1839 wfProfileIn( __METHOD__
);
1841 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1842 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1844 $this->Diff($mapped_from_lines, $mapped_to_lines);
1847 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1848 $orig = &$this->edits
[$i]->orig
;
1849 if (is_array($orig)) {
1850 $orig = array_slice($from_lines, $xi, sizeof($orig));
1851 $xi +
= sizeof($orig);
1854 $closing = &$this->edits
[$i]->closing
;
1855 if (is_array($closing)) {
1856 $closing = array_slice($to_lines, $yi, sizeof($closing));
1857 $yi +
= sizeof($closing);
1860 wfProfileOut( __METHOD__
);
1865 * A class to format Diffs
1867 * This class formats the diff in classic diff format.
1868 * It is intended that this class be customized via inheritance,
1869 * to obtain fancier outputs.
1872 * @ingroup DifferenceEngine
1874 class DiffFormatter
{
1876 * Number of leading context "lines" to preserve.
1878 * This should be left at zero for this class, but subclasses
1879 * may want to set this to other values.
1881 var $leading_context_lines = 0;
1884 * Number of trailing context "lines" to preserve.
1886 * This should be left at zero for this class, but subclasses
1887 * may want to set this to other values.
1889 var $trailing_context_lines = 0;
1894 * @param $diff object A Diff object.
1895 * @return string The formatted output.
1897 function format($diff) {
1898 wfProfileIn( __METHOD__
);
1904 $nlead = $this->leading_context_lines
;
1905 $ntrail = $this->trailing_context_lines
;
1907 $this->_start_diff();
1909 foreach ($diff->edits
as $edit) {
1910 if ($edit->type
== 'copy') {
1911 if (is_array($block)) {
1912 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1917 $context = array_slice($edit->orig
, 0, $ntrail);
1918 $block[] = new _DiffOp_Copy($context);
1920 $this->_block($x0, $ntrail +
$xi - $x0,
1921 $y0, $ntrail +
$yi - $y0,
1926 $context = $edit->orig
;
1929 if (! is_array($block)) {
1930 $context = array_slice($context, sizeof($context) - $nlead);
1931 $x0 = $xi - sizeof($context);
1932 $y0 = $yi - sizeof($context);
1935 $block[] = new _DiffOp_Copy($context);
1941 $xi +
= sizeof($edit->orig
);
1943 $yi +
= sizeof($edit->closing
);
1946 if (is_array($block))
1947 $this->_block($x0, $xi - $x0,
1951 $end = $this->_end_diff();
1952 wfProfileOut( __METHOD__
);
1956 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1957 wfProfileIn( __METHOD__
);
1958 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1959 foreach ($edits as $edit) {
1960 if ($edit->type
== 'copy')
1961 $this->_context($edit->orig
);
1962 elseif ($edit->type
== 'add')
1963 $this->_added($edit->closing
);
1964 elseif ($edit->type
== 'delete')
1965 $this->_deleted($edit->orig
);
1966 elseif ($edit->type
== 'change')
1967 $this->_changed($edit->orig
, $edit->closing
);
1969 trigger_error('Unknown edit type', E_USER_ERROR
);
1971 $this->_end_block();
1972 wfProfileOut( __METHOD__
);
1975 function _start_diff() {
1979 function _end_diff() {
1980 $val = ob_get_contents();
1985 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1987 $xbeg .= "," . ($xbeg +
$xlen - 1);
1989 $ybeg .= "," . ($ybeg +
$ylen - 1);
1991 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1994 function _start_block($header) {
1995 echo $header . "\n";
1998 function _end_block() {
2001 function _lines($lines, $prefix = ' ') {
2002 foreach ($lines as $line)
2003 echo "$prefix $line\n";
2006 function _context($lines) {
2007 $this->_lines($lines);
2010 function _added($lines) {
2011 $this->_lines($lines, '>');
2013 function _deleted($lines) {
2014 $this->_lines($lines, '<');
2017 function _changed($orig, $closing) {
2018 $this->_deleted($orig);
2020 $this->_added($closing);
2025 * A formatter that outputs unified diffs
2026 * @ingroup DifferenceEngine
2029 class UnifiedDiffFormatter
extends DiffFormatter
{
2030 var $leading_context_lines = 2;
2031 var $trailing_context_lines = 2;
2033 function _added($lines) {
2034 $this->_lines($lines, '+');
2036 function _deleted($lines) {
2037 $this->_lines($lines, '-');
2039 function _changed($orig, $closing) {
2040 $this->_deleted($orig);
2041 $this->_added($closing);
2043 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
2044 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
2049 * A pseudo-formatter that just passes along the Diff::$edits array
2050 * @ingroup DifferenceEngine
2052 class ArrayDiffFormatter
extends DiffFormatter
{
2053 function format($diff) {
2057 foreach($diff->edits
as $edit)
2058 switch($edit->type
) {
2060 foreach($edit->closing
as $l) {
2064 'newline' => $newline++
2069 foreach($edit->orig
as $l) {
2071 'action' => 'delete',
2073 'oldline' => $oldline++
,
2078 foreach($edit->orig
as $i => $l) {
2080 'action' => 'change',
2082 'new' => @$edit->closing
[$i],
2083 'oldline' => $oldline++
,
2084 'newline' => $newline++
,
2089 $oldline +
= count($edit->orig
);
2090 $newline +
= count($edit->orig
);
2097 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
2101 define('NBSP', ' '); // iso-8859-x non-breaking space.
2106 * @ingroup DifferenceEngine
2108 class _HWLDF_WordAccumulator
{
2109 function _HWLDF_WordAccumulator () {
2110 $this->_lines
= array();
2116 function _flushGroup ($new_tag) {
2117 if ($this->_group
!== '') {
2118 if ($this->_tag
== 'ins')
2119 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
2120 htmlspecialchars ( $this->_group
) . '</ins>';
2121 elseif ($this->_tag
== 'del')
2122 $this->_line
.= '<del class="diffchange diffchange-inline">' .
2123 htmlspecialchars ( $this->_group
) . '</del>';
2125 $this->_line
.= htmlspecialchars ( $this->_group
);
2128 $this->_tag
= $new_tag;
2131 function _flushLine ($new_tag) {
2132 $this->_flushGroup($new_tag);
2133 if ($this->_line
!= '')
2134 array_push ( $this->_lines
, $this->_line
);
2136 # make empty lines visible by inserting an NBSP
2137 array_push ( $this->_lines
, NBSP
);
2141 function addWords ($words, $tag = '') {
2142 if ($tag != $this->_tag
)
2143 $this->_flushGroup($tag);
2145 foreach ($words as $word) {
2146 // new-line should only come as first char of word.
2149 if ($word[0] == "\n") {
2150 $this->_flushLine($tag);
2151 $word = substr($word, 1);
2153 assert(!strstr($word, "\n"));
2154 $this->_group
.= $word;
2158 function getLines() {
2159 $this->_flushLine('~done');
2160 return $this->_lines
;
2167 * @ingroup DifferenceEngine
2169 class WordLevelDiff
extends MappedDiff
{
2170 const MAX_LINE_LENGTH
= 10000;
2172 function WordLevelDiff ($orig_lines, $closing_lines) {
2173 wfProfileIn( __METHOD__
);
2175 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
2176 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
2178 $this->MappedDiff($orig_words, $closing_words,
2179 $orig_stripped, $closing_stripped);
2180 wfProfileOut( __METHOD__
);
2183 function _split($lines) {
2184 wfProfileIn( __METHOD__
);
2187 $stripped = array();
2189 foreach ( $lines as $line ) {
2190 # If the line is too long, just pretend the entire line is one big word
2191 # This prevents resource exhaustion problems
2198 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2200 $stripped[] = $line;
2203 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2206 $words = array_merge( $words, $m[0] );
2207 $stripped = array_merge( $stripped, $m[1] );
2211 wfProfileOut( __METHOD__
);
2212 return array($words, $stripped);
2216 wfProfileIn( __METHOD__
);
2217 $orig = new _HWLDF_WordAccumulator
;
2219 foreach ($this->edits
as $edit) {
2220 if ($edit->type
== 'copy')
2221 $orig->addWords($edit->orig
);
2222 elseif ($edit->orig
)
2223 $orig->addWords($edit->orig
, 'del');
2225 $lines = $orig->getLines();
2226 wfProfileOut( __METHOD__
);
2230 function closing () {
2231 wfProfileIn( __METHOD__
);
2232 $closing = new _HWLDF_WordAccumulator
;
2234 foreach ($this->edits
as $edit) {
2235 if ($edit->type
== 'copy')
2236 $closing->addWords($edit->closing
);
2237 elseif ($edit->closing
)
2238 $closing->addWords($edit->closing
, 'ins');
2240 $lines = $closing->getLines();
2241 wfProfileOut( __METHOD__
);
2247 * Wikipedia Table style diff formatter.
2250 * @ingroup DifferenceEngine
2252 class TableDiffFormatter
extends DiffFormatter
{
2253 function TableDiffFormatter() {
2254 $this->leading_context_lines
= 2;
2255 $this->trailing_context_lines
= 2;
2258 public static function escapeWhiteSpace( $msg ) {
2259 $msg = preg_replace( '/^ /m', ' ', $msg );
2260 $msg = preg_replace( '/ $/m', ' ', $msg );
2261 $msg = preg_replace( '/ /', ' ', $msg );
2265 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2266 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2267 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2271 function _start_block( $header ) {
2275 function _end_block() {
2278 function _lines( $lines, $prefix=' ', $color='white' ) {
2281 # HTML-escape parameter before calling this
2282 function addedLine( $line ) {
2283 return $this->wrapLine( '+', 'diff-addedline', $line );
2286 # HTML-escape parameter before calling this
2287 function deletedLine( $line ) {
2288 return $this->wrapLine( '-', 'diff-deletedline', $line );
2291 # HTML-escape parameter before calling this
2292 function contextLine( $line ) {
2293 return $this->wrapLine( ' ', 'diff-context', $line );
2296 private function wrapLine( $marker, $class, $line ) {
2297 if( $line !== '' ) {
2298 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2299 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2301 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2304 function emptyLine() {
2305 return '<td colspan="2"> </td>';
2308 function _added( $lines ) {
2309 foreach ($lines as $line) {
2310 echo '<tr>' . $this->emptyLine() .
2311 $this->addedLine( '<ins class="diffchange">' .
2312 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2316 function _deleted($lines) {
2317 foreach ($lines as $line) {
2318 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2319 htmlspecialchars ( $line ) . '</del>' ) .
2320 $this->emptyLine() . "</tr>\n";
2324 function _context( $lines ) {
2325 foreach ($lines as $line) {
2327 $this->contextLine( htmlspecialchars ( $line ) ) .
2328 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2332 function _changed( $orig, $closing ) {
2333 wfProfileIn( __METHOD__
);
2335 $diff = new WordLevelDiff( $orig, $closing );
2336 $del = $diff->orig();
2337 $add = $diff->closing();
2339 # Notice that WordLevelDiff returns HTML-escaped output.
2340 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2342 while ( $line = array_shift( $del ) ) {
2343 $aline = array_shift( $add );
2344 echo '<tr>' . $this->deletedLine( $line ) .
2345 $this->addedLine( $aline ) . "</tr>\n";
2347 foreach ($add as $line) { # If any leftovers
2348 echo '<tr>' . $this->emptyLine() .
2349 $this->addedLine( $line ) . "</tr>\n";
2351 wfProfileOut( __METHOD__
);