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, $refreshCache = false , $htmldiff = false, $unhide = false ) {
47 $this->mTitle
= $titleObj;
48 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
50 if ( 'prev' === $new ) {
51 # Show diff between revision $old and the previous one.
52 # Get previous one from DB.
53 $this->mNewid
= intval($old);
54 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
55 } elseif ( 'next' === $new ) {
56 # Show diff between revision $old and the next one.
57 # Get next one from DB.
58 $this->mOldid
= intval($old);
59 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
60 if ( false === $this->mNewid
) {
61 # if no result, NewId points to the newest old revision. The only newer
62 # revision is cur, which is "0".
66 $this->mOldid
= intval($old);
67 $this->mNewid
= intval($new);
68 wfRunHooks( 'NewDifferenceEngine', array(&$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new) );
70 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
71 $this->mRefreshCache
= $refreshCache;
72 $this->htmldiff
= $htmldiff;
73 $this->unhide
= $unhide;
80 function wasCacheHit() {
81 return $this->mCacheHit
;
92 function showDiffPage( $diffOnly = false ) {
93 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
94 wfProfileIn( __METHOD__
);
97 # If external diffs are enabled both globally and for the user,
98 # we'll use the application/x-external-editor interface to call
99 # an external diff tool like kompare, kdiff3, etc.
100 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
101 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
103 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
104 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
105 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
106 $special=$wgLang->getNsText(NS_SPECIAL
);
111 Script={$wgServer}{$wgScript}
112 Special namespace={$special}
126 $wgOut->setArticleFlag( false );
127 if ( !$this->loadRevisionData() ) {
128 $t = $this->mTitle
->getPrefixedText();
129 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
130 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
131 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
132 wfProfileOut( __METHOD__
);
136 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
138 if ( $this->mNewRev
->isCurrent() ) {
139 $wgOut->setArticleFlag( true );
142 # mOldid is false if the difference engine is called with a "vague" query for
143 # a diff between a version V and its previous version V' AND the version V
144 # is the first version of that article. In that case, V' does not exist.
145 if ( $this->mOldid
=== false ) {
146 $this->showFirstRevision();
147 $this->renderNewRevision(); // should we respect $diffOnly here or not?
148 wfProfileOut( __METHOD__
);
152 $wgOut->suppressQuickbar();
154 $oldTitle = $this->mOldPage
->getPrefixedText();
155 $newTitle = $this->mNewPage
->getPrefixedText();
156 if( $oldTitle == $newTitle ) {
157 $wgOut->setPageTitle( $newTitle );
159 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
161 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
162 $wgOut->setRobotPolicy( 'noindex,nofollow' );
164 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
165 $wgOut->loginToUse();
168 wfProfileOut( __METHOD__
);
172 $sk = $wgUser->getSkin();
174 // Check if page is editable
175 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
176 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
177 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
182 // Prepare a change patrol link, if applicable
183 if( $wgUseRCPatrol && $this->mTitle
->userCan('patrol') ) {
184 // If we've been given an explicit change identifier, use it; saves time
185 if( $this->mRcidMarkPatrolled
) {
186 $rcid = $this->mRcidMarkPatrolled
;
187 $rc = RecentChange
::newFromId( $rcid );
188 // Already patrolled?
189 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ?
$rcid : 0;
191 // Look for an unpatrolled change corresponding to this diff
192 $db = wfGetDB( DB_SLAVE
);
193 $change = RecentChange
::newFromConds(
195 // Add redundant user,timestamp condition so we can use the existing index
196 'rc_user_text' => $this->mNewRev
->getRawUserText(),
197 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
198 'rc_this_oldid' => $this->mNewid
,
199 'rc_last_oldid' => $this->mOldid
,
204 if( $change instanceof RecentChange
) {
205 $rcid = $change->mAttribs
['rc_id'];
206 $this->mRcidMarkPatrolled
= $rcid;
214 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj( $this->mTitle
,
215 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$rcid}" ) . ']</span>';
224 # Carry over 'diffonly' param via navigation links
225 if( $diffOnly != $wgUser->getBoolOption('diffonly') ) {
226 $diffOnlyArg = '&diffonly='.$diffOnly;
228 $htmldiffarg = $this->htmlDiffArgument();
229 # Make "previous revision link"
230 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
231 "diff=prev&oldid={$this->mOldid}{$htmldiffarg}{$diffOnlyArg}", '', '', 'id="differences-prevlink"' );
232 # Make "next revision link"
233 if( $this->mNewRev
->isCurrent() ) {
234 $nextlink = ' ';
236 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
237 "diff=next&oldid={$this->mNewid}{$htmldiffarg}{$diffOnlyArg}", '', '', 'id="differences-nextlink"' );
243 if( $this->mOldRev
->isMinor() ) {
244 $oldminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
246 if( $this->mNewRev
->isMinor() ) {
247 $newminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
250 $rdel = ''; $ldel = '';
251 if( $wgUser->isAllowed( 'deleterevision' ) ) {
252 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
253 // If revision was hidden from sysops
254 $ldel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
256 $query = array( 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
257 'oldid' => $this->mOldRev
->getId()
259 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
261 $ldel = " $ldel ";
262 // We don't currently handle well changing the top revision's settings
263 if( $this->mNewRev
->isCurrent() ) {
264 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
265 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
266 // If revision was hidden from sysops
267 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
269 $query = array( 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
270 'oldid' => $this->mNewRev
->getId()
272 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
274 $rdel = " $rdel ";
277 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
278 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
279 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
280 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
281 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
282 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
283 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
284 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
286 # Check if this user can see the revisions
287 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
)
288 && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
289 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
)
290 ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
291 # Output the diff if allowed...
292 if( $deleted && (!$this->unhide ||
!$allowed) ) {
293 $this->showDiffStyle();
294 $multi = $this->getMultiNotice();
295 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
297 # Give explanation for why revision is not visible
298 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
299 array( 'rev-deleted-no-diff' ) );
301 # Give explanation and add a link to view the diff...
302 $link = $this->mTitle
->getFullUrl( "diff={$this->mNewid}&oldid={$this->mOldid}".
303 '&unhide=1&token='.urlencode( $wgUser->editToken($this->mNewid
) ) );
304 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
305 array( 'rev-deleted-unhide-diff', $link ) );
307 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
308 $multi = $this->getMultiNotice();
309 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
310 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
311 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
312 $this->renderHtmlDiff();
314 if( $wgEnableHtmlDiff ) {
315 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
316 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
318 $this->showDiff( $oldHeader, $newHeader );
320 $this->renderNewRevision();
323 wfProfileOut( __METHOD__
);
327 * Show the new revision of the page.
329 function renderNewRevision() {
330 global $wgOut, $wgUser;
331 wfProfileIn( __METHOD__
);
333 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
334 # Add deleted rev tag if needed
335 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
336 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
337 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
338 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
341 if( !$this->mNewRev
->isCurrent() ) {
342 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
345 $this->loadNewText();
346 if( is_object( $this->mNewRev
) ) {
347 $wgOut->setRevisionId( $this->mNewRev
->getId() );
350 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
351 // Stolen from Article::view --AG 2007-10-11
352 // Give hooks a chance to customise the output
353 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
354 // Wrap the whole lot in a <pre> and don't parse
356 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
357 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
358 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
359 $wgOut->addHTML( "\n</pre>\n" );
362 $wgOut->addWikiTextTidy( $this->mNewtext
);
365 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
366 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
368 # Add redundant patrol link on bottom...
369 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
370 $sk = $wgUser->getSkin();
372 "<div class='patrollink'>[" . $sk->makeKnownLinkObj( $this->mTitle
,
373 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) .
378 wfProfileOut( __METHOD__
);
382 function renderHtmlDiff() {
383 global $wgOut, $wgTitle, $wgParser, $wgDebugComments;
384 wfProfileIn( __METHOD__
);
386 $this->showDiffStyle();
388 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
389 #add deleted rev tag if needed
390 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
391 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
392 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
393 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
396 if( !$this->mNewRev
->isCurrent() ) {
397 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
403 if( is_object( $this->mOldRev
) ) {
404 $wgOut->setRevisionId( $this->mOldRev
->getId() );
407 $popts = $wgOut->parserOptions();
408 $oldTidy = $popts->setTidy( true );
409 $popts->setEditSection( false );
411 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
412 $popts->setTidy( $oldTidy );
415 //$wgOut->addParserOutputNoText( $parserOutput );
416 $oldHtml = $parserOutput->getText();
417 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
420 if( is_object( $this->mNewRev
) ) {
421 $wgOut->setRevisionId( $this->mNewRev
->getId() );
424 $popts = $wgOut->parserOptions();
425 $oldTidy = $popts->setTidy( true );
427 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
428 $popts->setTidy( $oldTidy );
430 $wgOut->addParserOutputNoText( $parserOutput );
431 $newHtml = $parserOutput->getText();
432 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
434 unset($parserOutput, $popts);
436 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
437 $differ->htmlDiff($oldHtml, $newHtml);
438 if ( $wgDebugComments ) {
439 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
442 wfProfileOut( __METHOD__
);
446 * Show the first revision of an article. Uses normal diff headers in
447 * contrast to normal "old revision" display style.
449 function showFirstRevision() {
450 global $wgOut, $wgUser;
451 wfProfileIn( __METHOD__
);
453 # Get article text from the DB
455 if ( ! $this->loadNewText() ) {
456 $t = $this->mTitle
->getPrefixedText();
457 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
458 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
459 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
460 wfProfileOut( __METHOD__
);
463 if ( $this->mNewRev
->isCurrent() ) {
464 $wgOut->setArticleFlag( true );
467 # Check if user is allowed to look at this page. If not, bail out.
469 if ( !$this->mTitle
->userCanRead() ) {
470 $wgOut->loginToUse();
472 wfProfileOut( __METHOD__
);
473 throw new MWException("Permission Error: you do not have access to view this page");
476 # Prepare the header box
478 $sk = $wgUser->getSkin();
480 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
484 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
485 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
487 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
488 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
490 $wgOut->addHTML( $header );
492 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
493 $wgOut->setRobotPolicy( 'noindex,nofollow' );
495 wfProfileOut( __METHOD__
);
498 function htmlDiffArgument(){
499 global $wgEnableHtmlDiff;
500 if($wgEnableHtmlDiff){
502 return '&htmldiff=1';
504 return '&htmldiff=0';
512 * Get the diff text, send it to $wgOut
513 * Returns false if the diff could not be generated, otherwise returns true
515 function showDiff( $otitle, $ntitle ) {
517 $diff = $this->getDiff( $otitle, $ntitle );
518 if ( $diff === false ) {
519 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
522 $this->showDiffStyle();
523 $wgOut->addHTML( $diff );
529 * Add style sheets and supporting JS for diff display.
531 function showDiffStyle() {
532 global $wgStylePath, $wgStyleVersion, $wgOut;
533 $wgOut->addStyle( 'common/diff.css' );
535 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
536 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
540 * Get complete diff table, including header
542 * @param Title $otitle Old title
543 * @param Title $ntitle New title
546 function getDiff( $otitle, $ntitle ) {
547 $body = $this->getDiffBody();
548 if ( $body === false ) {
551 $multi = $this->getMultiNotice();
552 return $this->addHeader( $body, $otitle, $ntitle, $multi );
557 * Get the diff table body, without header
561 function getDiffBody() {
563 wfProfileIn( __METHOD__
);
564 $this->mCacheHit
= true;
565 // Check if the diff should be hidden from this user
566 if ( !$this->loadRevisionData() )
568 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
570 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
572 } else if ( $this->mOldRev
&& $this->mNewRev
&& $this->mOldRev
->getID() == $this->mNewRev
->getID() ) {
577 if ( $this->mOldid
&& $this->mNewid
) {
578 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
580 if ( !$this->mRefreshCache
) {
581 $difftext = $wgMemc->get( $key );
583 wfIncrStats( 'diff_cache_hit' );
584 $difftext = $this->localiseLineNumbers( $difftext );
585 $difftext .= "\n<!-- diff cache key $key -->\n";
586 wfProfileOut( __METHOD__
);
589 } // don't try to load but save the result
591 $this->mCacheHit
= false;
593 // Loadtext is permission safe, this just clears out the diff
594 if ( !$this->loadText() ) {
595 wfProfileOut( __METHOD__
);
599 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
601 // Save to cache for 7 days
602 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
603 wfIncrStats( 'diff_uncacheable' );
604 } else if ( $key !== false && $difftext !== false ) {
605 wfIncrStats( 'diff_cache_miss' );
606 $wgMemc->set( $key, $difftext, 7*86400 );
608 wfIncrStats( 'diff_uncacheable' );
610 // Replace line numbers with the text in the user's language
611 if ( $difftext !== false ) {
612 $difftext = $this->localiseLineNumbers( $difftext );
614 wfProfileOut( __METHOD__
);
619 * Generate a diff, no caching
620 * $otext and $ntext must be already segmented
622 function generateDiffBody( $otext, $ntext ) {
623 global $wgExternalDiffEngine, $wgContLang;
625 $otext = str_replace( "\r\n", "\n", $otext );
626 $ntext = str_replace( "\r\n", "\n", $ntext );
628 if ( $wgExternalDiffEngine == 'wikidiff' ) {
629 # For historical reasons, external diff engine expects
630 # input text to be HTML-escaped already
631 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
632 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
633 if( !function_exists( 'wikidiff_do_diff' ) ) {
634 dl('php_wikidiff.so');
636 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
637 $this->debug( 'wikidiff1' );
640 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
641 # Better external diff engine, the 2 may some day be dropped
642 # This one does the escaping and segmenting itself
643 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
644 wfProfileIn( __METHOD__
. "-dl" );
645 @dl
('php_wikidiff2.so');
646 wfProfileOut( __METHOD__
. "-dl" );
648 if ( function_exists( 'wikidiff2_do_diff' ) ) {
649 wfProfileIn( 'wikidiff2_do_diff' );
650 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
651 $text .= $this->debug( 'wikidiff2' );
652 wfProfileOut( 'wikidiff2_do_diff' );
656 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
658 global $wgTmpDirectory;
659 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
660 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
662 $tempFile1 = fopen( $tempName1, "w" );
664 wfProfileOut( __METHOD__
);
667 $tempFile2 = fopen( $tempName2, "w" );
669 wfProfileOut( __METHOD__
);
672 fwrite( $tempFile1, $otext );
673 fwrite( $tempFile2, $ntext );
674 fclose( $tempFile1 );
675 fclose( $tempFile2 );
676 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
677 wfProfileIn( __METHOD__
. "-shellexec" );
678 $difftext = wfShellExec( $cmd );
679 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
680 wfProfileOut( __METHOD__
. "-shellexec" );
681 unlink( $tempName1 );
682 unlink( $tempName2 );
687 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
688 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
689 $diffs = new Diff( $ota, $nta );
690 $formatter = new TableDiffFormatter();
691 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
696 * Generate a debug comment indicating diff generating time,
697 * server node, and generator backend.
699 protected function debug( $generator="internal" ) {
700 global $wgShowHostnames;
701 $data = array( $generator );
702 if( $wgShowHostnames ) {
703 $data[] = wfHostname();
705 $data[] = wfTimestamp( TS_DB
);
706 return "<!-- diff generator: " .
715 * Replace line numbers with the text in the user's language
717 function localiseLineNumbers( $text ) {
718 return preg_replace_callback( '/<!--LINE (\d+)-->/',
719 array( &$this, 'localiseLineNumbersCb' ), $text );
722 function localiseLineNumbersCb( $matches ) {
724 return wfMsgExt( 'lineno', array (), $wgLang->formatNum( $matches[1] ) );
729 * If there are revisions between the ones being compared, return a note saying so.
731 function getMultiNotice() {
732 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
735 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
736 // Comparing two different pages? Count would be meaningless.
740 $oldid = $this->mOldRev
->getId();
741 $newid = $this->mNewRev
->getId();
742 if ( $oldid > $newid ) {
743 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
746 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
750 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
755 * Add the header to a diff body
757 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
760 <col class='diff-marker' />
761 <col class='diff-content' />
762 <col class='diff-marker' />
763 <col class='diff-content' />
765 <td colspan='2' class='diff-otitle'>{$otitle}</td>
766 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
771 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
773 return $header . $diff . "</table>";
777 * Use specified text instead of loading from the database
779 function setText( $oldText, $newText ) {
780 $this->mOldtext
= $oldText;
781 $this->mNewtext
= $newText;
782 $this->mTextLoaded
= 2;
783 $this->mRevisionsLoaded
= true;
787 * Load revision metadata for the specified articles. If newid is 0, then compare
788 * the old article in oldid to the current article; if oldid is 0, then
789 * compare the current article to the immediately previous one (ignoring the
792 * If oldid is false, leave the corresponding revision object set
793 * to false. This is impossible via ordinary user input, and is provided for
796 function loadRevisionData() {
797 global $wgLang, $wgUser;
798 if ( $this->mRevisionsLoaded
) {
801 // Whether it succeeds or fails, we don't want to try again
802 $this->mRevisionsLoaded
= true;
805 // Load the new revision object
806 $this->mNewRev
= $this->mNewid
807 ? Revision
::newFromId( $this->mNewid
)
808 : Revision
::newFromTitle( $this->mTitle
);
809 if( !$this->mNewRev
instanceof Revision
)
812 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
813 $this->mNewid
= $this->mNewRev
->getId();
815 // Check if page is editable
816 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
818 // Set assorted variables
819 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
820 $this->mNewPage
= $this->mNewRev
->getTitle();
821 if( $this->mNewRev
->isCurrent() ) {
822 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
823 $this->mPagetitle
= wfMsgHTML( 'currentrev-asof', $timestamp );
824 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
826 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
827 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
830 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
831 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
832 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
834 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
835 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
837 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
838 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
839 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
840 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
843 // Load the old revision object
844 $this->mOldRev
= false;
845 if( $this->mOldid
) {
846 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
847 } elseif ( $this->mOldid
=== 0 ) {
848 $rev = $this->mNewRev
->getPrevious();
850 $this->mOldid
= $rev->getId();
851 $this->mOldRev
= $rev;
853 // No previous revision; mark to show as first-version only.
854 $this->mOldid
= false;
855 $this->mOldRev
= false;
857 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
859 if( is_null( $this->mOldRev
) ) {
863 if ( $this->mOldRev
) {
864 $this->mOldPage
= $this->mOldRev
->getTitle();
866 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
867 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
868 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
869 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
871 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
872 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
873 // Add an "undo" link
874 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
875 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
876 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
877 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
878 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
881 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
882 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
883 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
884 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
892 * Load the text of the revisions, as well as revision data.
894 function loadText() {
895 if ( $this->mTextLoaded
== 2 ) {
898 // Whether it succeeds or fails, we don't want to try again
899 $this->mTextLoaded
= 2;
902 if ( !$this->loadRevisionData() ) {
905 if ( $this->mOldRev
) {
906 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
907 if ( $this->mOldtext
=== false ) {
911 if ( $this->mNewRev
) {
912 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
913 if ( $this->mNewtext
=== false ) {
921 * Load the text of the new revision, not the old one
923 function loadNewText() {
924 if ( $this->mTextLoaded
>= 1 ) {
927 $this->mTextLoaded
= 1;
929 if ( !$this->loadRevisionData() ) {
932 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
939 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
941 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
942 // You may copy this code freely under the conditions of the GPL.
945 define('USE_ASSERTS', function_exists('assert'));
950 * @ingroup DifferenceEngine
958 trigger_error('pure virtual', E_USER_ERROR
);
962 return $this->orig ?
sizeof($this->orig
) : 0;
965 function nclosing() {
966 return $this->closing ?
sizeof($this->closing
) : 0;
973 * @ingroup DifferenceEngine
975 class _DiffOp_Copy
extends _DiffOp
{
978 function _DiffOp_Copy ($orig, $closing = false) {
979 if (!is_array($closing))
982 $this->closing
= $closing;
986 return new _DiffOp_Copy($this->closing
, $this->orig
);
993 * @ingroup DifferenceEngine
995 class _DiffOp_Delete
extends _DiffOp
{
996 var $type = 'delete';
998 function _DiffOp_Delete ($lines) {
999 $this->orig
= $lines;
1000 $this->closing
= false;
1003 function reverse() {
1004 return new _DiffOp_Add($this->orig
);
1011 * @ingroup DifferenceEngine
1013 class _DiffOp_Add
extends _DiffOp
{
1016 function _DiffOp_Add ($lines) {
1017 $this->closing
= $lines;
1018 $this->orig
= false;
1021 function reverse() {
1022 return new _DiffOp_Delete($this->closing
);
1029 * @ingroup DifferenceEngine
1031 class _DiffOp_Change
extends _DiffOp
{
1032 var $type = 'change';
1034 function _DiffOp_Change ($orig, $closing) {
1035 $this->orig
= $orig;
1036 $this->closing
= $closing;
1039 function reverse() {
1040 return new _DiffOp_Change($this->closing
, $this->orig
);
1045 * Class used internally by Diff to actually compute the diffs.
1047 * The algorithm used here is mostly lifted from the perl module
1048 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1049 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1051 * More ideas are taken from:
1052 * http://www.ics.uci.edu/~eppstein/161/960229.html
1054 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1055 * diffutils-2.7, which can be found at:
1056 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1058 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1061 * Line length limits for robustness added by Tim Starling, 2005-08-31
1062 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1064 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1066 * @ingroup DifferenceEngine
1070 const MAX_XREF_LENGTH
= 10000;
1072 function diff ($from_lines, $to_lines){
1073 wfProfileIn( __METHOD__
);
1075 // Diff and store locally
1076 $this->diff_local($from_lines, $to_lines);
1078 // Merge edits when possible
1079 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1080 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1082 // Compute the edit operations.
1083 $n_from = sizeof($from_lines);
1084 $n_to = sizeof($to_lines);
1088 while ($xi < $n_from ||
$yi < $n_to) {
1089 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1090 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1092 // Skip matching "snake".
1094 while ( $xi < $n_from && $yi < $n_to
1095 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1096 $copy[] = $from_lines[$xi++
];
1100 $edits[] = new _DiffOp_Copy($copy);
1102 // Find deletes & adds.
1104 while ($xi < $n_from && $this->xchanged
[$xi])
1105 $delete[] = $from_lines[$xi++
];
1108 while ($yi < $n_to && $this->ychanged
[$yi])
1109 $add[] = $to_lines[$yi++
];
1111 if ($delete && $add)
1112 $edits[] = new _DiffOp_Change($delete, $add);
1114 $edits[] = new _DiffOp_Delete($delete);
1116 $edits[] = new _DiffOp_Add($add);
1118 wfProfileOut( __METHOD__
);
1122 function diff_local ($from_lines, $to_lines) {
1123 global $wgExternalDiffEngine;
1124 wfProfileIn( __METHOD__
);
1126 if($wgExternalDiffEngine == 'wikidiff3'){
1128 $wikidiff3 = new WikiDiff3();
1129 $wikidiff3->diff($from_lines, $to_lines);
1130 $this->xchanged
= $wikidiff3->removed
;
1131 $this->ychanged
= $wikidiff3->added
;
1135 $n_from = sizeof($from_lines);
1136 $n_to = sizeof($to_lines);
1137 $this->xchanged
= $this->ychanged
= array();
1138 $this->xv
= $this->yv
= array();
1139 $this->xind
= $this->yind
= array();
1141 unset($this->in_seq
);
1144 // Skip leading common lines.
1145 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1146 if ($from_lines[$skip] !== $to_lines[$skip])
1148 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1150 // Skip trailing common lines.
1151 $xi = $n_from; $yi = $n_to;
1152 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1153 if ($from_lines[$xi] !== $to_lines[$yi])
1155 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1158 // Ignore lines which do not exist in both files.
1159 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1160 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1163 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1164 $line = $to_lines[$yi];
1165 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1167 $yhash[$this->_line_hash($line)] = 1;
1168 $this->yv
[] = $line;
1169 $this->yind
[] = $yi;
1171 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1172 $line = $from_lines[$xi];
1173 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1175 $this->xv
[] = $line;
1176 $this->xind
[] = $xi;
1180 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1182 wfProfileOut( __METHOD__
);
1186 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1188 function _line_hash( $line ) {
1189 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1190 return md5( $line );
1196 /* Divide the Largest Common Subsequence (LCS) of the sequences
1197 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1200 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1201 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1202 * sub sequences. The first sub-sequence is contained in [X0, X1),
1203 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1204 * that (X0, Y0) == (XOFF, YOFF) and
1205 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1207 * This function assumes that the first lines of the specified portions
1208 * of the two files do not match, and likewise that the last lines do not
1209 * match. The caller must trim matching lines from the beginning and end
1210 * of the portions it is going to specify.
1212 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1215 if ($xlim - $xoff > $ylim - $yoff) {
1216 // Things seems faster (I'm not sure I understand why)
1217 // when the shortest sequence in X.
1219 list ($xoff, $xlim, $yoff, $ylim)
1220 = array( $yoff, $ylim, $xoff, $xlim);
1224 for ($i = $ylim - 1; $i >= $yoff; $i--)
1225 $ymatches[$this->xv
[$i]][] = $i;
1227 for ($i = $ylim - 1; $i >= $yoff; $i--)
1228 $ymatches[$this->yv
[$i]][] = $i;
1231 $this->seq
[0]= $yoff - 1;
1232 $this->in_seq
= array();
1233 $ymids[0] = array();
1235 $numer = $xlim - $xoff +
$nchunks - 1;
1237 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1239 for ($i = 0; $i <= $this->lcs
; $i++
)
1240 $ymids[$i][$chunk-1] = $this->seq
[$i];
1242 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1243 for ( ; $x < $x1; $x++
) {
1244 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1245 if (empty($ymatches[$line]))
1247 $matches = $ymatches[$line];
1249 while (list ($junk, $y) = each($matches))
1250 if (empty($this->in_seq
[$y])) {
1251 $k = $this->_lcs_pos($y);
1252 USE_ASSERTS
&& assert($k > 0);
1253 $ymids[$k] = $ymids[$k-1];
1256 while (list ( /* $junk */, $y) = each($matches)) {
1257 if ($y > $this->seq
[$k-1]) {
1258 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1259 // Optimization: this is a common case:
1260 // next match is just replacing previous match.
1261 $this->in_seq
[$this->seq
[$k]] = false;
1262 $this->seq
[$k] = $y;
1263 $this->in_seq
[$y] = 1;
1264 } else if (empty($this->in_seq
[$y])) {
1265 $k = $this->_lcs_pos($y);
1266 USE_ASSERTS
&& assert($k > 0);
1267 $ymids[$k] = $ymids[$k-1];
1273 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1274 $ymid = $ymids[$this->lcs
];
1275 for ($n = 0; $n < $nchunks - 1; $n++
) {
1276 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1277 $y1 = $ymid[$n] +
1;
1278 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1280 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1282 return array($this->lcs
, $seps);
1285 function _lcs_pos ($ypos) {
1287 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1288 $this->seq
[++
$this->lcs
] = $ypos;
1289 $this->in_seq
[$ypos] = 1;
1294 while ($beg < $end) {
1295 $mid = (int)(($beg +
$end) / 2);
1296 if ( $ypos > $this->seq
[$mid] )
1302 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1304 $this->in_seq
[$this->seq
[$end]] = false;
1305 $this->seq
[$end] = $ypos;
1306 $this->in_seq
[$ypos] = 1;
1310 /* Find LCS of two sequences.
1312 * The results are recorded in the vectors $this->{x,y}changed[], by
1313 * storing a 1 in the element for each line that is an insertion
1314 * or deletion (ie. is not in the LCS).
1316 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1318 * Note that XLIM, YLIM are exclusive bounds.
1319 * All line numbers are origin-0 and discarded lines are not counted.
1321 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1322 // Slide down the bottom initial diagonal.
1323 while ($xoff < $xlim && $yoff < $ylim
1324 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1329 // Slide up the top initial diagonal.
1330 while ($xlim > $xoff && $ylim > $yoff
1331 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1336 if ($xoff == $xlim ||
$yoff == $ylim)
1339 // This is ad hoc but seems to work well.
1340 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1341 //$nchunks = max(2,min(8,(int)$nchunks));
1342 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1344 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1348 // X and Y sequences have no common subsequence:
1349 // mark all changed.
1350 while ($yoff < $ylim)
1351 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1352 while ($xoff < $xlim)
1353 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1355 // Use the partitions to split this problem into subproblems.
1358 while ($pt2 = next($seps)) {
1359 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1365 /* Adjust inserts/deletes of identical lines to join changes
1366 * as much as possible.
1368 * We do something when a run of changed lines include a
1369 * line at one end and has an excluded, identical line at the other.
1370 * We are free to choose which identical line is included.
1371 * `compareseq' usually chooses the one at the beginning,
1372 * but usually it is cleaner to consider the following identical line
1373 * to be the "change".
1375 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1377 function _shift_boundaries ($lines, &$changed, $other_changed) {
1378 wfProfileIn( __METHOD__
);
1382 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1383 $len = sizeof($lines);
1384 $other_len = sizeof($other_changed);
1388 * Scan forwards to find beginning of another run of changes.
1389 * Also keep track of the corresponding point in the other file.
1391 * Throughout this code, $i and $j are adjusted together so that
1392 * the first $i elements of $changed and the first $j elements
1393 * of $other_changed both contain the same number of zeros
1394 * (unchanged lines).
1395 * Furthermore, $j is always kept so that $j == $other_len or
1396 * $other_changed[$j] == false.
1398 while ($j < $other_len && $other_changed[$j])
1401 while ($i < $len && ! $changed[$i]) {
1402 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1404 while ($j < $other_len && $other_changed[$j])
1413 // Find the end of this run of changes.
1414 while (++
$i < $len && $changed[$i])
1419 * Record the length of this run of changes, so that
1420 * we can later determine whether the run has grown.
1422 $runlength = $i - $start;
1425 * Move the changed region back, so long as the
1426 * previous unchanged line matches the last changed one.
1427 * This merges with previous changed regions.
1429 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1430 $changed[--$start] = 1;
1431 $changed[--$i] = false;
1432 while ($start > 0 && $changed[$start - 1])
1434 USE_ASSERTS
&& assert('$j > 0');
1435 while ($other_changed[--$j])
1437 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1441 * Set CORRESPONDING to the end of the changed run, at the last
1442 * point where it corresponds to a changed run in the other file.
1443 * CORRESPONDING == LEN means no such point has been found.
1445 $corresponding = $j < $other_len ?
$i : $len;
1448 * Move the changed region forward, so long as the
1449 * first changed line matches the following unchanged one.
1450 * This merges with following changed regions.
1451 * Do this second, so that if there are no merges,
1452 * the changed region is moved forward as far as possible.
1454 while ($i < $len && $lines[$start] == $lines[$i]) {
1455 $changed[$start++
] = false;
1457 while ($i < $len && $changed[$i])
1460 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1462 if ($j < $other_len && $other_changed[$j]) {
1463 $corresponding = $i;
1464 while ($j < $other_len && $other_changed[$j])
1468 } while ($runlength != $i - $start);
1471 * If possible, move the fully-merged run of changes
1472 * back to a corresponding run in the other file.
1474 while ($corresponding < $i) {
1475 $changed[--$start] = 1;
1477 USE_ASSERTS
&& assert('$j > 0');
1478 while ($other_changed[--$j])
1480 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1483 wfProfileOut( __METHOD__
);
1488 * Class representing a 'diff' between two sequences of strings.
1491 * @ingroup DifferenceEngine
1499 * Computes diff between sequences of strings.
1501 * @param $from_lines array An array of strings.
1502 * (Typically these are lines from a file.)
1503 * @param $to_lines array An array of strings.
1505 function Diff($from_lines, $to_lines) {
1506 $eng = new _DiffEngine
;
1507 $this->edits
= $eng->diff($from_lines, $to_lines);
1508 //$this->_check($from_lines, $to_lines);
1512 * Compute reversed Diff.
1516 * $diff = new Diff($lines1, $lines2);
1517 * $rev = $diff->reverse();
1518 * @return object A Diff object representing the inverse of the
1521 function reverse () {
1523 $rev->edits
= array();
1524 foreach ($this->edits
as $edit) {
1525 $rev->edits
[] = $edit->reverse();
1531 * Check for empty diff.
1533 * @return bool True iff two sequences were identical.
1535 function isEmpty () {
1536 foreach ($this->edits
as $edit) {
1537 if ($edit->type
!= 'copy')
1544 * Compute the length of the Longest Common Subsequence (LCS).
1546 * This is mostly for diagnostic purposed.
1548 * @return int The length of the LCS.
1552 foreach ($this->edits
as $edit) {
1553 if ($edit->type
== 'copy')
1554 $lcs +
= sizeof($edit->orig
);
1560 * Get the original set of lines.
1562 * This reconstructs the $from_lines parameter passed to the
1565 * @return array The original sequence of strings.
1570 foreach ($this->edits
as $edit) {
1572 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1578 * Get the closing set of lines.
1580 * This reconstructs the $to_lines parameter passed to the
1583 * @return array The sequence of strings.
1585 function closing() {
1588 foreach ($this->edits
as $edit) {
1590 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1596 * Check a Diff for validity.
1598 * This is here only for debugging purposes.
1600 function _check ($from_lines, $to_lines) {
1601 wfProfileIn( __METHOD__
);
1602 if (serialize($from_lines) != serialize($this->orig()))
1603 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1604 if (serialize($to_lines) != serialize($this->closing()))
1605 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1607 $rev = $this->reverse();
1608 if (serialize($to_lines) != serialize($rev->orig()))
1609 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1610 if (serialize($from_lines) != serialize($rev->closing()))
1611 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1615 foreach ($this->edits
as $edit) {
1616 if ( $prevtype == $edit->type
)
1617 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1618 $prevtype = $edit->type
;
1621 $lcs = $this->lcs();
1622 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1623 wfProfileOut( __METHOD__
);
1628 * @todo document, bad name.
1630 * @ingroup DifferenceEngine
1632 class MappedDiff
extends Diff
1637 * Computes diff between sequences of strings.
1639 * This can be used to compute things like
1640 * case-insensitve diffs, or diffs which ignore
1641 * changes in white-space.
1643 * @param $from_lines array An array of strings.
1644 * (Typically these are lines from a file.)
1646 * @param $to_lines array An array of strings.
1648 * @param $mapped_from_lines array This array should
1649 * have the same size number of elements as $from_lines.
1650 * The elements in $mapped_from_lines and
1651 * $mapped_to_lines are what is actually compared
1652 * when computing the diff.
1654 * @param $mapped_to_lines array This array should
1655 * have the same number of elements as $to_lines.
1657 function MappedDiff($from_lines, $to_lines,
1658 $mapped_from_lines, $mapped_to_lines) {
1659 wfProfileIn( __METHOD__
);
1661 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1662 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1664 $this->Diff($mapped_from_lines, $mapped_to_lines);
1667 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1668 $orig = &$this->edits
[$i]->orig
;
1669 if (is_array($orig)) {
1670 $orig = array_slice($from_lines, $xi, sizeof($orig));
1671 $xi +
= sizeof($orig);
1674 $closing = &$this->edits
[$i]->closing
;
1675 if (is_array($closing)) {
1676 $closing = array_slice($to_lines, $yi, sizeof($closing));
1677 $yi +
= sizeof($closing);
1680 wfProfileOut( __METHOD__
);
1685 * A class to format Diffs
1687 * This class formats the diff in classic diff format.
1688 * It is intended that this class be customized via inheritance,
1689 * to obtain fancier outputs.
1692 * @ingroup DifferenceEngine
1694 class DiffFormatter
{
1696 * Number of leading context "lines" to preserve.
1698 * This should be left at zero for this class, but subclasses
1699 * may want to set this to other values.
1701 var $leading_context_lines = 0;
1704 * Number of trailing context "lines" to preserve.
1706 * This should be left at zero for this class, but subclasses
1707 * may want to set this to other values.
1709 var $trailing_context_lines = 0;
1714 * @param $diff object A Diff object.
1715 * @return string The formatted output.
1717 function format($diff) {
1718 wfProfileIn( __METHOD__
);
1724 $nlead = $this->leading_context_lines
;
1725 $ntrail = $this->trailing_context_lines
;
1727 $this->_start_diff();
1729 foreach ($diff->edits
as $edit) {
1730 if ($edit->type
== 'copy') {
1731 if (is_array($block)) {
1732 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1737 $context = array_slice($edit->orig
, 0, $ntrail);
1738 $block[] = new _DiffOp_Copy($context);
1740 $this->_block($x0, $ntrail +
$xi - $x0,
1741 $y0, $ntrail +
$yi - $y0,
1746 $context = $edit->orig
;
1749 if (! is_array($block)) {
1750 $context = array_slice($context, sizeof($context) - $nlead);
1751 $x0 = $xi - sizeof($context);
1752 $y0 = $yi - sizeof($context);
1755 $block[] = new _DiffOp_Copy($context);
1761 $xi +
= sizeof($edit->orig
);
1763 $yi +
= sizeof($edit->closing
);
1766 if (is_array($block))
1767 $this->_block($x0, $xi - $x0,
1771 $end = $this->_end_diff();
1772 wfProfileOut( __METHOD__
);
1776 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1777 wfProfileIn( __METHOD__
);
1778 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1779 foreach ($edits as $edit) {
1780 if ($edit->type
== 'copy')
1781 $this->_context($edit->orig
);
1782 elseif ($edit->type
== 'add')
1783 $this->_added($edit->closing
);
1784 elseif ($edit->type
== 'delete')
1785 $this->_deleted($edit->orig
);
1786 elseif ($edit->type
== 'change')
1787 $this->_changed($edit->orig
, $edit->closing
);
1789 trigger_error('Unknown edit type', E_USER_ERROR
);
1791 $this->_end_block();
1792 wfProfileOut( __METHOD__
);
1795 function _start_diff() {
1799 function _end_diff() {
1800 $val = ob_get_contents();
1805 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1807 $xbeg .= "," . ($xbeg +
$xlen - 1);
1809 $ybeg .= "," . ($ybeg +
$ylen - 1);
1811 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1814 function _start_block($header) {
1815 echo $header . "\n";
1818 function _end_block() {
1821 function _lines($lines, $prefix = ' ') {
1822 foreach ($lines as $line)
1823 echo "$prefix $line\n";
1826 function _context($lines) {
1827 $this->_lines($lines);
1830 function _added($lines) {
1831 $this->_lines($lines, '>');
1833 function _deleted($lines) {
1834 $this->_lines($lines, '<');
1837 function _changed($orig, $closing) {
1838 $this->_deleted($orig);
1840 $this->_added($closing);
1845 * A formatter that outputs unified diffs
1846 * @ingroup DifferenceEngine
1849 class UnifiedDiffFormatter
extends DiffFormatter
{
1850 var $leading_context_lines = 2;
1851 var $trailing_context_lines = 2;
1853 function _added($lines) {
1854 $this->_lines($lines, '+');
1856 function _deleted($lines) {
1857 $this->_lines($lines, '-');
1859 function _changed($orig, $closing) {
1860 $this->_deleted($orig);
1861 $this->_added($closing);
1863 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1864 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1869 * A pseudo-formatter that just passes along the Diff::$edits array
1870 * @ingroup DifferenceEngine
1872 class ArrayDiffFormatter
extends DiffFormatter
{
1873 function format($diff) {
1877 foreach($diff->edits
as $edit)
1878 switch($edit->type
) {
1880 foreach($edit->closing
as $l) {
1884 'newline' => $newline++
1889 foreach($edit->orig
as $l) {
1891 'action' => 'delete',
1893 'oldline' => $oldline++
,
1898 foreach($edit->orig
as $i => $l) {
1900 'action' => 'change',
1902 'new' => @$edit->closing
[$i],
1903 'oldline' => $oldline++
,
1904 'newline' => $newline++
,
1909 $oldline +
= count($edit->orig
);
1910 $newline +
= count($edit->orig
);
1917 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1921 define('NBSP', ' '); // iso-8859-x non-breaking space.
1926 * @ingroup DifferenceEngine
1928 class _HWLDF_WordAccumulator
{
1929 function _HWLDF_WordAccumulator () {
1930 $this->_lines
= array();
1936 function _flushGroup ($new_tag) {
1937 if ($this->_group
!== '') {
1938 if ($this->_tag
== 'ins')
1939 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1940 htmlspecialchars ( $this->_group
) . '</ins>';
1941 elseif ($this->_tag
== 'del')
1942 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1943 htmlspecialchars ( $this->_group
) . '</del>';
1945 $this->_line
.= htmlspecialchars ( $this->_group
);
1948 $this->_tag
= $new_tag;
1951 function _flushLine ($new_tag) {
1952 $this->_flushGroup($new_tag);
1953 if ($this->_line
!= '')
1954 array_push ( $this->_lines
, $this->_line
);
1956 # make empty lines visible by inserting an NBSP
1957 array_push ( $this->_lines
, NBSP
);
1961 function addWords ($words, $tag = '') {
1962 if ($tag != $this->_tag
)
1963 $this->_flushGroup($tag);
1965 foreach ($words as $word) {
1966 // new-line should only come as first char of word.
1969 if ($word[0] == "\n") {
1970 $this->_flushLine($tag);
1971 $word = substr($word, 1);
1973 assert(!strstr($word, "\n"));
1974 $this->_group
.= $word;
1978 function getLines() {
1979 $this->_flushLine('~done');
1980 return $this->_lines
;
1987 * @ingroup DifferenceEngine
1989 class WordLevelDiff
extends MappedDiff
{
1990 const MAX_LINE_LENGTH
= 10000;
1992 function WordLevelDiff ($orig_lines, $closing_lines) {
1993 wfProfileIn( __METHOD__
);
1995 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1996 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1998 $this->MappedDiff($orig_words, $closing_words,
1999 $orig_stripped, $closing_stripped);
2000 wfProfileOut( __METHOD__
);
2003 function _split($lines) {
2004 wfProfileIn( __METHOD__
);
2007 $stripped = array();
2009 foreach ( $lines as $line ) {
2010 # If the line is too long, just pretend the entire line is one big word
2011 # This prevents resource exhaustion problems
2018 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2020 $stripped[] = $line;
2023 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2026 $words = array_merge( $words, $m[0] );
2027 $stripped = array_merge( $stripped, $m[1] );
2031 wfProfileOut( __METHOD__
);
2032 return array($words, $stripped);
2036 wfProfileIn( __METHOD__
);
2037 $orig = new _HWLDF_WordAccumulator
;
2039 foreach ($this->edits
as $edit) {
2040 if ($edit->type
== 'copy')
2041 $orig->addWords($edit->orig
);
2042 elseif ($edit->orig
)
2043 $orig->addWords($edit->orig
, 'del');
2045 $lines = $orig->getLines();
2046 wfProfileOut( __METHOD__
);
2050 function closing () {
2051 wfProfileIn( __METHOD__
);
2052 $closing = new _HWLDF_WordAccumulator
;
2054 foreach ($this->edits
as $edit) {
2055 if ($edit->type
== 'copy')
2056 $closing->addWords($edit->closing
);
2057 elseif ($edit->closing
)
2058 $closing->addWords($edit->closing
, 'ins');
2060 $lines = $closing->getLines();
2061 wfProfileOut( __METHOD__
);
2067 * Wikipedia Table style diff formatter.
2070 * @ingroup DifferenceEngine
2072 class TableDiffFormatter
extends DiffFormatter
{
2073 function TableDiffFormatter() {
2074 $this->leading_context_lines
= 2;
2075 $this->trailing_context_lines
= 2;
2078 public static function escapeWhiteSpace( $msg ) {
2079 $msg = preg_replace( '/^ /m', ' ', $msg );
2080 $msg = preg_replace( '/ $/m', ' ', $msg );
2081 $msg = preg_replace( '/ /', ' ', $msg );
2085 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2086 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2087 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2091 function _start_block( $header ) {
2095 function _end_block() {
2098 function _lines( $lines, $prefix=' ', $color='white' ) {
2101 # HTML-escape parameter before calling this
2102 function addedLine( $line ) {
2103 return $this->wrapLine( '+', 'diff-addedline', $line );
2106 # HTML-escape parameter before calling this
2107 function deletedLine( $line ) {
2108 return $this->wrapLine( '-', 'diff-deletedline', $line );
2111 # HTML-escape parameter before calling this
2112 function contextLine( $line ) {
2113 return $this->wrapLine( ' ', 'diff-context', $line );
2116 private function wrapLine( $marker, $class, $line ) {
2117 if( $line !== '' ) {
2118 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2119 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2121 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2124 function emptyLine() {
2125 return '<td colspan="2"> </td>';
2128 function _added( $lines ) {
2129 foreach ($lines as $line) {
2130 echo '<tr>' . $this->emptyLine() .
2131 $this->addedLine( '<ins class="diffchange">' .
2132 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2136 function _deleted($lines) {
2137 foreach ($lines as $line) {
2138 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2139 htmlspecialchars ( $line ) . '</del>' ) .
2140 $this->emptyLine() . "</tr>\n";
2144 function _context( $lines ) {
2145 foreach ($lines as $line) {
2147 $this->contextLine( htmlspecialchars ( $line ) ) .
2148 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2152 function _changed( $orig, $closing ) {
2153 wfProfileIn( __METHOD__
);
2155 $diff = new WordLevelDiff( $orig, $closing );
2156 $del = $diff->orig();
2157 $add = $diff->closing();
2159 # Notice that WordLevelDiff returns HTML-escaped output.
2160 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2162 while ( $line = array_shift( $del ) ) {
2163 $aline = array_shift( $add );
2164 echo '<tr>' . $this->deletedLine( $line ) .
2165 $this->addedLine( $aline ) . "</tr>\n";
2167 foreach ($add as $line) { # If any leftovers
2168 echo '<tr>' . $this->emptyLine() .
2169 $this->addedLine( $line ) . "</tr>\n";
2171 wfProfileOut( __METHOD__
);