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 # Output the diff if allowed
287 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
) && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
288 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
289 if( $deleted && (!$this->unhide ||
!$allowed) ) {
290 $this->showDiffStyle();
291 $multi = $this->getMultiNotice();
292 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
293 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
294 array( 'rev-deleted-no-diff' ) );
295 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
296 $multi = $this->getMultiNotice();
297 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
298 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
299 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
300 $this->renderHtmlDiff();
302 if( $wgEnableHtmlDiff ) {
303 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
304 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
306 $this->showDiff( $oldHeader, $newHeader );
308 $this->renderNewRevision();
311 wfProfileOut( __METHOD__
);
315 * Show the new revision of the page.
317 function renderNewRevision() {
318 global $wgOut, $wgUser;
319 wfProfileIn( __METHOD__
);
321 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
322 # Add deleted rev tag if needed
323 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
324 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
325 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
326 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
329 if( !$this->mNewRev
->isCurrent() ) {
330 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
333 $this->loadNewText();
334 if( is_object( $this->mNewRev
) ) {
335 $wgOut->setRevisionId( $this->mNewRev
->getId() );
338 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
339 // Stolen from Article::view --AG 2007-10-11
340 // Give hooks a chance to customise the output
341 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
342 // Wrap the whole lot in a <pre> and don't parse
344 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
345 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
346 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
347 $wgOut->addHTML( "\n</pre>\n" );
350 $wgOut->addWikiTextTidy( $this->mNewtext
);
353 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
354 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
356 # Add redundant patrol link on bottom...
357 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
358 $sk = $wgUser->getSkin();
360 "<div class='patrollink'>[" . $sk->makeKnownLinkObj( $this->mTitle
,
361 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) .
366 wfProfileOut( __METHOD__
);
370 function renderHtmlDiff() {
371 global $wgOut, $wgTitle, $wgParser, $wgDebugComments;
372 wfProfileIn( __METHOD__
);
374 $this->showDiffStyle();
376 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
377 #add deleted rev tag if needed
378 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
379 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
380 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
381 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
384 if( !$this->mNewRev
->isCurrent() ) {
385 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
391 if( is_object( $this->mOldRev
) ) {
392 $wgOut->setRevisionId( $this->mOldRev
->getId() );
395 $popts = $wgOut->parserOptions();
396 $oldTidy = $popts->setTidy( true );
397 $popts->setEditSection( false );
399 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
400 $popts->setTidy( $oldTidy );
403 //$wgOut->addParserOutputNoText( $parserOutput );
404 $oldHtml = $parserOutput->getText();
405 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
408 if( is_object( $this->mNewRev
) ) {
409 $wgOut->setRevisionId( $this->mNewRev
->getId() );
412 $popts = $wgOut->parserOptions();
413 $oldTidy = $popts->setTidy( true );
415 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
416 $popts->setTidy( $oldTidy );
418 $wgOut->addParserOutputNoText( $parserOutput );
419 $newHtml = $parserOutput->getText();
420 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
422 unset($parserOutput, $popts);
424 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
425 $differ->htmlDiff($oldHtml, $newHtml);
426 if ( $wgDebugComments ) {
427 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
430 wfProfileOut( __METHOD__
);
434 * Show the first revision of an article. Uses normal diff headers in
435 * contrast to normal "old revision" display style.
437 function showFirstRevision() {
438 global $wgOut, $wgUser;
439 wfProfileIn( __METHOD__
);
441 # Get article text from the DB
443 if ( ! $this->loadNewText() ) {
444 $t = $this->mTitle
->getPrefixedText();
445 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
446 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
447 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
448 wfProfileOut( __METHOD__
);
451 if ( $this->mNewRev
->isCurrent() ) {
452 $wgOut->setArticleFlag( true );
455 # Check if user is allowed to look at this page. If not, bail out.
457 if ( !$this->mTitle
->userCanRead() ) {
458 $wgOut->loginToUse();
460 wfProfileOut( __METHOD__
);
461 throw new MWException("Permission Error: you do not have access to view this page");
464 # Prepare the header box
466 $sk = $wgUser->getSkin();
468 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
472 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
473 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
475 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
476 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
478 $wgOut->addHTML( $header );
480 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
481 $wgOut->setRobotPolicy( 'noindex,nofollow' );
483 wfProfileOut( __METHOD__
);
486 function htmlDiffArgument(){
487 global $wgEnableHtmlDiff;
488 if($wgEnableHtmlDiff){
490 return '&htmldiff=1';
492 return '&htmldiff=0';
500 * Get the diff text, send it to $wgOut
501 * Returns false if the diff could not be generated, otherwise returns true
503 function showDiff( $otitle, $ntitle ) {
505 $diff = $this->getDiff( $otitle, $ntitle );
506 if ( $diff === false ) {
507 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
510 $this->showDiffStyle();
511 $wgOut->addHTML( $diff );
517 * Add style sheets and supporting JS for diff display.
519 function showDiffStyle() {
520 global $wgStylePath, $wgStyleVersion, $wgOut;
521 $wgOut->addStyle( 'common/diff.css' );
523 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
524 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
528 * Get complete diff table, including header
530 * @param Title $otitle Old title
531 * @param Title $ntitle New title
534 function getDiff( $otitle, $ntitle ) {
535 $body = $this->getDiffBody();
536 if ( $body === false ) {
539 $multi = $this->getMultiNotice();
540 return $this->addHeader( $body, $otitle, $ntitle, $multi );
545 * Get the diff table body, without header
549 function getDiffBody() {
551 wfProfileIn( __METHOD__
);
552 $this->mCacheHit
= true;
553 // Check if the diff should be hidden from this user
554 if ( !$this->loadRevisionData() )
556 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
558 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
560 } else if ( $this->mOldRev
&& $this->mNewRev
&& $this->mOldRev
->getID() == $this->mNewRev
->getID() ) {
565 if ( $this->mOldid
&& $this->mNewid
) {
566 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
568 if ( !$this->mRefreshCache
) {
569 $difftext = $wgMemc->get( $key );
571 wfIncrStats( 'diff_cache_hit' );
572 $difftext = $this->localiseLineNumbers( $difftext );
573 $difftext .= "\n<!-- diff cache key $key -->\n";
574 wfProfileOut( __METHOD__
);
577 } // don't try to load but save the result
579 $this->mCacheHit
= false;
581 // Loadtext is permission safe, this just clears out the diff
582 if ( !$this->loadText() ) {
583 wfProfileOut( __METHOD__
);
587 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
589 // Save to cache for 7 days
590 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
591 wfIncrStats( 'diff_uncacheable' );
592 } else if ( $key !== false && $difftext !== false ) {
593 wfIncrStats( 'diff_cache_miss' );
594 $wgMemc->set( $key, $difftext, 7*86400 );
596 wfIncrStats( 'diff_uncacheable' );
598 // Replace line numbers with the text in the user's language
599 if ( $difftext !== false ) {
600 $difftext = $this->localiseLineNumbers( $difftext );
602 wfProfileOut( __METHOD__
);
607 * Generate a diff, no caching
608 * $otext and $ntext must be already segmented
610 function generateDiffBody( $otext, $ntext ) {
611 global $wgExternalDiffEngine, $wgContLang;
613 $otext = str_replace( "\r\n", "\n", $otext );
614 $ntext = str_replace( "\r\n", "\n", $ntext );
616 if ( $wgExternalDiffEngine == 'wikidiff' ) {
617 # For historical reasons, external diff engine expects
618 # input text to be HTML-escaped already
619 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
620 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
621 if( !function_exists( 'wikidiff_do_diff' ) ) {
622 dl('php_wikidiff.so');
624 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
625 $this->debug( 'wikidiff1' );
628 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
629 # Better external diff engine, the 2 may some day be dropped
630 # This one does the escaping and segmenting itself
631 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
632 wfProfileIn( __METHOD__
. "-dl" );
633 @dl
('php_wikidiff2.so');
634 wfProfileOut( __METHOD__
. "-dl" );
636 if ( function_exists( 'wikidiff2_do_diff' ) ) {
637 wfProfileIn( 'wikidiff2_do_diff' );
638 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
639 $text .= $this->debug( 'wikidiff2' );
640 wfProfileOut( 'wikidiff2_do_diff' );
644 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
646 global $wgTmpDirectory;
647 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
648 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
650 $tempFile1 = fopen( $tempName1, "w" );
652 wfProfileOut( __METHOD__
);
655 $tempFile2 = fopen( $tempName2, "w" );
657 wfProfileOut( __METHOD__
);
660 fwrite( $tempFile1, $otext );
661 fwrite( $tempFile2, $ntext );
662 fclose( $tempFile1 );
663 fclose( $tempFile2 );
664 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
665 wfProfileIn( __METHOD__
. "-shellexec" );
666 $difftext = wfShellExec( $cmd );
667 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
668 wfProfileOut( __METHOD__
. "-shellexec" );
669 unlink( $tempName1 );
670 unlink( $tempName2 );
675 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
676 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
677 $diffs = new Diff( $ota, $nta );
678 $formatter = new TableDiffFormatter();
679 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
684 * Generate a debug comment indicating diff generating time,
685 * server node, and generator backend.
687 protected function debug( $generator="internal" ) {
688 global $wgShowHostnames;
689 $data = array( $generator );
690 if( $wgShowHostnames ) {
691 $data[] = wfHostname();
693 $data[] = wfTimestamp( TS_DB
);
694 return "<!-- diff generator: " .
703 * Replace line numbers with the text in the user's language
705 function localiseLineNumbers( $text ) {
706 return preg_replace_callback( '/<!--LINE (\d+)-->/',
707 array( &$this, 'localiseLineNumbersCb' ), $text );
710 function localiseLineNumbersCb( $matches ) {
712 return wfMsgExt( 'lineno', array (), $wgLang->formatNum( $matches[1] ) );
717 * If there are revisions between the ones being compared, return a note saying so.
719 function getMultiNotice() {
720 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
723 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
724 // Comparing two different pages? Count would be meaningless.
728 $oldid = $this->mOldRev
->getId();
729 $newid = $this->mNewRev
->getId();
730 if ( $oldid > $newid ) {
731 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
734 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
738 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
743 * Add the header to a diff body
745 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
748 <col class='diff-marker' />
749 <col class='diff-content' />
750 <col class='diff-marker' />
751 <col class='diff-content' />
753 <td colspan='2' class='diff-otitle'>{$otitle}</td>
754 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
759 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
761 return $header . $diff . "</table>";
765 * Use specified text instead of loading from the database
767 function setText( $oldText, $newText ) {
768 $this->mOldtext
= $oldText;
769 $this->mNewtext
= $newText;
770 $this->mTextLoaded
= 2;
771 $this->mRevisionsLoaded
= true;
775 * Load revision metadata for the specified articles. If newid is 0, then compare
776 * the old article in oldid to the current article; if oldid is 0, then
777 * compare the current article to the immediately previous one (ignoring the
780 * If oldid is false, leave the corresponding revision object set
781 * to false. This is impossible via ordinary user input, and is provided for
784 function loadRevisionData() {
785 global $wgLang, $wgUser;
786 if ( $this->mRevisionsLoaded
) {
789 // Whether it succeeds or fails, we don't want to try again
790 $this->mRevisionsLoaded
= true;
793 // Load the new revision object
794 $this->mNewRev
= $this->mNewid
795 ? Revision
::newFromId( $this->mNewid
)
796 : Revision
::newFromTitle( $this->mTitle
);
797 if( !$this->mNewRev
instanceof Revision
)
800 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
801 $this->mNewid
= $this->mNewRev
->getId();
803 // Check if page is editable
804 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
806 // Set assorted variables
807 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
808 $this->mNewPage
= $this->mNewRev
->getTitle();
809 if( $this->mNewRev
->isCurrent() ) {
810 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
811 $this->mPagetitle
= wfMsgHTML( 'currentrev-asof', $timestamp );
812 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
814 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
815 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
818 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
819 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
820 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
822 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
823 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
825 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
826 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
827 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
828 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
831 // Load the old revision object
832 $this->mOldRev
= false;
833 if( $this->mOldid
) {
834 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
835 } elseif ( $this->mOldid
=== 0 ) {
836 $rev = $this->mNewRev
->getPrevious();
838 $this->mOldid
= $rev->getId();
839 $this->mOldRev
= $rev;
841 // No previous revision; mark to show as first-version only.
842 $this->mOldid
= false;
843 $this->mOldRev
= false;
845 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
847 if( is_null( $this->mOldRev
) ) {
851 if ( $this->mOldRev
) {
852 $this->mOldPage
= $this->mOldRev
->getTitle();
854 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
855 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
856 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
857 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
859 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
860 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
861 // Add an "undo" link
862 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
863 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
864 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
865 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
866 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
869 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
870 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
871 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
872 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
880 * Load the text of the revisions, as well as revision data.
882 function loadText() {
883 if ( $this->mTextLoaded
== 2 ) {
886 // Whether it succeeds or fails, we don't want to try again
887 $this->mTextLoaded
= 2;
890 if ( !$this->loadRevisionData() ) {
893 if ( $this->mOldRev
) {
894 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
895 if ( $this->mOldtext
=== false ) {
899 if ( $this->mNewRev
) {
900 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
901 if ( $this->mNewtext
=== false ) {
909 * Load the text of the new revision, not the old one
911 function loadNewText() {
912 if ( $this->mTextLoaded
>= 1 ) {
915 $this->mTextLoaded
= 1;
917 if ( !$this->loadRevisionData() ) {
920 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
927 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
929 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
930 // You may copy this code freely under the conditions of the GPL.
933 define('USE_ASSERTS', function_exists('assert'));
938 * @ingroup DifferenceEngine
946 trigger_error('pure virtual', E_USER_ERROR
);
950 return $this->orig ?
sizeof($this->orig
) : 0;
953 function nclosing() {
954 return $this->closing ?
sizeof($this->closing
) : 0;
961 * @ingroup DifferenceEngine
963 class _DiffOp_Copy
extends _DiffOp
{
966 function _DiffOp_Copy ($orig, $closing = false) {
967 if (!is_array($closing))
970 $this->closing
= $closing;
974 return new _DiffOp_Copy($this->closing
, $this->orig
);
981 * @ingroup DifferenceEngine
983 class _DiffOp_Delete
extends _DiffOp
{
984 var $type = 'delete';
986 function _DiffOp_Delete ($lines) {
987 $this->orig
= $lines;
988 $this->closing
= false;
992 return new _DiffOp_Add($this->orig
);
999 * @ingroup DifferenceEngine
1001 class _DiffOp_Add
extends _DiffOp
{
1004 function _DiffOp_Add ($lines) {
1005 $this->closing
= $lines;
1006 $this->orig
= false;
1009 function reverse() {
1010 return new _DiffOp_Delete($this->closing
);
1017 * @ingroup DifferenceEngine
1019 class _DiffOp_Change
extends _DiffOp
{
1020 var $type = 'change';
1022 function _DiffOp_Change ($orig, $closing) {
1023 $this->orig
= $orig;
1024 $this->closing
= $closing;
1027 function reverse() {
1028 return new _DiffOp_Change($this->closing
, $this->orig
);
1033 * Class used internally by Diff to actually compute the diffs.
1035 * The algorithm used here is mostly lifted from the perl module
1036 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1037 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1039 * More ideas are taken from:
1040 * http://www.ics.uci.edu/~eppstein/161/960229.html
1042 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1043 * diffutils-2.7, which can be found at:
1044 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1046 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1049 * Line length limits for robustness added by Tim Starling, 2005-08-31
1050 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1052 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1054 * @ingroup DifferenceEngine
1058 const MAX_XREF_LENGTH
= 10000;
1060 function diff ($from_lines, $to_lines){
1061 wfProfileIn( __METHOD__
);
1063 // Diff and store locally
1064 $this->diff_local($from_lines, $to_lines);
1066 // Merge edits when possible
1067 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1068 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1070 // Compute the edit operations.
1071 $n_from = sizeof($from_lines);
1072 $n_to = sizeof($to_lines);
1076 while ($xi < $n_from ||
$yi < $n_to) {
1077 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1078 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1080 // Skip matching "snake".
1082 while ( $xi < $n_from && $yi < $n_to
1083 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1084 $copy[] = $from_lines[$xi++
];
1088 $edits[] = new _DiffOp_Copy($copy);
1090 // Find deletes & adds.
1092 while ($xi < $n_from && $this->xchanged
[$xi])
1093 $delete[] = $from_lines[$xi++
];
1096 while ($yi < $n_to && $this->ychanged
[$yi])
1097 $add[] = $to_lines[$yi++
];
1099 if ($delete && $add)
1100 $edits[] = new _DiffOp_Change($delete, $add);
1102 $edits[] = new _DiffOp_Delete($delete);
1104 $edits[] = new _DiffOp_Add($add);
1106 wfProfileOut( __METHOD__
);
1110 function diff_local ($from_lines, $to_lines) {
1111 global $wgExternalDiffEngine;
1112 wfProfileIn( __METHOD__
);
1114 if($wgExternalDiffEngine == 'wikidiff3'){
1116 $wikidiff3 = new WikiDiff3();
1117 $wikidiff3->diff($from_lines, $to_lines);
1118 $this->xchanged
= $wikidiff3->removed
;
1119 $this->ychanged
= $wikidiff3->added
;
1123 $n_from = sizeof($from_lines);
1124 $n_to = sizeof($to_lines);
1125 $this->xchanged
= $this->ychanged
= array();
1126 $this->xv
= $this->yv
= array();
1127 $this->xind
= $this->yind
= array();
1129 unset($this->in_seq
);
1132 // Skip leading common lines.
1133 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1134 if ($from_lines[$skip] !== $to_lines[$skip])
1136 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1138 // Skip trailing common lines.
1139 $xi = $n_from; $yi = $n_to;
1140 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1141 if ($from_lines[$xi] !== $to_lines[$yi])
1143 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1146 // Ignore lines which do not exist in both files.
1147 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1148 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1151 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1152 $line = $to_lines[$yi];
1153 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1155 $yhash[$this->_line_hash($line)] = 1;
1156 $this->yv
[] = $line;
1157 $this->yind
[] = $yi;
1159 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1160 $line = $from_lines[$xi];
1161 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1163 $this->xv
[] = $line;
1164 $this->xind
[] = $xi;
1168 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1170 wfProfileOut( __METHOD__
);
1174 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1176 function _line_hash( $line ) {
1177 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1178 return md5( $line );
1184 /* Divide the Largest Common Subsequence (LCS) of the sequences
1185 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1188 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1189 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1190 * sub sequences. The first sub-sequence is contained in [X0, X1),
1191 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1192 * that (X0, Y0) == (XOFF, YOFF) and
1193 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1195 * This function assumes that the first lines of the specified portions
1196 * of the two files do not match, and likewise that the last lines do not
1197 * match. The caller must trim matching lines from the beginning and end
1198 * of the portions it is going to specify.
1200 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1203 if ($xlim - $xoff > $ylim - $yoff) {
1204 // Things seems faster (I'm not sure I understand why)
1205 // when the shortest sequence in X.
1207 list ($xoff, $xlim, $yoff, $ylim)
1208 = array( $yoff, $ylim, $xoff, $xlim);
1212 for ($i = $ylim - 1; $i >= $yoff; $i--)
1213 $ymatches[$this->xv
[$i]][] = $i;
1215 for ($i = $ylim - 1; $i >= $yoff; $i--)
1216 $ymatches[$this->yv
[$i]][] = $i;
1219 $this->seq
[0]= $yoff - 1;
1220 $this->in_seq
= array();
1221 $ymids[0] = array();
1223 $numer = $xlim - $xoff +
$nchunks - 1;
1225 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1227 for ($i = 0; $i <= $this->lcs
; $i++
)
1228 $ymids[$i][$chunk-1] = $this->seq
[$i];
1230 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1231 for ( ; $x < $x1; $x++
) {
1232 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1233 if (empty($ymatches[$line]))
1235 $matches = $ymatches[$line];
1237 while (list ($junk, $y) = each($matches))
1238 if (empty($this->in_seq
[$y])) {
1239 $k = $this->_lcs_pos($y);
1240 USE_ASSERTS
&& assert($k > 0);
1241 $ymids[$k] = $ymids[$k-1];
1244 while (list ( /* $junk */, $y) = each($matches)) {
1245 if ($y > $this->seq
[$k-1]) {
1246 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1247 // Optimization: this is a common case:
1248 // next match is just replacing previous match.
1249 $this->in_seq
[$this->seq
[$k]] = false;
1250 $this->seq
[$k] = $y;
1251 $this->in_seq
[$y] = 1;
1252 } else if (empty($this->in_seq
[$y])) {
1253 $k = $this->_lcs_pos($y);
1254 USE_ASSERTS
&& assert($k > 0);
1255 $ymids[$k] = $ymids[$k-1];
1261 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1262 $ymid = $ymids[$this->lcs
];
1263 for ($n = 0; $n < $nchunks - 1; $n++
) {
1264 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1265 $y1 = $ymid[$n] +
1;
1266 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1268 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1270 return array($this->lcs
, $seps);
1273 function _lcs_pos ($ypos) {
1275 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1276 $this->seq
[++
$this->lcs
] = $ypos;
1277 $this->in_seq
[$ypos] = 1;
1282 while ($beg < $end) {
1283 $mid = (int)(($beg +
$end) / 2);
1284 if ( $ypos > $this->seq
[$mid] )
1290 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1292 $this->in_seq
[$this->seq
[$end]] = false;
1293 $this->seq
[$end] = $ypos;
1294 $this->in_seq
[$ypos] = 1;
1298 /* Find LCS of two sequences.
1300 * The results are recorded in the vectors $this->{x,y}changed[], by
1301 * storing a 1 in the element for each line that is an insertion
1302 * or deletion (ie. is not in the LCS).
1304 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1306 * Note that XLIM, YLIM are exclusive bounds.
1307 * All line numbers are origin-0 and discarded lines are not counted.
1309 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1310 // Slide down the bottom initial diagonal.
1311 while ($xoff < $xlim && $yoff < $ylim
1312 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1317 // Slide up the top initial diagonal.
1318 while ($xlim > $xoff && $ylim > $yoff
1319 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1324 if ($xoff == $xlim ||
$yoff == $ylim)
1327 // This is ad hoc but seems to work well.
1328 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1329 //$nchunks = max(2,min(8,(int)$nchunks));
1330 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1332 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1336 // X and Y sequences have no common subsequence:
1337 // mark all changed.
1338 while ($yoff < $ylim)
1339 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1340 while ($xoff < $xlim)
1341 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1343 // Use the partitions to split this problem into subproblems.
1346 while ($pt2 = next($seps)) {
1347 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1353 /* Adjust inserts/deletes of identical lines to join changes
1354 * as much as possible.
1356 * We do something when a run of changed lines include a
1357 * line at one end and has an excluded, identical line at the other.
1358 * We are free to choose which identical line is included.
1359 * `compareseq' usually chooses the one at the beginning,
1360 * but usually it is cleaner to consider the following identical line
1361 * to be the "change".
1363 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1365 function _shift_boundaries ($lines, &$changed, $other_changed) {
1366 wfProfileIn( __METHOD__
);
1370 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1371 $len = sizeof($lines);
1372 $other_len = sizeof($other_changed);
1376 * Scan forwards to find beginning of another run of changes.
1377 * Also keep track of the corresponding point in the other file.
1379 * Throughout this code, $i and $j are adjusted together so that
1380 * the first $i elements of $changed and the first $j elements
1381 * of $other_changed both contain the same number of zeros
1382 * (unchanged lines).
1383 * Furthermore, $j is always kept so that $j == $other_len or
1384 * $other_changed[$j] == false.
1386 while ($j < $other_len && $other_changed[$j])
1389 while ($i < $len && ! $changed[$i]) {
1390 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1392 while ($j < $other_len && $other_changed[$j])
1401 // Find the end of this run of changes.
1402 while (++
$i < $len && $changed[$i])
1407 * Record the length of this run of changes, so that
1408 * we can later determine whether the run has grown.
1410 $runlength = $i - $start;
1413 * Move the changed region back, so long as the
1414 * previous unchanged line matches the last changed one.
1415 * This merges with previous changed regions.
1417 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1418 $changed[--$start] = 1;
1419 $changed[--$i] = false;
1420 while ($start > 0 && $changed[$start - 1])
1422 USE_ASSERTS
&& assert('$j > 0');
1423 while ($other_changed[--$j])
1425 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1429 * Set CORRESPONDING to the end of the changed run, at the last
1430 * point where it corresponds to a changed run in the other file.
1431 * CORRESPONDING == LEN means no such point has been found.
1433 $corresponding = $j < $other_len ?
$i : $len;
1436 * Move the changed region forward, so long as the
1437 * first changed line matches the following unchanged one.
1438 * This merges with following changed regions.
1439 * Do this second, so that if there are no merges,
1440 * the changed region is moved forward as far as possible.
1442 while ($i < $len && $lines[$start] == $lines[$i]) {
1443 $changed[$start++
] = false;
1445 while ($i < $len && $changed[$i])
1448 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1450 if ($j < $other_len && $other_changed[$j]) {
1451 $corresponding = $i;
1452 while ($j < $other_len && $other_changed[$j])
1456 } while ($runlength != $i - $start);
1459 * If possible, move the fully-merged run of changes
1460 * back to a corresponding run in the other file.
1462 while ($corresponding < $i) {
1463 $changed[--$start] = 1;
1465 USE_ASSERTS
&& assert('$j > 0');
1466 while ($other_changed[--$j])
1468 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1471 wfProfileOut( __METHOD__
);
1476 * Class representing a 'diff' between two sequences of strings.
1479 * @ingroup DifferenceEngine
1487 * Computes diff between sequences of strings.
1489 * @param $from_lines array An array of strings.
1490 * (Typically these are lines from a file.)
1491 * @param $to_lines array An array of strings.
1493 function Diff($from_lines, $to_lines) {
1494 $eng = new _DiffEngine
;
1495 $this->edits
= $eng->diff($from_lines, $to_lines);
1496 //$this->_check($from_lines, $to_lines);
1500 * Compute reversed Diff.
1504 * $diff = new Diff($lines1, $lines2);
1505 * $rev = $diff->reverse();
1506 * @return object A Diff object representing the inverse of the
1509 function reverse () {
1511 $rev->edits
= array();
1512 foreach ($this->edits
as $edit) {
1513 $rev->edits
[] = $edit->reverse();
1519 * Check for empty diff.
1521 * @return bool True iff two sequences were identical.
1523 function isEmpty () {
1524 foreach ($this->edits
as $edit) {
1525 if ($edit->type
!= 'copy')
1532 * Compute the length of the Longest Common Subsequence (LCS).
1534 * This is mostly for diagnostic purposed.
1536 * @return int The length of the LCS.
1540 foreach ($this->edits
as $edit) {
1541 if ($edit->type
== 'copy')
1542 $lcs +
= sizeof($edit->orig
);
1548 * Get the original set of lines.
1550 * This reconstructs the $from_lines parameter passed to the
1553 * @return array The original sequence of strings.
1558 foreach ($this->edits
as $edit) {
1560 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1566 * Get the closing set of lines.
1568 * This reconstructs the $to_lines parameter passed to the
1571 * @return array The sequence of strings.
1573 function closing() {
1576 foreach ($this->edits
as $edit) {
1578 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1584 * Check a Diff for validity.
1586 * This is here only for debugging purposes.
1588 function _check ($from_lines, $to_lines) {
1589 wfProfileIn( __METHOD__
);
1590 if (serialize($from_lines) != serialize($this->orig()))
1591 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1592 if (serialize($to_lines) != serialize($this->closing()))
1593 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1595 $rev = $this->reverse();
1596 if (serialize($to_lines) != serialize($rev->orig()))
1597 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1598 if (serialize($from_lines) != serialize($rev->closing()))
1599 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1603 foreach ($this->edits
as $edit) {
1604 if ( $prevtype == $edit->type
)
1605 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1606 $prevtype = $edit->type
;
1609 $lcs = $this->lcs();
1610 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1611 wfProfileOut( __METHOD__
);
1616 * @todo document, bad name.
1618 * @ingroup DifferenceEngine
1620 class MappedDiff
extends Diff
1625 * Computes diff between sequences of strings.
1627 * This can be used to compute things like
1628 * case-insensitve diffs, or diffs which ignore
1629 * changes in white-space.
1631 * @param $from_lines array An array of strings.
1632 * (Typically these are lines from a file.)
1634 * @param $to_lines array An array of strings.
1636 * @param $mapped_from_lines array This array should
1637 * have the same size number of elements as $from_lines.
1638 * The elements in $mapped_from_lines and
1639 * $mapped_to_lines are what is actually compared
1640 * when computing the diff.
1642 * @param $mapped_to_lines array This array should
1643 * have the same number of elements as $to_lines.
1645 function MappedDiff($from_lines, $to_lines,
1646 $mapped_from_lines, $mapped_to_lines) {
1647 wfProfileIn( __METHOD__
);
1649 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1650 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1652 $this->Diff($mapped_from_lines, $mapped_to_lines);
1655 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1656 $orig = &$this->edits
[$i]->orig
;
1657 if (is_array($orig)) {
1658 $orig = array_slice($from_lines, $xi, sizeof($orig));
1659 $xi +
= sizeof($orig);
1662 $closing = &$this->edits
[$i]->closing
;
1663 if (is_array($closing)) {
1664 $closing = array_slice($to_lines, $yi, sizeof($closing));
1665 $yi +
= sizeof($closing);
1668 wfProfileOut( __METHOD__
);
1673 * A class to format Diffs
1675 * This class formats the diff in classic diff format.
1676 * It is intended that this class be customized via inheritance,
1677 * to obtain fancier outputs.
1680 * @ingroup DifferenceEngine
1682 class DiffFormatter
{
1684 * Number of leading context "lines" to preserve.
1686 * This should be left at zero for this class, but subclasses
1687 * may want to set this to other values.
1689 var $leading_context_lines = 0;
1692 * Number of trailing context "lines" to preserve.
1694 * This should be left at zero for this class, but subclasses
1695 * may want to set this to other values.
1697 var $trailing_context_lines = 0;
1702 * @param $diff object A Diff object.
1703 * @return string The formatted output.
1705 function format($diff) {
1706 wfProfileIn( __METHOD__
);
1712 $nlead = $this->leading_context_lines
;
1713 $ntrail = $this->trailing_context_lines
;
1715 $this->_start_diff();
1717 foreach ($diff->edits
as $edit) {
1718 if ($edit->type
== 'copy') {
1719 if (is_array($block)) {
1720 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1725 $context = array_slice($edit->orig
, 0, $ntrail);
1726 $block[] = new _DiffOp_Copy($context);
1728 $this->_block($x0, $ntrail +
$xi - $x0,
1729 $y0, $ntrail +
$yi - $y0,
1734 $context = $edit->orig
;
1737 if (! is_array($block)) {
1738 $context = array_slice($context, sizeof($context) - $nlead);
1739 $x0 = $xi - sizeof($context);
1740 $y0 = $yi - sizeof($context);
1743 $block[] = new _DiffOp_Copy($context);
1749 $xi +
= sizeof($edit->orig
);
1751 $yi +
= sizeof($edit->closing
);
1754 if (is_array($block))
1755 $this->_block($x0, $xi - $x0,
1759 $end = $this->_end_diff();
1760 wfProfileOut( __METHOD__
);
1764 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1765 wfProfileIn( __METHOD__
);
1766 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1767 foreach ($edits as $edit) {
1768 if ($edit->type
== 'copy')
1769 $this->_context($edit->orig
);
1770 elseif ($edit->type
== 'add')
1771 $this->_added($edit->closing
);
1772 elseif ($edit->type
== 'delete')
1773 $this->_deleted($edit->orig
);
1774 elseif ($edit->type
== 'change')
1775 $this->_changed($edit->orig
, $edit->closing
);
1777 trigger_error('Unknown edit type', E_USER_ERROR
);
1779 $this->_end_block();
1780 wfProfileOut( __METHOD__
);
1783 function _start_diff() {
1787 function _end_diff() {
1788 $val = ob_get_contents();
1793 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1795 $xbeg .= "," . ($xbeg +
$xlen - 1);
1797 $ybeg .= "," . ($ybeg +
$ylen - 1);
1799 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1802 function _start_block($header) {
1803 echo $header . "\n";
1806 function _end_block() {
1809 function _lines($lines, $prefix = ' ') {
1810 foreach ($lines as $line)
1811 echo "$prefix $line\n";
1814 function _context($lines) {
1815 $this->_lines($lines);
1818 function _added($lines) {
1819 $this->_lines($lines, '>');
1821 function _deleted($lines) {
1822 $this->_lines($lines, '<');
1825 function _changed($orig, $closing) {
1826 $this->_deleted($orig);
1828 $this->_added($closing);
1833 * A formatter that outputs unified diffs
1834 * @ingroup DifferenceEngine
1837 class UnifiedDiffFormatter
extends DiffFormatter
{
1838 var $leading_context_lines = 2;
1839 var $trailing_context_lines = 2;
1841 function _added($lines) {
1842 $this->_lines($lines, '+');
1844 function _deleted($lines) {
1845 $this->_lines($lines, '-');
1847 function _changed($orig, $closing) {
1848 $this->_deleted($orig);
1849 $this->_added($closing);
1851 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1852 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1857 * A pseudo-formatter that just passes along the Diff::$edits array
1858 * @ingroup DifferenceEngine
1860 class ArrayDiffFormatter
extends DiffFormatter
{
1861 function format($diff) {
1865 foreach($diff->edits
as $edit)
1866 switch($edit->type
) {
1868 foreach($edit->closing
as $l) {
1872 'newline' => $newline++
1877 foreach($edit->orig
as $l) {
1879 'action' => 'delete',
1881 'oldline' => $oldline++
,
1886 foreach($edit->orig
as $i => $l) {
1888 'action' => 'change',
1890 'new' => @$edit->closing
[$i],
1891 'oldline' => $oldline++
,
1892 'newline' => $newline++
,
1897 $oldline +
= count($edit->orig
);
1898 $newline +
= count($edit->orig
);
1905 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1909 define('NBSP', ' '); // iso-8859-x non-breaking space.
1914 * @ingroup DifferenceEngine
1916 class _HWLDF_WordAccumulator
{
1917 function _HWLDF_WordAccumulator () {
1918 $this->_lines
= array();
1924 function _flushGroup ($new_tag) {
1925 if ($this->_group
!== '') {
1926 if ($this->_tag
== 'ins')
1927 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1928 htmlspecialchars ( $this->_group
) . '</ins>';
1929 elseif ($this->_tag
== 'del')
1930 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1931 htmlspecialchars ( $this->_group
) . '</del>';
1933 $this->_line
.= htmlspecialchars ( $this->_group
);
1936 $this->_tag
= $new_tag;
1939 function _flushLine ($new_tag) {
1940 $this->_flushGroup($new_tag);
1941 if ($this->_line
!= '')
1942 array_push ( $this->_lines
, $this->_line
);
1944 # make empty lines visible by inserting an NBSP
1945 array_push ( $this->_lines
, NBSP
);
1949 function addWords ($words, $tag = '') {
1950 if ($tag != $this->_tag
)
1951 $this->_flushGroup($tag);
1953 foreach ($words as $word) {
1954 // new-line should only come as first char of word.
1957 if ($word[0] == "\n") {
1958 $this->_flushLine($tag);
1959 $word = substr($word, 1);
1961 assert(!strstr($word, "\n"));
1962 $this->_group
.= $word;
1966 function getLines() {
1967 $this->_flushLine('~done');
1968 return $this->_lines
;
1975 * @ingroup DifferenceEngine
1977 class WordLevelDiff
extends MappedDiff
{
1978 const MAX_LINE_LENGTH
= 10000;
1980 function WordLevelDiff ($orig_lines, $closing_lines) {
1981 wfProfileIn( __METHOD__
);
1983 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1984 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1986 $this->MappedDiff($orig_words, $closing_words,
1987 $orig_stripped, $closing_stripped);
1988 wfProfileOut( __METHOD__
);
1991 function _split($lines) {
1992 wfProfileIn( __METHOD__
);
1995 $stripped = array();
1997 foreach ( $lines as $line ) {
1998 # If the line is too long, just pretend the entire line is one big word
1999 # This prevents resource exhaustion problems
2006 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
2008 $stripped[] = $line;
2011 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
2014 $words = array_merge( $words, $m[0] );
2015 $stripped = array_merge( $stripped, $m[1] );
2019 wfProfileOut( __METHOD__
);
2020 return array($words, $stripped);
2024 wfProfileIn( __METHOD__
);
2025 $orig = new _HWLDF_WordAccumulator
;
2027 foreach ($this->edits
as $edit) {
2028 if ($edit->type
== 'copy')
2029 $orig->addWords($edit->orig
);
2030 elseif ($edit->orig
)
2031 $orig->addWords($edit->orig
, 'del');
2033 $lines = $orig->getLines();
2034 wfProfileOut( __METHOD__
);
2038 function closing () {
2039 wfProfileIn( __METHOD__
);
2040 $closing = new _HWLDF_WordAccumulator
;
2042 foreach ($this->edits
as $edit) {
2043 if ($edit->type
== 'copy')
2044 $closing->addWords($edit->closing
);
2045 elseif ($edit->closing
)
2046 $closing->addWords($edit->closing
, 'ins');
2048 $lines = $closing->getLines();
2049 wfProfileOut( __METHOD__
);
2055 * Wikipedia Table style diff formatter.
2058 * @ingroup DifferenceEngine
2060 class TableDiffFormatter
extends DiffFormatter
{
2061 function TableDiffFormatter() {
2062 $this->leading_context_lines
= 2;
2063 $this->trailing_context_lines
= 2;
2066 public static function escapeWhiteSpace( $msg ) {
2067 $msg = preg_replace( '/^ /m', ' ', $msg );
2068 $msg = preg_replace( '/ $/m', ' ', $msg );
2069 $msg = preg_replace( '/ /', ' ', $msg );
2073 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2074 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2075 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2079 function _start_block( $header ) {
2083 function _end_block() {
2086 function _lines( $lines, $prefix=' ', $color='white' ) {
2089 # HTML-escape parameter before calling this
2090 function addedLine( $line ) {
2091 return $this->wrapLine( '+', 'diff-addedline', $line );
2094 # HTML-escape parameter before calling this
2095 function deletedLine( $line ) {
2096 return $this->wrapLine( '-', 'diff-deletedline', $line );
2099 # HTML-escape parameter before calling this
2100 function contextLine( $line ) {
2101 return $this->wrapLine( ' ', 'diff-context', $line );
2104 private function wrapLine( $marker, $class, $line ) {
2105 if( $line !== '' ) {
2106 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2107 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2109 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2112 function emptyLine() {
2113 return '<td colspan="2"> </td>';
2116 function _added( $lines ) {
2117 foreach ($lines as $line) {
2118 echo '<tr>' . $this->emptyLine() .
2119 $this->addedLine( '<ins class="diffchange">' .
2120 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2124 function _deleted($lines) {
2125 foreach ($lines as $line) {
2126 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2127 htmlspecialchars ( $line ) . '</del>' ) .
2128 $this->emptyLine() . "</tr>\n";
2132 function _context( $lines ) {
2133 foreach ($lines as $line) {
2135 $this->contextLine( htmlspecialchars ( $line ) ) .
2136 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2140 function _changed( $orig, $closing ) {
2141 wfProfileIn( __METHOD__
);
2143 $diff = new WordLevelDiff( $orig, $closing );
2144 $del = $diff->orig();
2145 $add = $diff->closing();
2147 # Notice that WordLevelDiff returns HTML-escaped output.
2148 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2150 while ( $line = array_shift( $del ) ) {
2151 $aline = array_shift( $add );
2152 echo '<tr>' . $this->deletedLine( $line ) .
2153 $this->addedLine( $aline ) . "</tr>\n";
2155 foreach ($add as $line) { # If any leftovers
2156 echo '<tr>' . $this->emptyLine() .
2157 $this->addedLine( $line ) . "</tr>\n";
2159 wfProfileOut( __METHOD__
);