2df9e145bbdceee76ab819ba9efbc465449a5bde
3 * @defgroup DifferenceEngine DifferenceEngine
7 * Constant to indicate diff cache compatibility.
8 * Bump this when changing the diff formatting in a way that
9 * fixes important bugs or such to force cached diff views to
12 define( 'MW_DIFF_VERSION', '1.11a' );
16 * @ingroup DifferenceEngine
18 class DifferenceEngine
{
22 var $mOldid, $mNewid, $mTitle;
23 var $mOldtitle, $mNewtitle, $mPagetitle;
24 var $mOldtext, $mNewtext;
25 var $mOldPage, $mNewPage;
26 var $mRcidMarkPatrolled;
27 var $mOldRev, $mNewRev;
28 var $mRevisionsLoaded = false; // Have the revisions been loaded
29 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
30 var $mCacheHit = false; // Was the diff fetched from cache?
33 protected $unhide = false;
38 * @param $titleObj Title object that the diff is associated with
39 * @param $old Integer: old ID we want to show and diff with.
40 * @param $new String: either 'prev' or 'next'.
41 * @param $rcid Integer: ??? FIXME (default 0)
42 * @param $refreshCache boolean If set, refreshes the diff cache
43 * @param $htmldiff boolean If set, output using HTMLDiff instead of raw wikicode diff
44 * @param $unhide boolean If set, allow viewing deleted revs
46 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0,
47 $refreshCache = false, $htmldiff = false, $unhide = false )
49 $this->mTitle
= $titleObj;
50 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
52 if ( 'prev' === $new ) {
53 # Show diff between revision $old and the previous one.
54 # Get previous one from DB.
55 $this->mNewid
= intval($old);
56 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
57 } elseif ( 'next' === $new ) {
58 # Show diff between revision $old and the next one.
59 # Get next one from DB.
60 $this->mOldid
= intval($old);
61 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
62 if ( false === $this->mNewid
) {
63 # if no result, NewId points to the newest old revision. The only newer
64 # revision is cur, which is "0".
68 $this->mOldid
= intval($old);
69 $this->mNewid
= intval($new);
70 wfRunHooks( 'NewDifferenceEngine', array(&$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new) );
72 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
73 $this->mRefreshCache
= $refreshCache;
74 $this->htmldiff
= $htmldiff;
75 $this->unhide
= $unhide;
82 function wasCacheHit() {
83 return $this->mCacheHit
;
94 function showDiffPage( $diffOnly = false ) {
95 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
96 wfProfileIn( __METHOD__
);
99 # If external diffs are enabled both globally and for the user,
100 # we'll use the application/x-external-editor interface to call
101 # an external diff tool like kompare, kdiff3, etc.
102 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
103 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
105 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
106 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
107 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
108 $special=$wgLang->getNsText(NS_SPECIAL
);
113 Script={$wgServer}{$wgScript}
114 Special namespace={$special}
128 $wgOut->setArticleFlag( false );
129 if ( !$this->loadRevisionData() ) {
130 $t = $this->mTitle
->getPrefixedText();
131 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
132 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
133 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
134 wfProfileOut( __METHOD__
);
138 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
140 if ( $this->mNewRev
->isCurrent() ) {
141 $wgOut->setArticleFlag( true );
144 # mOldid is false if the difference engine is called with a "vague" query for
145 # a diff between a version V and its previous version V' AND the version V
146 # is the first version of that article. In that case, V' does not exist.
147 if ( $this->mOldid
=== false ) {
148 $this->showFirstRevision();
149 $this->renderNewRevision(); // should we respect $diffOnly here or not?
150 wfProfileOut( __METHOD__
);
154 $wgOut->suppressQuickbar();
156 $oldTitle = $this->mOldPage
->getPrefixedText();
157 $newTitle = $this->mNewPage
->getPrefixedText();
158 if( $oldTitle == $newTitle ) {
159 $wgOut->setPageTitle( $newTitle );
161 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
163 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
164 $wgOut->setRobotPolicy( 'noindex,nofollow' );
166 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
167 $wgOut->loginToUse();
170 wfProfileOut( __METHOD__
);
174 $sk = $wgUser->getSkin();
176 // Check if page is editable
177 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
178 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
179 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
184 // Prepare a change patrol link, if applicable
185 if( $wgUseRCPatrol && $this->mTitle
->userCan('patrol') ) {
186 // If we've been given an explicit change identifier, use it; saves time
187 if( $this->mRcidMarkPatrolled
) {
188 $rcid = $this->mRcidMarkPatrolled
;
189 $rc = RecentChange
::newFromId( $rcid );
190 // Already patrolled?
191 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ?
$rcid : 0;
193 // Look for an unpatrolled change corresponding to this diff
194 $db = wfGetDB( DB_SLAVE
);
195 $change = RecentChange
::newFromConds(
197 // Redundant user,timestamp condition so we can use the existing index
198 'rc_user_text' => $this->mNewRev
->getRawUserText(),
199 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
200 'rc_this_oldid' => $this->mNewid
,
201 'rc_last_oldid' => $this->mOldid
,
206 if( $change instanceof RecentChange
) {
207 $rcid = $change->mAttribs
['rc_id'];
208 $this->mRcidMarkPatrolled
= $rcid;
216 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj( $this->mTitle
,
217 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$rcid}" ) . ']</span>';
226 # Carry over 'diffonly' param via navigation links
227 if( $diffOnly != $wgUser->getBoolOption('diffonly') ) {
228 $diffOnlyArg = '&diffonly='.$diffOnly;
230 $htmldiffarg = $this->htmlDiffArgument();
231 # Make "previous revision link"
232 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
233 "diff=prev&oldid={$this->mOldid}{$htmldiffarg}{$diffOnlyArg}", '', '', 'id="differences-prevlink"' );
234 # Make "next revision link"
235 if( $this->mNewRev
->isCurrent() ) {
236 $nextlink = ' ';
238 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
239 "diff=next&oldid={$this->mNewid}{$htmldiffarg}{$diffOnlyArg}", '', '', 'id="differences-nextlink"' );
245 if( $this->mOldRev
->isMinor() ) {
246 $oldminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
248 if( $this->mNewRev
->isMinor() ) {
249 $newminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
252 $rdel = ''; $ldel = '';
253 if( $wgUser->isAllowed( 'deleterevision' ) ) {
254 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
255 // If revision was hidden from sysops
256 $ldel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
259 'type' => 'revision',
260 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
261 'ids' => $this->mOldRev
->getId()
263 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
265 $ldel = " $ldel ";
266 // We don't currently handle well changing the top revision's settings
267 if( $this->mNewRev
->isCurrent() ) {
268 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
269 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
270 // If revision was hidden from sysops
271 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
274 'type' => 'revision',
275 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
276 'ids' => $this->mNewRev
->getId()
278 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
280 $rdel = " $rdel ";
283 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
284 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
285 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
286 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
287 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
288 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
289 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
290 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
292 # Check if this user can see the revisions
293 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
)
294 && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
295 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
)
296 ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
297 # Output the diff if allowed...
298 if( $deleted && (!$this->unhide ||
!$allowed) ) {
299 $this->showDiffStyle();
300 $multi = $this->getMultiNotice();
301 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
303 # Give explanation for why revision is not visible
304 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
305 array( 'rev-deleted-no-diff' ) );
307 # Give explanation and add a link to view the diff...
308 $link = $this->mTitle
->getFullUrl( "diff={$this->mNewid}&oldid={$this->mOldid}&unhide=1" );
309 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
310 array( 'rev-deleted-unhide-diff', $link ) );
312 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
313 $multi = $this->getMultiNotice();
314 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
315 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
316 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
317 $this->renderHtmlDiff();
319 if( $wgEnableHtmlDiff ) {
320 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
321 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
323 $this->showDiff( $oldHeader, $newHeader );
325 $this->renderNewRevision();
328 wfProfileOut( __METHOD__
);
332 * Show the new revision of the page.
334 function renderNewRevision() {
335 global $wgOut, $wgUser;
336 wfProfileIn( __METHOD__
);
338 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
339 # Add deleted rev tag if needed
340 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
341 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
342 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
343 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
346 if( !$this->mNewRev
->isCurrent() ) {
347 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
350 $this->loadNewText();
351 if( is_object( $this->mNewRev
) ) {
352 $wgOut->setRevisionId( $this->mNewRev
->getId() );
355 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
356 // Stolen from Article::view --AG 2007-10-11
357 // Give hooks a chance to customise the output
358 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
359 // Wrap the whole lot in a <pre> and don't parse
361 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
362 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
363 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
364 $wgOut->addHTML( "\n</pre>\n" );
367 $wgOut->addWikiTextTidy( $this->mNewtext
);
370 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
371 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
373 # Add redundant patrol link on bottom...
374 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
375 $sk = $wgUser->getSkin();
377 "<div class='patrollink'>[" . $sk->makeKnownLinkObj( $this->mTitle
,
378 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) .
383 wfProfileOut( __METHOD__
);
387 function renderHtmlDiff() {
388 global $wgOut, $wgParser, $wgDebugComments;
389 wfProfileIn( __METHOD__
);
391 $this->showDiffStyle();
393 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
394 #add deleted rev tag if needed
395 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
396 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
397 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
398 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
401 if( !$this->mNewRev
->isCurrent() ) {
402 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
408 if( is_object( $this->mOldRev
) ) {
409 $wgOut->setRevisionId( $this->mOldRev
->getId() );
412 $popts = $wgOut->parserOptions();
413 $oldTidy = $popts->setTidy( true );
414 $popts->setEditSection( false );
416 $parserOutput = $wgParser->parse( $this->mOldtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
417 $popts->setTidy( $oldTidy );
420 //$wgOut->addParserOutputNoText( $parserOutput );
421 $oldHtml = $parserOutput->getText();
422 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
425 if( is_object( $this->mNewRev
) ) {
426 $wgOut->setRevisionId( $this->mNewRev
->getId() );
429 $popts = $wgOut->parserOptions();
430 $oldTidy = $popts->setTidy( true );
432 $parserOutput = $wgParser->parse( $this->mNewtext
, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
433 $popts->setTidy( $oldTidy );
435 $wgOut->addParserOutputNoText( $parserOutput );
436 $newHtml = $parserOutput->getText();
437 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
439 unset($parserOutput, $popts);
441 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
442 $differ->htmlDiff($oldHtml, $newHtml);
443 if ( $wgDebugComments ) {
444 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
447 wfProfileOut( __METHOD__
);
451 * Show the first revision of an article. Uses normal diff headers in
452 * contrast to normal "old revision" display style.
454 function showFirstRevision() {
455 global $wgOut, $wgUser;
456 wfProfileIn( __METHOD__
);
458 # Get article text from the DB
460 if ( ! $this->loadNewText() ) {
461 $t = $this->mTitle
->getPrefixedText();
462 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
463 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
464 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
465 wfProfileOut( __METHOD__
);
468 if ( $this->mNewRev
->isCurrent() ) {
469 $wgOut->setArticleFlag( true );
472 # Check if user is allowed to look at this page. If not, bail out.
474 if ( !$this->mTitle
->userCanRead() ) {
475 $wgOut->loginToUse();
477 wfProfileOut( __METHOD__
);
478 throw new MWException("Permission Error: you do not have access to view this page");
481 # Prepare the header box
483 $sk = $wgUser->getSkin();
485 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
489 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
490 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
492 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
493 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
495 $wgOut->addHTML( $header );
497 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
498 $wgOut->setRobotPolicy( 'noindex,nofollow' );
500 wfProfileOut( __METHOD__
);
503 function htmlDiffArgument(){
504 global $wgEnableHtmlDiff;
505 if($wgEnableHtmlDiff){
507 return '&htmldiff=1';
509 return '&htmldiff=0';
517 * Get the diff text, send it to $wgOut
518 * Returns false if the diff could not be generated, otherwise returns true
520 function showDiff( $otitle, $ntitle ) {
522 $diff = $this->getDiff( $otitle, $ntitle );
523 if ( $diff === false ) {
524 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
527 $this->showDiffStyle();
528 $wgOut->addHTML( $diff );
534 * Add style sheets and supporting JS for diff display.
536 function showDiffStyle() {
537 global $wgStylePath, $wgStyleVersion, $wgOut;
538 $wgOut->addStyle( 'common/diff.css' );
540 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
541 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
545 * Get complete diff table, including header
547 * @param Title $otitle Old title
548 * @param Title $ntitle New title
551 function getDiff( $otitle, $ntitle ) {
552 $body = $this->getDiffBody();
553 if ( $body === false ) {
556 $multi = $this->getMultiNotice();
557 return $this->addHeader( $body, $otitle, $ntitle, $multi );
562 * Get the diff table body, without header
566 function getDiffBody() {
568 wfProfileIn( __METHOD__
);
569 $this->mCacheHit
= true;
570 // Check if the diff should be hidden from this user
571 if ( !$this->loadRevisionData() )
573 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
575 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
577 } else if ( $this->mOldRev
&& $this->mNewRev
&& $this->mOldRev
->getID() == $this->mNewRev
->getID() ) {
582 if ( $this->mOldid
&& $this->mNewid
) {
583 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
585 if ( !$this->mRefreshCache
) {
586 $difftext = $wgMemc->get( $key );
588 wfIncrStats( 'diff_cache_hit' );
589 $difftext = $this->localiseLineNumbers( $difftext );
590 $difftext .= "\n<!-- diff cache key $key -->\n";
591 wfProfileOut( __METHOD__
);
594 } // don't try to load but save the result
596 $this->mCacheHit
= false;
598 // Loadtext is permission safe, this just clears out the diff
599 if ( !$this->loadText() ) {
600 wfProfileOut( __METHOD__
);
604 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
606 // Save to cache for 7 days
607 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
608 wfIncrStats( 'diff_uncacheable' );
609 } else if ( $key !== false && $difftext !== false ) {
610 wfIncrStats( 'diff_cache_miss' );
611 $wgMemc->set( $key, $difftext, 7*86400 );
613 wfIncrStats( 'diff_uncacheable' );
615 // Replace line numbers with the text in the user's language
616 if ( $difftext !== false ) {
617 $difftext = $this->localiseLineNumbers( $difftext );
619 wfProfileOut( __METHOD__
);
624 * Make sure the proper modules are loaded before we try to
627 private function initDiffEngines() {
628 global $wgExternalDiffEngine;
629 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
630 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
631 wfSuppressWarnings();
632 dl( 'php_wikidiff.so' );
634 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
636 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
637 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
638 wfSuppressWarnings();
639 dl( 'php_wikidiff2.so' );
641 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
646 * Generate a diff, no caching
647 * $otext and $ntext must be already segmented
649 function generateDiffBody( $otext, $ntext ) {
650 global $wgExternalDiffEngine, $wgContLang;
652 $otext = str_replace( "\r\n", "\n", $otext );
653 $ntext = str_replace( "\r\n", "\n", $ntext );
655 $this->initDiffEngines();
657 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
658 # For historical reasons, external diff engine expects
659 # input text to be HTML-escaped already
660 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
661 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
662 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
663 $this->debug( 'wikidiff1' );
666 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
667 # Better external diff engine, the 2 may some day be dropped
668 # This one does the escaping and segmenting itself
669 wfProfileIn( 'wikidiff2_do_diff' );
670 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
671 $text .= $this->debug( 'wikidiff2' );
672 wfProfileOut( 'wikidiff2_do_diff' );
675 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
677 global $wgTmpDirectory;
678 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
679 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
681 $tempFile1 = fopen( $tempName1, "w" );
683 wfProfileOut( __METHOD__
);
686 $tempFile2 = fopen( $tempName2, "w" );
688 wfProfileOut( __METHOD__
);
691 fwrite( $tempFile1, $otext );
692 fwrite( $tempFile2, $ntext );
693 fclose( $tempFile1 );
694 fclose( $tempFile2 );
695 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
696 wfProfileIn( __METHOD__
. "-shellexec" );
697 $difftext = wfShellExec( $cmd );
698 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
699 wfProfileOut( __METHOD__
. "-shellexec" );
700 unlink( $tempName1 );
701 unlink( $tempName2 );
706 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
707 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
708 $diffs = new Diff( $ota, $nta );
709 $formatter = new TableDiffFormatter();
710 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
715 * Generate a debug comment indicating diff generating time,
716 * server node, and generator backend.
718 protected function debug( $generator="internal" ) {
719 global $wgShowHostnames;
720 $data = array( $generator );
721 if( $wgShowHostnames ) {
722 $data[] = wfHostname();
724 $data[] = wfTimestamp( TS_DB
);
725 return "<!-- diff generator: " .
734 * Replace line numbers with the text in the user's language
736 function localiseLineNumbers( $text ) {
737 return preg_replace_callback( '/<!--LINE (\d+)-->/',
738 array( &$this, 'localiseLineNumbersCb' ), $text );
741 function localiseLineNumbersCb( $matches ) {
743 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
748 * If there are revisions between the ones being compared, return a note saying so.
750 function getMultiNotice() {
751 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
754 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
755 // Comparing two different pages? Count would be meaningless.
759 $oldid = $this->mOldRev
->getId();
760 $newid = $this->mNewRev
->getId();
761 if ( $oldid > $newid ) {
762 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
765 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
769 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
774 * Add the header to a diff body
776 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
778 $header = "<table class='diff'>";
779 if( $diff ) { // Safari/Chrome show broken output if cols not used
781 <col class='diff-marker' />
782 <col class='diff-content' />
783 <col class='diff-marker' />
784 <col class='diff-content' />";
789 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
790 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
794 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
796 return $header . $diff . "</table>";
800 * Use specified text instead of loading from the database
802 function setText( $oldText, $newText ) {
803 $this->mOldtext
= $oldText;
804 $this->mNewtext
= $newText;
805 $this->mTextLoaded
= 2;
806 $this->mRevisionsLoaded
= true;
810 * Load revision metadata for the specified articles. If newid is 0, then compare
811 * the old article in oldid to the current article; if oldid is 0, then
812 * compare the current article to the immediately previous one (ignoring the
815 * If oldid is false, leave the corresponding revision object set
816 * to false. This is impossible via ordinary user input, and is provided for
819 function loadRevisionData() {
820 global $wgLang, $wgUser;
821 if ( $this->mRevisionsLoaded
) {
824 // Whether it succeeds or fails, we don't want to try again
825 $this->mRevisionsLoaded
= true;
828 // Load the new revision object
829 $this->mNewRev
= $this->mNewid
830 ? Revision
::newFromId( $this->mNewid
)
831 : Revision
::newFromTitle( $this->mTitle
);
832 if( !$this->mNewRev
instanceof Revision
)
835 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
836 $this->mNewid
= $this->mNewRev
->getId();
838 // Check if page is editable
839 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
841 // Set assorted variables
842 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
843 $this->mNewPage
= $this->mNewRev
->getTitle();
844 if( $this->mNewRev
->isCurrent() ) {
845 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
846 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev-asof', $timestamp ) );
847 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
849 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
850 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
852 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
853 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
854 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
856 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
857 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
859 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
860 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
861 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
862 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
865 // Load the old revision object
866 $this->mOldRev
= false;
867 if( $this->mOldid
) {
868 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
869 } elseif ( $this->mOldid
=== 0 ) {
870 $rev = $this->mNewRev
->getPrevious();
872 $this->mOldid
= $rev->getId();
873 $this->mOldRev
= $rev;
875 // No previous revision; mark to show as first-version only.
876 $this->mOldid
= false;
877 $this->mOldRev
= false;
879 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
881 if( is_null( $this->mOldRev
) ) {
885 if ( $this->mOldRev
) {
886 $this->mOldPage
= $this->mOldRev
->getTitle();
888 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
889 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
890 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
891 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
893 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
894 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
895 // Add an "undo" link
896 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
897 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
898 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
899 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
900 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
903 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
904 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
905 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
906 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
914 * Load the text of the revisions, as well as revision data.
916 function loadText() {
917 if ( $this->mTextLoaded
== 2 ) {
920 // Whether it succeeds or fails, we don't want to try again
921 $this->mTextLoaded
= 2;
924 if ( !$this->loadRevisionData() ) {
927 if ( $this->mOldRev
) {
928 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
929 if ( $this->mOldtext
=== false ) {
933 if ( $this->mNewRev
) {
934 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
935 if ( $this->mNewtext
=== false ) {
943 * Load the text of the new revision, not the old one
945 function loadNewText() {
946 if ( $this->mTextLoaded
>= 1 ) {
949 $this->mTextLoaded
= 1;
951 if ( !$this->loadRevisionData() ) {
954 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
961 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
963 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
964 // You may copy this code freely under the conditions of the GPL.
967 define('USE_ASSERTS', function_exists('assert'));
972 * @ingroup DifferenceEngine
980 trigger_error('pure virtual', E_USER_ERROR
);
984 return $this->orig ?
sizeof($this->orig
) : 0;
987 function nclosing() {
988 return $this->closing ?
sizeof($this->closing
) : 0;
995 * @ingroup DifferenceEngine
997 class _DiffOp_Copy
extends _DiffOp
{
1000 function _DiffOp_Copy ($orig, $closing = false) {
1001 if (!is_array($closing))
1003 $this->orig
= $orig;
1004 $this->closing
= $closing;
1007 function reverse() {
1008 return new _DiffOp_Copy($this->closing
, $this->orig
);
1015 * @ingroup DifferenceEngine
1017 class _DiffOp_Delete
extends _DiffOp
{
1018 var $type = 'delete';
1020 function _DiffOp_Delete ($lines) {
1021 $this->orig
= $lines;
1022 $this->closing
= false;
1025 function reverse() {
1026 return new _DiffOp_Add($this->orig
);
1033 * @ingroup DifferenceEngine
1035 class _DiffOp_Add
extends _DiffOp
{
1038 function _DiffOp_Add ($lines) {
1039 $this->closing
= $lines;
1040 $this->orig
= false;
1043 function reverse() {
1044 return new _DiffOp_Delete($this->closing
);
1051 * @ingroup DifferenceEngine
1053 class _DiffOp_Change
extends _DiffOp
{
1054 var $type = 'change';
1056 function _DiffOp_Change ($orig, $closing) {
1057 $this->orig
= $orig;
1058 $this->closing
= $closing;
1061 function reverse() {
1062 return new _DiffOp_Change($this->closing
, $this->orig
);
1067 * Class used internally by Diff to actually compute the diffs.
1069 * The algorithm used here is mostly lifted from the perl module
1070 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1071 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1073 * More ideas are taken from:
1074 * http://www.ics.uci.edu/~eppstein/161/960229.html
1076 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1077 * diffutils-2.7, which can be found at:
1078 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1080 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1083 * Line length limits for robustness added by Tim Starling, 2005-08-31
1084 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1086 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1088 * @ingroup DifferenceEngine
1092 const MAX_XREF_LENGTH
= 10000;
1094 function diff ($from_lines, $to_lines){
1095 wfProfileIn( __METHOD__
);
1097 // Diff and store locally
1098 $this->diff_local($from_lines, $to_lines);
1100 // Merge edits when possible
1101 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1102 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1104 // Compute the edit operations.
1105 $n_from = sizeof($from_lines);
1106 $n_to = sizeof($to_lines);
1110 while ($xi < $n_from ||
$yi < $n_to) {
1111 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1112 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1114 // Skip matching "snake".
1116 while ( $xi < $n_from && $yi < $n_to
1117 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1118 $copy[] = $from_lines[$xi++
];
1122 $edits[] = new _DiffOp_Copy($copy);
1124 // Find deletes & adds.
1126 while ($xi < $n_from && $this->xchanged
[$xi])
1127 $delete[] = $from_lines[$xi++
];
1130 while ($yi < $n_to && $this->ychanged
[$yi])
1131 $add[] = $to_lines[$yi++
];
1133 if ($delete && $add)
1134 $edits[] = new _DiffOp_Change($delete, $add);
1136 $edits[] = new _DiffOp_Delete($delete);
1138 $edits[] = new _DiffOp_Add($add);
1140 wfProfileOut( __METHOD__
);
1144 function diff_local ($from_lines, $to_lines) {
1145 global $wgExternalDiffEngine;
1146 wfProfileIn( __METHOD__
);
1148 if($wgExternalDiffEngine == 'wikidiff3'){
1150 $wikidiff3 = new WikiDiff3();
1151 $wikidiff3->diff($from_lines, $to_lines);
1152 $this->xchanged
= $wikidiff3->removed
;
1153 $this->ychanged
= $wikidiff3->added
;
1157 $n_from = sizeof($from_lines);
1158 $n_to = sizeof($to_lines);
1159 $this->xchanged
= $this->ychanged
= array();
1160 $this->xv
= $this->yv
= array();
1161 $this->xind
= $this->yind
= array();
1163 unset($this->in_seq
);
1166 // Skip leading common lines.
1167 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1168 if ($from_lines[$skip] !== $to_lines[$skip])
1170 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1172 // Skip trailing common lines.
1173 $xi = $n_from; $yi = $n_to;
1174 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1175 if ($from_lines[$xi] !== $to_lines[$yi])
1177 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1180 // Ignore lines which do not exist in both files.
1181 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1182 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1185 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1186 $line = $to_lines[$yi];
1187 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1189 $yhash[$this->_line_hash($line)] = 1;
1190 $this->yv
[] = $line;
1191 $this->yind
[] = $yi;
1193 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1194 $line = $from_lines[$xi];
1195 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1197 $this->xv
[] = $line;
1198 $this->xind
[] = $xi;
1202 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1204 wfProfileOut( __METHOD__
);
1208 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1210 function _line_hash( $line ) {
1211 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1212 return md5( $line );
1218 /* Divide the Largest Common Subsequence (LCS) of the sequences
1219 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1222 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1223 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1224 * sub sequences. The first sub-sequence is contained in [X0, X1),
1225 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1226 * that (X0, Y0) == (XOFF, YOFF) and
1227 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1229 * This function assumes that the first lines of the specified portions
1230 * of the two files do not match, and likewise that the last lines do not
1231 * match. The caller must trim matching lines from the beginning and end
1232 * of the portions it is going to specify.
1234 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1237 if ($xlim - $xoff > $ylim - $yoff) {
1238 // Things seems faster (I'm not sure I understand why)
1239 // when the shortest sequence in X.
1241 list ($xoff, $xlim, $yoff, $ylim)
1242 = array( $yoff, $ylim, $xoff, $xlim);
1246 for ($i = $ylim - 1; $i >= $yoff; $i--)
1247 $ymatches[$this->xv
[$i]][] = $i;
1249 for ($i = $ylim - 1; $i >= $yoff; $i--)
1250 $ymatches[$this->yv
[$i]][] = $i;
1253 $this->seq
[0]= $yoff - 1;
1254 $this->in_seq
= array();
1255 $ymids[0] = array();
1257 $numer = $xlim - $xoff +
$nchunks - 1;
1259 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1261 for ($i = 0; $i <= $this->lcs
; $i++
)
1262 $ymids[$i][$chunk-1] = $this->seq
[$i];
1264 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1265 for ( ; $x < $x1; $x++
) {
1266 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1267 if (empty($ymatches[$line]))
1269 $matches = $ymatches[$line];
1271 while (list ($junk, $y) = each($matches))
1272 if (empty($this->in_seq
[$y])) {
1273 $k = $this->_lcs_pos($y);
1274 USE_ASSERTS
&& assert($k > 0);
1275 $ymids[$k] = $ymids[$k-1];
1278 while (list ( /* $junk */, $y) = each($matches)) {
1279 if ($y > $this->seq
[$k-1]) {
1280 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1281 // Optimization: this is a common case:
1282 // next match is just replacing previous match.
1283 $this->in_seq
[$this->seq
[$k]] = false;
1284 $this->seq
[$k] = $y;
1285 $this->in_seq
[$y] = 1;
1286 } else if (empty($this->in_seq
[$y])) {
1287 $k = $this->_lcs_pos($y);
1288 USE_ASSERTS
&& assert($k > 0);
1289 $ymids[$k] = $ymids[$k-1];
1295 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1296 $ymid = $ymids[$this->lcs
];
1297 for ($n = 0; $n < $nchunks - 1; $n++
) {
1298 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1299 $y1 = $ymid[$n] +
1;
1300 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1302 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1304 return array($this->lcs
, $seps);
1307 function _lcs_pos ($ypos) {
1309 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1310 $this->seq
[++
$this->lcs
] = $ypos;
1311 $this->in_seq
[$ypos] = 1;
1316 while ($beg < $end) {
1317 $mid = (int)(($beg +
$end) / 2);
1318 if ( $ypos > $this->seq
[$mid] )
1324 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1326 $this->in_seq
[$this->seq
[$end]] = false;
1327 $this->seq
[$end] = $ypos;
1328 $this->in_seq
[$ypos] = 1;
1332 /* Find LCS of two sequences.
1334 * The results are recorded in the vectors $this->{x,y}changed[], by
1335 * storing a 1 in the element for each line that is an insertion
1336 * or deletion (ie. is not in the LCS).
1338 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1340 * Note that XLIM, YLIM are exclusive bounds.
1341 * All line numbers are origin-0 and discarded lines are not counted.
1343 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1344 // Slide down the bottom initial diagonal.
1345 while ($xoff < $xlim && $yoff < $ylim
1346 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1351 // Slide up the top initial diagonal.
1352 while ($xlim > $xoff && $ylim > $yoff
1353 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1358 if ($xoff == $xlim ||
$yoff == $ylim)
1361 // This is ad hoc but seems to work well.
1362 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1363 //$nchunks = max(2,min(8,(int)$nchunks));
1364 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1366 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1370 // X and Y sequences have no common subsequence:
1371 // mark all changed.
1372 while ($yoff < $ylim)
1373 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1374 while ($xoff < $xlim)
1375 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1377 // Use the partitions to split this problem into subproblems.
1380 while ($pt2 = next($seps)) {
1381 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1387 /* Adjust inserts/deletes of identical lines to join changes
1388 * as much as possible.
1390 * We do something when a run of changed lines include a
1391 * line at one end and has an excluded, identical line at the other.
1392 * We are free to choose which identical line is included.
1393 * `compareseq' usually chooses the one at the beginning,
1394 * but usually it is cleaner to consider the following identical line
1395 * to be the "change".
1397 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1399 function _shift_boundaries ($lines, &$changed, $other_changed) {
1400 wfProfileIn( __METHOD__
);
1404 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1405 $len = sizeof($lines);
1406 $other_len = sizeof($other_changed);
1410 * Scan forwards to find beginning of another run of changes.
1411 * Also keep track of the corresponding point in the other file.
1413 * Throughout this code, $i and $j are adjusted together so that
1414 * the first $i elements of $changed and the first $j elements
1415 * of $other_changed both contain the same number of zeros
1416 * (unchanged lines).
1417 * Furthermore, $j is always kept so that $j == $other_len or
1418 * $other_changed[$j] == false.
1420 while ($j < $other_len && $other_changed[$j])
1423 while ($i < $len && ! $changed[$i]) {
1424 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1426 while ($j < $other_len && $other_changed[$j])
1435 // Find the end of this run of changes.
1436 while (++
$i < $len && $changed[$i])
1441 * Record the length of this run of changes, so that
1442 * we can later determine whether the run has grown.
1444 $runlength = $i - $start;
1447 * Move the changed region back, so long as the
1448 * previous unchanged line matches the last changed one.
1449 * This merges with previous changed regions.
1451 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1452 $changed[--$start] = 1;
1453 $changed[--$i] = false;
1454 while ($start > 0 && $changed[$start - 1])
1456 USE_ASSERTS
&& assert('$j > 0');
1457 while ($other_changed[--$j])
1459 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1463 * Set CORRESPONDING to the end of the changed run, at the last
1464 * point where it corresponds to a changed run in the other file.
1465 * CORRESPONDING == LEN means no such point has been found.
1467 $corresponding = $j < $other_len ?
$i : $len;
1470 * Move the changed region forward, so long as the
1471 * first changed line matches the following unchanged one.
1472 * This merges with following changed regions.
1473 * Do this second, so that if there are no merges,
1474 * the changed region is moved forward as far as possible.
1476 while ($i < $len && $lines[$start] == $lines[$i]) {
1477 $changed[$start++
] = false;
1479 while ($i < $len && $changed[$i])
1482 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1484 if ($j < $other_len && $other_changed[$j]) {
1485 $corresponding = $i;
1486 while ($j < $other_len && $other_changed[$j])
1490 } while ($runlength != $i - $start);
1493 * If possible, move the fully-merged run of changes
1494 * back to a corresponding run in the other file.
1496 while ($corresponding < $i) {
1497 $changed[--$start] = 1;
1499 USE_ASSERTS
&& assert('$j > 0');
1500 while ($other_changed[--$j])
1502 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1505 wfProfileOut( __METHOD__
);
1510 * Class representing a 'diff' between two sequences of strings.
1513 * @ingroup DifferenceEngine
1521 * Computes diff between sequences of strings.
1523 * @param $from_lines array An array of strings.
1524 * (Typically these are lines from a file.)
1525 * @param $to_lines array An array of strings.
1527 function Diff($from_lines, $to_lines) {
1528 $eng = new _DiffEngine
;
1529 $this->edits
= $eng->diff($from_lines, $to_lines);
1530 //$this->_check($from_lines, $to_lines);
1534 * Compute reversed Diff.
1538 * $diff = new Diff($lines1, $lines2);
1539 * $rev = $diff->reverse();
1540 * @return object A Diff object representing the inverse of the
1543 function reverse () {
1545 $rev->edits
= array();
1546 foreach ($this->edits
as $edit) {
1547 $rev->edits
[] = $edit->reverse();
1553 * Check for empty diff.
1555 * @return bool True iff two sequences were identical.
1557 function isEmpty () {
1558 foreach ($this->edits
as $edit) {
1559 if ($edit->type
!= 'copy')
1566 * Compute the length of the Longest Common Subsequence (LCS).
1568 * This is mostly for diagnostic purposed.
1570 * @return int The length of the LCS.
1574 foreach ($this->edits
as $edit) {
1575 if ($edit->type
== 'copy')
1576 $lcs +
= sizeof($edit->orig
);
1582 * Get the original set of lines.
1584 * This reconstructs the $from_lines parameter passed to the
1587 * @return array The original sequence of strings.
1592 foreach ($this->edits
as $edit) {
1594 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1600 * Get the closing set of lines.
1602 * This reconstructs the $to_lines parameter passed to the
1605 * @return array The sequence of strings.
1607 function closing() {
1610 foreach ($this->edits
as $edit) {
1612 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1618 * Check a Diff for validity.
1620 * This is here only for debugging purposes.
1622 function _check ($from_lines, $to_lines) {
1623 wfProfileIn( __METHOD__
);
1624 if (serialize($from_lines) != serialize($this->orig()))
1625 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1626 if (serialize($to_lines) != serialize($this->closing()))
1627 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1629 $rev = $this->reverse();
1630 if (serialize($to_lines) != serialize($rev->orig()))
1631 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1632 if (serialize($from_lines) != serialize($rev->closing()))
1633 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1637 foreach ($this->edits
as $edit) {
1638 if ( $prevtype == $edit->type
)
1639 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1640 $prevtype = $edit->type
;
1643 $lcs = $this->lcs();
1644 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1645 wfProfileOut( __METHOD__
);
1650 * @todo document, bad name.
1652 * @ingroup DifferenceEngine
1654 class MappedDiff
extends Diff
1659 * Computes diff between sequences of strings.
1661 * This can be used to compute things like
1662 * case-insensitve diffs, or diffs which ignore
1663 * changes in white-space.
1665 * @param $from_lines array An array of strings.
1666 * (Typically these are lines from a file.)
1668 * @param $to_lines array An array of strings.
1670 * @param $mapped_from_lines array This array should
1671 * have the same size number of elements as $from_lines.
1672 * The elements in $mapped_from_lines and
1673 * $mapped_to_lines are what is actually compared
1674 * when computing the diff.
1676 * @param $mapped_to_lines array This array should
1677 * have the same number of elements as $to_lines.
1679 function MappedDiff($from_lines, $to_lines,
1680 $mapped_from_lines, $mapped_to_lines) {
1681 wfProfileIn( __METHOD__
);
1683 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1684 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1686 $this->Diff($mapped_from_lines, $mapped_to_lines);
1689 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1690 $orig = &$this->edits
[$i]->orig
;
1691 if (is_array($orig)) {
1692 $orig = array_slice($from_lines, $xi, sizeof($orig));
1693 $xi +
= sizeof($orig);
1696 $closing = &$this->edits
[$i]->closing
;
1697 if (is_array($closing)) {
1698 $closing = array_slice($to_lines, $yi, sizeof($closing));
1699 $yi +
= sizeof($closing);
1702 wfProfileOut( __METHOD__
);
1707 * A class to format Diffs
1709 * This class formats the diff in classic diff format.
1710 * It is intended that this class be customized via inheritance,
1711 * to obtain fancier outputs.
1714 * @ingroup DifferenceEngine
1716 class DiffFormatter
{
1718 * Number of leading context "lines" to preserve.
1720 * This should be left at zero for this class, but subclasses
1721 * may want to set this to other values.
1723 var $leading_context_lines = 0;
1726 * Number of trailing context "lines" to preserve.
1728 * This should be left at zero for this class, but subclasses
1729 * may want to set this to other values.
1731 var $trailing_context_lines = 0;
1736 * @param $diff object A Diff object.
1737 * @return string The formatted output.
1739 function format($diff) {
1740 wfProfileIn( __METHOD__
);
1746 $nlead = $this->leading_context_lines
;
1747 $ntrail = $this->trailing_context_lines
;
1749 $this->_start_diff();
1751 foreach ($diff->edits
as $edit) {
1752 if ($edit->type
== 'copy') {
1753 if (is_array($block)) {
1754 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1759 $context = array_slice($edit->orig
, 0, $ntrail);
1760 $block[] = new _DiffOp_Copy($context);
1762 $this->_block($x0, $ntrail +
$xi - $x0,
1763 $y0, $ntrail +
$yi - $y0,
1768 $context = $edit->orig
;
1771 if (! is_array($block)) {
1772 $context = array_slice($context, sizeof($context) - $nlead);
1773 $x0 = $xi - sizeof($context);
1774 $y0 = $yi - sizeof($context);
1777 $block[] = new _DiffOp_Copy($context);
1783 $xi +
= sizeof($edit->orig
);
1785 $yi +
= sizeof($edit->closing
);
1788 if (is_array($block))
1789 $this->_block($x0, $xi - $x0,
1793 $end = $this->_end_diff();
1794 wfProfileOut( __METHOD__
);
1798 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1799 wfProfileIn( __METHOD__
);
1800 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1801 foreach ($edits as $edit) {
1802 if ($edit->type
== 'copy')
1803 $this->_context($edit->orig
);
1804 elseif ($edit->type
== 'add')
1805 $this->_added($edit->closing
);
1806 elseif ($edit->type
== 'delete')
1807 $this->_deleted($edit->orig
);
1808 elseif ($edit->type
== 'change')
1809 $this->_changed($edit->orig
, $edit->closing
);
1811 trigger_error('Unknown edit type', E_USER_ERROR
);
1813 $this->_end_block();
1814 wfProfileOut( __METHOD__
);
1817 function _start_diff() {
1821 function _end_diff() {
1822 $val = ob_get_contents();
1827 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1829 $xbeg .= "," . ($xbeg +
$xlen - 1);
1831 $ybeg .= "," . ($ybeg +
$ylen - 1);
1833 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1836 function _start_block($header) {
1837 echo $header . "\n";
1840 function _end_block() {
1843 function _lines($lines, $prefix = ' ') {
1844 foreach ($lines as $line)
1845 echo "$prefix $line\n";
1848 function _context($lines) {
1849 $this->_lines($lines);
1852 function _added($lines) {
1853 $this->_lines($lines, '>');
1855 function _deleted($lines) {
1856 $this->_lines($lines, '<');
1859 function _changed($orig, $closing) {
1860 $this->_deleted($orig);
1862 $this->_added($closing);
1867 * A formatter that outputs unified diffs
1868 * @ingroup DifferenceEngine
1871 class UnifiedDiffFormatter
extends DiffFormatter
{
1872 var $leading_context_lines = 2;
1873 var $trailing_context_lines = 2;
1875 function _added($lines) {
1876 $this->_lines($lines, '+');
1878 function _deleted($lines) {
1879 $this->_lines($lines, '-');
1881 function _changed($orig, $closing) {
1882 $this->_deleted($orig);
1883 $this->_added($closing);
1885 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1886 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1891 * A pseudo-formatter that just passes along the Diff::$edits array
1892 * @ingroup DifferenceEngine
1894 class ArrayDiffFormatter
extends DiffFormatter
{
1895 function format($diff) {
1899 foreach($diff->edits
as $edit)
1900 switch($edit->type
) {
1902 foreach($edit->closing
as $l) {
1906 'newline' => $newline++
1911 foreach($edit->orig
as $l) {
1913 'action' => 'delete',
1915 'oldline' => $oldline++
,
1920 foreach($edit->orig
as $i => $l) {
1922 'action' => 'change',
1924 'new' => @$edit->closing
[$i],
1925 'oldline' => $oldline++
,
1926 'newline' => $newline++
,
1931 $oldline +
= count($edit->orig
);
1932 $newline +
= count($edit->orig
);
1939 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1943 define('NBSP', ' '); // iso-8859-x non-breaking space.
1948 * @ingroup DifferenceEngine
1950 class _HWLDF_WordAccumulator
{
1951 function _HWLDF_WordAccumulator () {
1952 $this->_lines
= array();
1958 function _flushGroup ($new_tag) {
1959 if ($this->_group
!== '') {
1960 if ($this->_tag
== 'ins')
1961 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1962 htmlspecialchars ( $this->_group
) . '</ins>';
1963 elseif ($this->_tag
== 'del')
1964 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1965 htmlspecialchars ( $this->_group
) . '</del>';
1967 $this->_line
.= htmlspecialchars ( $this->_group
);
1970 $this->_tag
= $new_tag;
1973 function _flushLine ($new_tag) {
1974 $this->_flushGroup($new_tag);
1975 if ($this->_line
!= '')
1976 array_push ( $this->_lines
, $this->_line
);
1978 # make empty lines visible by inserting an NBSP
1979 array_push ( $this->_lines
, NBSP
);
1983 function addWords ($words, $tag = '') {
1984 if ($tag != $this->_tag
)
1985 $this->_flushGroup($tag);
1987 foreach ($words as $word) {
1988 // new-line should only come as first char of word.
1991 if ($word[0] == "\n") {
1992 $this->_flushLine($tag);
1993 $word = substr($word, 1);
1995 assert(!strstr($word, "\n"));
1996 $this->_group
.= $word;
2000 function getLines() {
2001 $this->_flushLine('~done');
2002 return $this->_lines
;
2009 * @ingroup DifferenceEngine
2011 class WordLevelDiff
extends MappedDiff
{
2012 const MAX_LINE_LENGTH
= 10000;
2014 function WordLevelDiff ($orig_lines, $closing_lines) {
2015 wfProfileIn( __METHOD__
);
2017 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
2018 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
2020 $this->MappedDiff($orig_words, $closing_words,
2021 $orig_stripped, $closing_stripped);
2022 wfProfileOut( __METHOD__
);
2025 function _split($lines) {
2026 wfProfileIn( __METHOD__
);
2029 $stripped = array();
2031 foreach ( $lines as $line ) {
2032 # If the line is too long, just pretend the entire line is one big word
2033 # This prevents resource exhaustion problems
2040 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2042 $stripped[] = $line;
2045 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2048 $words = array_merge( $words, $m[0] );
2049 $stripped = array_merge( $stripped, $m[1] );
2053 wfProfileOut( __METHOD__
);
2054 return array($words, $stripped);
2058 wfProfileIn( __METHOD__
);
2059 $orig = new _HWLDF_WordAccumulator
;
2061 foreach ($this->edits
as $edit) {
2062 if ($edit->type
== 'copy')
2063 $orig->addWords($edit->orig
);
2064 elseif ($edit->orig
)
2065 $orig->addWords($edit->orig
, 'del');
2067 $lines = $orig->getLines();
2068 wfProfileOut( __METHOD__
);
2072 function closing () {
2073 wfProfileIn( __METHOD__
);
2074 $closing = new _HWLDF_WordAccumulator
;
2076 foreach ($this->edits
as $edit) {
2077 if ($edit->type
== 'copy')
2078 $closing->addWords($edit->closing
);
2079 elseif ($edit->closing
)
2080 $closing->addWords($edit->closing
, 'ins');
2082 $lines = $closing->getLines();
2083 wfProfileOut( __METHOD__
);
2089 * Wikipedia Table style diff formatter.
2092 * @ingroup DifferenceEngine
2094 class TableDiffFormatter
extends DiffFormatter
{
2095 function TableDiffFormatter() {
2096 $this->leading_context_lines
= 2;
2097 $this->trailing_context_lines
= 2;
2100 public static function escapeWhiteSpace( $msg ) {
2101 $msg = preg_replace( '/^ /m', ' ', $msg );
2102 $msg = preg_replace( '/ $/m', ' ', $msg );
2103 $msg = preg_replace( '/ /', ' ', $msg );
2107 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2108 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2109 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2113 function _start_block( $header ) {
2117 function _end_block() {
2120 function _lines( $lines, $prefix=' ', $color='white' ) {
2123 # HTML-escape parameter before calling this
2124 function addedLine( $line ) {
2125 return $this->wrapLine( '+', 'diff-addedline', $line );
2128 # HTML-escape parameter before calling this
2129 function deletedLine( $line ) {
2130 return $this->wrapLine( '-', 'diff-deletedline', $line );
2133 # HTML-escape parameter before calling this
2134 function contextLine( $line ) {
2135 return $this->wrapLine( ' ', 'diff-context', $line );
2138 private function wrapLine( $marker, $class, $line ) {
2139 if( $line !== '' ) {
2140 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2141 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2143 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2146 function emptyLine() {
2147 return '<td colspan="2"> </td>';
2150 function _added( $lines ) {
2151 foreach ($lines as $line) {
2152 echo '<tr>' . $this->emptyLine() .
2153 $this->addedLine( '<ins class="diffchange">' .
2154 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2158 function _deleted($lines) {
2159 foreach ($lines as $line) {
2160 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2161 htmlspecialchars ( $line ) . '</del>' ) .
2162 $this->emptyLine() . "</tr>\n";
2166 function _context( $lines ) {
2167 foreach ($lines as $line) {
2169 $this->contextLine( htmlspecialchars ( $line ) ) .
2170 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2174 function _changed( $orig, $closing ) {
2175 wfProfileIn( __METHOD__
);
2177 $diff = new WordLevelDiff( $orig, $closing );
2178 $del = $diff->orig();
2179 $add = $diff->closing();
2181 # Notice that WordLevelDiff returns HTML-escaped output.
2182 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2184 while ( $line = array_shift( $del ) ) {
2185 $aline = array_shift( $add );
2186 echo '<tr>' . $this->deletedLine( $line ) .
2187 $this->addedLine( $aline ) . "</tr>\n";
2189 foreach ($add as $line) { # If any leftovers
2190 echo '<tr>' . $this->emptyLine() .
2191 $this->addedLine( $line ) . "</tr>\n";
2193 wfProfileOut( __METHOD__
);