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?
32 protected $unhide = false;
37 * @param $titleObj Title object that the diff is associated with
38 * @param $old Integer: old ID we want to show and diff with.
39 * @param $new String: either 'prev' or 'next'.
40 * @param $rcid Integer: ??? FIXME (default 0)
41 * @param $refreshCache boolean If set, refreshes the diff cache
42 * @param $htmldiff boolean If set, output using HTMLDiff instead of raw wikicode diff
43 * @param $unhide boolean If set, allow viewing deleted revs
45 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false , $htmldiff = false, $unhide = false ) {
46 $this->mTitle
= $titleObj;
47 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
49 if ( 'prev' === $new ) {
50 # Show diff between revision $old and the previous one.
51 # Get previous one from DB.
52 $this->mNewid
= intval($old);
53 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
54 } elseif ( 'next' === $new ) {
55 # Show diff between revision $old and the previous one.
56 # Get previous 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 showDiffPage( $diffOnly = false ) {
81 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
82 wfProfileIn( __METHOD__
);
85 # If external diffs are enabled both globally and for the user,
86 # we'll use the application/x-external-editor interface to call
87 # an external diff tool like kompare, kdiff3, etc.
88 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
89 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
91 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
92 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
93 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
94 $special=$wgLang->getNsText(NS_SPECIAL
);
99 Script={$wgServer}{$wgScript}
100 Special namespace={$special}
114 $wgOut->setArticleFlag( false );
115 if ( !$this->loadRevisionData() ) {
116 $t = $this->mTitle
->getPrefixedText();
117 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
118 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
119 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
120 wfProfileOut( __METHOD__
);
124 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
126 if ( $this->mNewRev
->isCurrent() ) {
127 $wgOut->setArticleFlag( true );
130 # mOldid is false if the difference engine is called with a "vague" query for
131 # a diff between a version V and its previous version V' AND the version V
132 # is the first version of that article. In that case, V' does not exist.
133 if ( $this->mOldid
=== false ) {
134 $this->showFirstRevision();
135 $this->renderNewRevision(); // should we respect $diffOnly here or not?
136 wfProfileOut( __METHOD__
);
140 $wgOut->suppressQuickbar();
142 $oldTitle = $this->mOldPage
->getPrefixedText();
143 $newTitle = $this->mNewPage
->getPrefixedText();
144 if( $oldTitle == $newTitle ) {
145 $wgOut->setPageTitle( $newTitle );
147 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
149 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
150 $wgOut->setRobotPolicy( 'noindex,nofollow' );
152 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
153 $wgOut->loginToUse();
156 wfProfileOut( __METHOD__
);
160 $sk = $wgUser->getSkin();
162 // Check if page is editable
163 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
164 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
165 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
170 // Prepare a change patrol link, if applicable
171 if( $wgUseRCPatrol && $this->mTitle
->userCan('patrol') ) {
172 // If we've been given an explicit change identifier, use it; saves time
173 if( $this->mRcidMarkPatrolled
) {
174 $rcid = $this->mRcidMarkPatrolled
;
175 $rc = RecentChange
::newFromId( $rcid );
176 // Already patrolled?
177 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ?
$rcid : 0;
179 // Look for an unpatrolled change corresponding to this diff
180 $db = wfGetDB( DB_SLAVE
);
181 $change = RecentChange
::newFromConds(
183 // Add redundant user,timestamp condition so we can use the existing index
184 'rc_user_text' => $this->mNewRev
->getRawUserText(),
185 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
186 'rc_this_oldid' => $this->mNewid
,
187 'rc_last_oldid' => $this->mOldid
,
192 if( $change instanceof RecentChange
) {
193 $rcid = $change->mAttribs
['rc_id'];
194 $this->mRcidMarkPatrolled
= $rcid;
202 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj( $this->mTitle
,
203 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$rcid}" ) . ']</span>';
212 # Carry over 'diffonly' param via navigation links
213 if( $diffOnly != $wgUser->getBoolOption('diffonly') ) {
214 $diffOnlyArg = '&diffonly='.$diffOnly;
216 $htmldiffarg = $this->htmlDiffArgument();
217 # Make "previous revision link"
218 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
219 "diff=prev&oldid={$this->mOldid}{$htmldiffarg}{$diffOnlyArg}", '', '', 'id="differences-prevlink"' );
220 # Make "next revision link"
221 if( $this->mNewRev
->isCurrent() ) {
222 $nextlink = ' ';
224 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
225 "diff=next&oldid={$this->mNewid}{$htmldiffarg}{$diffOnlyArg}", '', '', 'id="differences-nextlink"' );
231 if( $this->mOldRev
->isMinor() ) {
232 $oldminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
234 if( $this->mNewRev
->isMinor() ) {
235 $newminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
238 $rdel = ''; $ldel = '';
239 if( $wgUser->isAllowed( 'deleterevision' ) ) {
240 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
241 // If revision was hidden from sysops
242 $ldel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
244 $query = array( 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
245 'oldid' => $this->mOldRev
->getId()
247 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
249 $ldel = " $ldel ";
250 // We don't currently handle well changing the top revision's settings
251 if( $this->mNewRev
->isCurrent() ) {
252 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
253 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
254 // If revision was hidden from sysops
255 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
257 $query = array( 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
258 'oldid' => $this->mNewRev
->getId()
260 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
262 $rdel = " $rdel ";
265 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
266 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . "</div>" .
267 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
).$ldel."</div>" .
268 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
269 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
270 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) . " $rollback</div>" .
271 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
).$rdel."</div>" .
272 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
274 # Output the diff if allowed
275 $allowed = $this->mOldRev
->userCan(Revision
::DELETED_TEXT
) && $this->mNewRev
->userCan(Revision
::DELETED_TEXT
);
276 $deleted = $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ||
$this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
);
277 if( $deleted && (!$this->unhide ||
!$allowed) ) {
278 $this->showDiffStyle();
279 $multi = $this->getMultiNotice();
280 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
281 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
282 array( 'rev-deleted-no-diff' ) );
283 } else if( $wgEnableHtmlDiff && $this->htmldiff
) {
284 $multi = $this->getMultiNotice();
285 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
286 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
287 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
288 $this->renderHtmlDiff();
290 if( $wgEnableHtmlDiff ) {
291 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
292 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
294 $this->showDiff( $oldHeader, $newHeader );
296 $this->renderNewRevision();
299 wfProfileOut( __METHOD__
);
303 * Show the new revision of the page.
305 function renderNewRevision() {
306 global $wgOut, $wgUser;
307 wfProfileIn( __METHOD__
);
309 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
310 # Add deleted rev tag if needed
311 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
312 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
313 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
314 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
317 if( !$this->mNewRev
->isCurrent() ) {
318 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
321 $this->loadNewText();
322 if( is_object( $this->mNewRev
) ) {
323 $wgOut->setRevisionId( $this->mNewRev
->getId() );
326 if( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
327 // Stolen from Article::view --AG 2007-10-11
328 // Give hooks a chance to customise the output
329 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
330 // Wrap the whole lot in a <pre> and don't parse
332 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
333 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
334 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
335 $wgOut->addHTML( "\n</pre>\n" );
338 $wgOut->addWikiTextTidy( $this->mNewtext
);
341 if( is_object( $this->mNewRev
) && !$this->mNewRev
->isCurrent() ) {
342 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
344 # Add redundant patrol link on bottom...
345 if( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan('patrol') ) {
346 $sk = $wgUser->getSkin();
348 "<div class='patrollink'>[" . $sk->makeKnownLinkObj( $this->mTitle
,
349 wfMsgHtml( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) .
354 wfProfileOut( __METHOD__
);
358 function renderHtmlDiff() {
359 global $wgOut, $wgTitle, $wgParser, $wgDebugComments;
360 wfProfileIn( __METHOD__
);
362 $this->showDiffStyle();
364 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
365 #add deleted rev tag if needed
366 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
367 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
368 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
369 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
372 if( !$this->mNewRev
->isCurrent() ) {
373 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
379 if( is_object( $this->mOldRev
) ) {
380 $wgOut->setRevisionId( $this->mOldRev
->getId() );
383 $popts = $wgOut->parserOptions();
384 $oldTidy = $popts->setTidy( true );
385 $popts->setEditSection( false );
387 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
388 $popts->setTidy( $oldTidy );
391 //$wgOut->addParserOutputNoText( $parserOutput );
392 $oldHtml = $parserOutput->getText();
393 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
396 if( is_object( $this->mNewRev
) ) {
397 $wgOut->setRevisionId( $this->mNewRev
->getId() );
400 $popts = $wgOut->parserOptions();
401 $oldTidy = $popts->setTidy( true );
403 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
404 $popts->setTidy( $oldTidy );
406 $wgOut->addParserOutputNoText( $parserOutput );
407 $newHtml = $parserOutput->getText();
408 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
410 unset($parserOutput, $popts);
412 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
413 $differ->htmlDiff($oldHtml, $newHtml);
414 if ( $wgDebugComments ) {
415 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
418 wfProfileOut( __METHOD__
);
422 * Show the first revision of an article. Uses normal diff headers in
423 * contrast to normal "old revision" display style.
425 function showFirstRevision() {
426 global $wgOut, $wgUser;
427 wfProfileIn( __METHOD__
);
429 # Get article text from the DB
431 if ( ! $this->loadNewText() ) {
432 $t = $this->mTitle
->getPrefixedText();
433 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
434 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
435 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
436 wfProfileOut( __METHOD__
);
439 if ( $this->mNewRev
->isCurrent() ) {
440 $wgOut->setArticleFlag( true );
443 # Check if user is allowed to look at this page. If not, bail out.
445 if ( !$this->mTitle
->userCanRead() ) {
446 $wgOut->loginToUse();
448 wfProfileOut( __METHOD__
);
449 throw new MWException("Permission Error: you do not have access to view this page");
452 # Prepare the header box
454 $sk = $wgUser->getSkin();
456 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
460 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
461 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
463 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
464 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
466 $wgOut->addHTML( $header );
468 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
469 $wgOut->setRobotPolicy( 'noindex,nofollow' );
471 wfProfileOut( __METHOD__
);
474 function htmlDiffArgument(){
475 global $wgEnableHtmlDiff;
476 if($wgEnableHtmlDiff){
478 return '&htmldiff=1';
480 return '&htmldiff=0';
488 * Get the diff text, send it to $wgOut
489 * Returns false if the diff could not be generated, otherwise returns true
491 function showDiff( $otitle, $ntitle ) {
493 $diff = $this->getDiff( $otitle, $ntitle );
494 if ( $diff === false ) {
495 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
498 $this->showDiffStyle();
499 $wgOut->addHTML( $diff );
505 * Add style sheets and supporting JS for diff display.
507 function showDiffStyle() {
508 global $wgStylePath, $wgStyleVersion, $wgOut;
509 $wgOut->addStyle( 'common/diff.css' );
511 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
512 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
516 * Get complete diff table, including header
518 * @param Title $otitle Old title
519 * @param Title $ntitle New title
522 function getDiff( $otitle, $ntitle ) {
523 $body = $this->getDiffBody();
524 if ( $body === false ) {
527 $multi = $this->getMultiNotice();
528 return $this->addHeader( $body, $otitle, $ntitle, $multi );
533 * Get the diff table body, without header
537 function getDiffBody() {
539 wfProfileIn( __METHOD__
);
540 // Check if the diff should be hidden from this user
541 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
543 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
548 if ( $this->mOldid
&& $this->mNewid
) {
549 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
551 if ( !$this->mRefreshCache
) {
552 $difftext = $wgMemc->get( $key );
554 wfIncrStats( 'diff_cache_hit' );
555 $difftext = $this->localiseLineNumbers( $difftext );
556 $difftext .= "\n<!-- diff cache key $key -->\n";
557 wfProfileOut( __METHOD__
);
560 } // don't try to load but save the result
563 // Loadtext is permission safe, this just clears out the diff
564 if ( !$this->loadText() ) {
565 wfProfileOut( __METHOD__
);
569 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
571 // Save to cache for 7 days
572 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
573 wfIncrStats( 'diff_uncacheable' );
574 } else if ( $key !== false && $difftext !== false ) {
575 wfIncrStats( 'diff_cache_miss' );
576 $wgMemc->set( $key, $difftext, 7*86400 );
578 wfIncrStats( 'diff_uncacheable' );
580 // Replace line numbers with the text in the user's language
581 if ( $difftext !== false ) {
582 $difftext = $this->localiseLineNumbers( $difftext );
584 wfProfileOut( __METHOD__
);
589 * Generate a diff, no caching
590 * $otext and $ntext must be already segmented
592 function generateDiffBody( $otext, $ntext ) {
593 global $wgExternalDiffEngine, $wgContLang;
595 $otext = str_replace( "\r\n", "\n", $otext );
596 $ntext = str_replace( "\r\n", "\n", $ntext );
598 if ( $wgExternalDiffEngine == 'wikidiff' ) {
599 # For historical reasons, external diff engine expects
600 # input text to be HTML-escaped already
601 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
602 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
603 if( !function_exists( 'wikidiff_do_diff' ) ) {
604 dl('php_wikidiff.so');
606 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
607 $this->debug( 'wikidiff1' );
610 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
611 # Better external diff engine, the 2 may some day be dropped
612 # This one does the escaping and segmenting itself
613 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
614 wfProfileIn( __METHOD__
. "-dl" );
615 @dl
('php_wikidiff2.so');
616 wfProfileOut( __METHOD__
. "-dl" );
618 if ( function_exists( 'wikidiff2_do_diff' ) ) {
619 wfProfileIn( 'wikidiff2_do_diff' );
620 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
621 $text .= $this->debug( 'wikidiff2' );
622 wfProfileOut( 'wikidiff2_do_diff' );
626 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
628 global $wgTmpDirectory;
629 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
630 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
632 $tempFile1 = fopen( $tempName1, "w" );
634 wfProfileOut( __METHOD__
);
637 $tempFile2 = fopen( $tempName2, "w" );
639 wfProfileOut( __METHOD__
);
642 fwrite( $tempFile1, $otext );
643 fwrite( $tempFile2, $ntext );
644 fclose( $tempFile1 );
645 fclose( $tempFile2 );
646 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
647 wfProfileIn( __METHOD__
. "-shellexec" );
648 $difftext = wfShellExec( $cmd );
649 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
650 wfProfileOut( __METHOD__
. "-shellexec" );
651 unlink( $tempName1 );
652 unlink( $tempName2 );
657 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
658 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
659 $diffs = new Diff( $ota, $nta );
660 $formatter = new TableDiffFormatter();
661 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
666 * Generate a debug comment indicating diff generating time,
667 * server node, and generator backend.
669 protected function debug( $generator="internal" ) {
670 global $wgShowHostnames;
671 $data = array( $generator );
672 if( $wgShowHostnames ) {
673 $data[] = wfHostname();
675 $data[] = wfTimestamp( TS_DB
);
676 return "<!-- diff generator: " .
685 * Replace line numbers with the text in the user's language
687 function localiseLineNumbers( $text ) {
688 return preg_replace_callback( '/<!--LINE (\d+)-->/',
689 array( &$this, 'localiseLineNumbersCb' ), $text );
692 function localiseLineNumbersCb( $matches ) {
694 return wfMsgExt( 'lineno', array( 'parseinline' ), $wgLang->formatNum( $matches[1] ) );
699 * If there are revisions between the ones being compared, return a note saying so.
701 function getMultiNotice() {
702 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
705 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
706 // Comparing two different pages? Count would be meaningless.
710 $oldid = $this->mOldRev
->getId();
711 $newid = $this->mNewRev
->getId();
712 if ( $oldid > $newid ) {
713 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
716 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
720 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
725 * Add the header to a diff body
727 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
730 <col class='diff-marker' />
731 <col class='diff-content' />
732 <col class='diff-marker' />
733 <col class='diff-content' />
735 <td colspan='2' class='diff-otitle'>{$otitle}</td>
736 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
741 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
743 return $header . $diff . "</table>";
747 * Use specified text instead of loading from the database
749 function setText( $oldText, $newText ) {
750 $this->mOldtext
= $oldText;
751 $this->mNewtext
= $newText;
752 $this->mTextLoaded
= 2;
756 * Load revision metadata for the specified articles. If newid is 0, then compare
757 * the old article in oldid to the current article; if oldid is 0, then
758 * compare the current article to the immediately previous one (ignoring the
761 * If oldid is false, leave the corresponding revision object set
762 * to false. This is impossible via ordinary user input, and is provided for
765 function loadRevisionData() {
766 global $wgLang, $wgUser;
767 if ( $this->mRevisionsLoaded
) {
770 // Whether it succeeds or fails, we don't want to try again
771 $this->mRevisionsLoaded
= true;
774 // Load the new revision object
775 $this->mNewRev
= $this->mNewid
776 ? Revision
::newFromId( $this->mNewid
)
777 : Revision
::newFromTitle( $this->mTitle
);
778 if( !$this->mNewRev
instanceof Revision
)
781 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
782 $this->mNewid
= $this->mNewRev
->getId();
784 // Check if page is editable
785 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
787 // Set assorted variables
788 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
789 $this->mNewPage
= $this->mNewRev
->getTitle();
790 if( $this->mNewRev
->isCurrent() ) {
791 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
792 $this->mPagetitle
= wfMsgHTML( 'currentrev-asof', $timestamp );
793 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
795 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
796 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
799 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
800 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
801 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
803 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
804 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
806 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
807 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
808 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
809 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
812 // Load the old revision object
813 $this->mOldRev
= false;
814 if( $this->mOldid
) {
815 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
816 } elseif ( $this->mOldid
=== 0 ) {
817 $rev = $this->mNewRev
->getPrevious();
819 $this->mOldid
= $rev->getId();
820 $this->mOldRev
= $rev;
822 // No previous revision; mark to show as first-version only.
823 $this->mOldid
= false;
824 $this->mOldRev
= false;
826 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
828 if( is_null( $this->mOldRev
) ) {
832 if ( $this->mOldRev
) {
833 $this->mOldPage
= $this->mOldRev
->getTitle();
835 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
836 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
837 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
838 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
840 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
841 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
842 // Add an "undo" link
843 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
844 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
845 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
846 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
847 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
850 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
851 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
852 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
853 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
861 * Load the text of the revisions, as well as revision data.
863 function loadText() {
864 if ( $this->mTextLoaded
== 2 ) {
867 // Whether it succeeds or fails, we don't want to try again
868 $this->mTextLoaded
= 2;
871 if ( !$this->loadRevisionData() ) {
874 if ( $this->mOldRev
) {
875 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
876 if ( $this->mOldtext
=== false ) {
880 if ( $this->mNewRev
) {
881 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
882 if ( $this->mNewtext
=== false ) {
890 * Load the text of the new revision, not the old one
892 function loadNewText() {
893 if ( $this->mTextLoaded
>= 1 ) {
896 $this->mTextLoaded
= 1;
898 if ( !$this->loadRevisionData() ) {
901 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
908 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
910 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
911 // You may copy this code freely under the conditions of the GPL.
914 define('USE_ASSERTS', function_exists('assert'));
919 * @ingroup DifferenceEngine
927 trigger_error('pure virtual', E_USER_ERROR
);
931 return $this->orig ?
sizeof($this->orig
) : 0;
934 function nclosing() {
935 return $this->closing ?
sizeof($this->closing
) : 0;
942 * @ingroup DifferenceEngine
944 class _DiffOp_Copy
extends _DiffOp
{
947 function _DiffOp_Copy ($orig, $closing = false) {
948 if (!is_array($closing))
951 $this->closing
= $closing;
955 return new _DiffOp_Copy($this->closing
, $this->orig
);
962 * @ingroup DifferenceEngine
964 class _DiffOp_Delete
extends _DiffOp
{
965 var $type = 'delete';
967 function _DiffOp_Delete ($lines) {
968 $this->orig
= $lines;
969 $this->closing
= false;
973 return new _DiffOp_Add($this->orig
);
980 * @ingroup DifferenceEngine
982 class _DiffOp_Add
extends _DiffOp
{
985 function _DiffOp_Add ($lines) {
986 $this->closing
= $lines;
991 return new _DiffOp_Delete($this->closing
);
998 * @ingroup DifferenceEngine
1000 class _DiffOp_Change
extends _DiffOp
{
1001 var $type = 'change';
1003 function _DiffOp_Change ($orig, $closing) {
1004 $this->orig
= $orig;
1005 $this->closing
= $closing;
1008 function reverse() {
1009 return new _DiffOp_Change($this->closing
, $this->orig
);
1014 * Class used internally by Diff to actually compute the diffs.
1016 * The algorithm used here is mostly lifted from the perl module
1017 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
1018 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
1020 * More ideas are taken from:
1021 * http://www.ics.uci.edu/~eppstein/161/960229.html
1023 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1024 * diffutils-2.7, which can be found at:
1025 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1027 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1030 * Line length limits for robustness added by Tim Starling, 2005-08-31
1031 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1033 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1035 * @ingroup DifferenceEngine
1039 const MAX_XREF_LENGTH
= 10000;
1041 function diff ($from_lines, $to_lines){
1042 wfProfileIn( __METHOD__
);
1044 // Diff and store locally
1045 $this->diff_local($from_lines, $to_lines);
1047 // Merge edits when possible
1048 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1049 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1051 // Compute the edit operations.
1052 $n_from = sizeof($from_lines);
1053 $n_to = sizeof($to_lines);
1057 while ($xi < $n_from ||
$yi < $n_to) {
1058 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1059 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1061 // Skip matching "snake".
1063 while ( $xi < $n_from && $yi < $n_to
1064 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1065 $copy[] = $from_lines[$xi++
];
1069 $edits[] = new _DiffOp_Copy($copy);
1071 // Find deletes & adds.
1073 while ($xi < $n_from && $this->xchanged
[$xi])
1074 $delete[] = $from_lines[$xi++
];
1077 while ($yi < $n_to && $this->ychanged
[$yi])
1078 $add[] = $to_lines[$yi++
];
1080 if ($delete && $add)
1081 $edits[] = new _DiffOp_Change($delete, $add);
1083 $edits[] = new _DiffOp_Delete($delete);
1085 $edits[] = new _DiffOp_Add($add);
1087 wfProfileOut( __METHOD__
);
1091 function diff_local ($from_lines, $to_lines) {
1092 global $wgExternalDiffEngine;
1093 wfProfileIn( __METHOD__
);
1095 if($wgExternalDiffEngine == 'wikidiff3'){
1097 $wikidiff3 = new WikiDiff3();
1098 $wikidiff3->diff($from_lines, $to_lines);
1099 $this->xchanged
= $wikidiff3->removed
;
1100 $this->ychanged
= $wikidiff3->added
;
1104 $n_from = sizeof($from_lines);
1105 $n_to = sizeof($to_lines);
1106 $this->xchanged
= $this->ychanged
= array();
1107 $this->xv
= $this->yv
= array();
1108 $this->xind
= $this->yind
= array();
1110 unset($this->in_seq
);
1113 // Skip leading common lines.
1114 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1115 if ($from_lines[$skip] !== $to_lines[$skip])
1117 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1119 // Skip trailing common lines.
1120 $xi = $n_from; $yi = $n_to;
1121 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1122 if ($from_lines[$xi] !== $to_lines[$yi])
1124 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1127 // Ignore lines which do not exist in both files.
1128 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1129 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1132 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1133 $line = $to_lines[$yi];
1134 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1136 $yhash[$this->_line_hash($line)] = 1;
1137 $this->yv
[] = $line;
1138 $this->yind
[] = $yi;
1140 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1141 $line = $from_lines[$xi];
1142 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1144 $this->xv
[] = $line;
1145 $this->xind
[] = $xi;
1149 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1151 wfProfileOut( __METHOD__
);
1155 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1157 function _line_hash( $line ) {
1158 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1159 return md5( $line );
1165 /* Divide the Largest Common Subsequence (LCS) of the sequences
1166 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1169 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1170 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1171 * sub sequences. The first sub-sequence is contained in [X0, X1),
1172 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1173 * that (X0, Y0) == (XOFF, YOFF) and
1174 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1176 * This function assumes that the first lines of the specified portions
1177 * of the two files do not match, and likewise that the last lines do not
1178 * match. The caller must trim matching lines from the beginning and end
1179 * of the portions it is going to specify.
1181 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1184 if ($xlim - $xoff > $ylim - $yoff) {
1185 // Things seems faster (I'm not sure I understand why)
1186 // when the shortest sequence in X.
1188 list ($xoff, $xlim, $yoff, $ylim)
1189 = array( $yoff, $ylim, $xoff, $xlim);
1193 for ($i = $ylim - 1; $i >= $yoff; $i--)
1194 $ymatches[$this->xv
[$i]][] = $i;
1196 for ($i = $ylim - 1; $i >= $yoff; $i--)
1197 $ymatches[$this->yv
[$i]][] = $i;
1200 $this->seq
[0]= $yoff - 1;
1201 $this->in_seq
= array();
1202 $ymids[0] = array();
1204 $numer = $xlim - $xoff +
$nchunks - 1;
1206 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1208 for ($i = 0; $i <= $this->lcs
; $i++
)
1209 $ymids[$i][$chunk-1] = $this->seq
[$i];
1211 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1212 for ( ; $x < $x1; $x++
) {
1213 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1214 if (empty($ymatches[$line]))
1216 $matches = $ymatches[$line];
1218 while (list ($junk, $y) = each($matches))
1219 if (empty($this->in_seq
[$y])) {
1220 $k = $this->_lcs_pos($y);
1221 USE_ASSERTS
&& assert($k > 0);
1222 $ymids[$k] = $ymids[$k-1];
1225 while (list ( /* $junk */, $y) = each($matches)) {
1226 if ($y > $this->seq
[$k-1]) {
1227 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1228 // Optimization: this is a common case:
1229 // next match is just replacing previous match.
1230 $this->in_seq
[$this->seq
[$k]] = false;
1231 $this->seq
[$k] = $y;
1232 $this->in_seq
[$y] = 1;
1233 } else if (empty($this->in_seq
[$y])) {
1234 $k = $this->_lcs_pos($y);
1235 USE_ASSERTS
&& assert($k > 0);
1236 $ymids[$k] = $ymids[$k-1];
1242 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1243 $ymid = $ymids[$this->lcs
];
1244 for ($n = 0; $n < $nchunks - 1; $n++
) {
1245 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1246 $y1 = $ymid[$n] +
1;
1247 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1249 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1251 return array($this->lcs
, $seps);
1254 function _lcs_pos ($ypos) {
1256 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1257 $this->seq
[++
$this->lcs
] = $ypos;
1258 $this->in_seq
[$ypos] = 1;
1263 while ($beg < $end) {
1264 $mid = (int)(($beg +
$end) / 2);
1265 if ( $ypos > $this->seq
[$mid] )
1271 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1273 $this->in_seq
[$this->seq
[$end]] = false;
1274 $this->seq
[$end] = $ypos;
1275 $this->in_seq
[$ypos] = 1;
1279 /* Find LCS of two sequences.
1281 * The results are recorded in the vectors $this->{x,y}changed[], by
1282 * storing a 1 in the element for each line that is an insertion
1283 * or deletion (ie. is not in the LCS).
1285 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1287 * Note that XLIM, YLIM are exclusive bounds.
1288 * All line numbers are origin-0 and discarded lines are not counted.
1290 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1291 // Slide down the bottom initial diagonal.
1292 while ($xoff < $xlim && $yoff < $ylim
1293 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1298 // Slide up the top initial diagonal.
1299 while ($xlim > $xoff && $ylim > $yoff
1300 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1305 if ($xoff == $xlim ||
$yoff == $ylim)
1308 // This is ad hoc but seems to work well.
1309 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1310 //$nchunks = max(2,min(8,(int)$nchunks));
1311 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1313 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1317 // X and Y sequences have no common subsequence:
1318 // mark all changed.
1319 while ($yoff < $ylim)
1320 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1321 while ($xoff < $xlim)
1322 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1324 // Use the partitions to split this problem into subproblems.
1327 while ($pt2 = next($seps)) {
1328 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1334 /* Adjust inserts/deletes of identical lines to join changes
1335 * as much as possible.
1337 * We do something when a run of changed lines include a
1338 * line at one end and has an excluded, identical line at the other.
1339 * We are free to choose which identical line is included.
1340 * `compareseq' usually chooses the one at the beginning,
1341 * but usually it is cleaner to consider the following identical line
1342 * to be the "change".
1344 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1346 function _shift_boundaries ($lines, &$changed, $other_changed) {
1347 wfProfileIn( __METHOD__
);
1351 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1352 $len = sizeof($lines);
1353 $other_len = sizeof($other_changed);
1357 * Scan forwards to find beginning of another run of changes.
1358 * Also keep track of the corresponding point in the other file.
1360 * Throughout this code, $i and $j are adjusted together so that
1361 * the first $i elements of $changed and the first $j elements
1362 * of $other_changed both contain the same number of zeros
1363 * (unchanged lines).
1364 * Furthermore, $j is always kept so that $j == $other_len or
1365 * $other_changed[$j] == false.
1367 while ($j < $other_len && $other_changed[$j])
1370 while ($i < $len && ! $changed[$i]) {
1371 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1373 while ($j < $other_len && $other_changed[$j])
1382 // Find the end of this run of changes.
1383 while (++
$i < $len && $changed[$i])
1388 * Record the length of this run of changes, so that
1389 * we can later determine whether the run has grown.
1391 $runlength = $i - $start;
1394 * Move the changed region back, so long as the
1395 * previous unchanged line matches the last changed one.
1396 * This merges with previous changed regions.
1398 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1399 $changed[--$start] = 1;
1400 $changed[--$i] = false;
1401 while ($start > 0 && $changed[$start - 1])
1403 USE_ASSERTS
&& assert('$j > 0');
1404 while ($other_changed[--$j])
1406 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1410 * Set CORRESPONDING to the end of the changed run, at the last
1411 * point where it corresponds to a changed run in the other file.
1412 * CORRESPONDING == LEN means no such point has been found.
1414 $corresponding = $j < $other_len ?
$i : $len;
1417 * Move the changed region forward, so long as the
1418 * first changed line matches the following unchanged one.
1419 * This merges with following changed regions.
1420 * Do this second, so that if there are no merges,
1421 * the changed region is moved forward as far as possible.
1423 while ($i < $len && $lines[$start] == $lines[$i]) {
1424 $changed[$start++
] = false;
1426 while ($i < $len && $changed[$i])
1429 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1431 if ($j < $other_len && $other_changed[$j]) {
1432 $corresponding = $i;
1433 while ($j < $other_len && $other_changed[$j])
1437 } while ($runlength != $i - $start);
1440 * If possible, move the fully-merged run of changes
1441 * back to a corresponding run in the other file.
1443 while ($corresponding < $i) {
1444 $changed[--$start] = 1;
1446 USE_ASSERTS
&& assert('$j > 0');
1447 while ($other_changed[--$j])
1449 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1452 wfProfileOut( __METHOD__
);
1457 * Class representing a 'diff' between two sequences of strings.
1460 * @ingroup DifferenceEngine
1468 * Computes diff between sequences of strings.
1470 * @param $from_lines array An array of strings.
1471 * (Typically these are lines from a file.)
1472 * @param $to_lines array An array of strings.
1474 function Diff($from_lines, $to_lines) {
1475 $eng = new _DiffEngine
;
1476 $this->edits
= $eng->diff($from_lines, $to_lines);
1477 //$this->_check($from_lines, $to_lines);
1481 * Compute reversed Diff.
1485 * $diff = new Diff($lines1, $lines2);
1486 * $rev = $diff->reverse();
1487 * @return object A Diff object representing the inverse of the
1490 function reverse () {
1492 $rev->edits
= array();
1493 foreach ($this->edits
as $edit) {
1494 $rev->edits
[] = $edit->reverse();
1500 * Check for empty diff.
1502 * @return bool True iff two sequences were identical.
1504 function isEmpty () {
1505 foreach ($this->edits
as $edit) {
1506 if ($edit->type
!= 'copy')
1513 * Compute the length of the Longest Common Subsequence (LCS).
1515 * This is mostly for diagnostic purposed.
1517 * @return int The length of the LCS.
1521 foreach ($this->edits
as $edit) {
1522 if ($edit->type
== 'copy')
1523 $lcs +
= sizeof($edit->orig
);
1529 * Get the original set of lines.
1531 * This reconstructs the $from_lines parameter passed to the
1534 * @return array The original sequence of strings.
1539 foreach ($this->edits
as $edit) {
1541 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1547 * Get the closing set of lines.
1549 * This reconstructs the $to_lines parameter passed to the
1552 * @return array The sequence of strings.
1554 function closing() {
1557 foreach ($this->edits
as $edit) {
1559 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1565 * Check a Diff for validity.
1567 * This is here only for debugging purposes.
1569 function _check ($from_lines, $to_lines) {
1570 wfProfileIn( __METHOD__
);
1571 if (serialize($from_lines) != serialize($this->orig()))
1572 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1573 if (serialize($to_lines) != serialize($this->closing()))
1574 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1576 $rev = $this->reverse();
1577 if (serialize($to_lines) != serialize($rev->orig()))
1578 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1579 if (serialize($from_lines) != serialize($rev->closing()))
1580 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1584 foreach ($this->edits
as $edit) {
1585 if ( $prevtype == $edit->type
)
1586 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1587 $prevtype = $edit->type
;
1590 $lcs = $this->lcs();
1591 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1592 wfProfileOut( __METHOD__
);
1597 * @todo document, bad name.
1599 * @ingroup DifferenceEngine
1601 class MappedDiff
extends Diff
1606 * Computes diff between sequences of strings.
1608 * This can be used to compute things like
1609 * case-insensitve diffs, or diffs which ignore
1610 * changes in white-space.
1612 * @param $from_lines array An array of strings.
1613 * (Typically these are lines from a file.)
1615 * @param $to_lines array An array of strings.
1617 * @param $mapped_from_lines array This array should
1618 * have the same size number of elements as $from_lines.
1619 * The elements in $mapped_from_lines and
1620 * $mapped_to_lines are what is actually compared
1621 * when computing the diff.
1623 * @param $mapped_to_lines array This array should
1624 * have the same number of elements as $to_lines.
1626 function MappedDiff($from_lines, $to_lines,
1627 $mapped_from_lines, $mapped_to_lines) {
1628 wfProfileIn( __METHOD__
);
1630 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1631 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1633 $this->Diff($mapped_from_lines, $mapped_to_lines);
1636 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1637 $orig = &$this->edits
[$i]->orig
;
1638 if (is_array($orig)) {
1639 $orig = array_slice($from_lines, $xi, sizeof($orig));
1640 $xi +
= sizeof($orig);
1643 $closing = &$this->edits
[$i]->closing
;
1644 if (is_array($closing)) {
1645 $closing = array_slice($to_lines, $yi, sizeof($closing));
1646 $yi +
= sizeof($closing);
1649 wfProfileOut( __METHOD__
);
1654 * A class to format Diffs
1656 * This class formats the diff in classic diff format.
1657 * It is intended that this class be customized via inheritance,
1658 * to obtain fancier outputs.
1661 * @ingroup DifferenceEngine
1663 class DiffFormatter
{
1665 * Number of leading context "lines" to preserve.
1667 * This should be left at zero for this class, but subclasses
1668 * may want to set this to other values.
1670 var $leading_context_lines = 0;
1673 * Number of trailing context "lines" to preserve.
1675 * This should be left at zero for this class, but subclasses
1676 * may want to set this to other values.
1678 var $trailing_context_lines = 0;
1683 * @param $diff object A Diff object.
1684 * @return string The formatted output.
1686 function format($diff) {
1687 wfProfileIn( __METHOD__
);
1693 $nlead = $this->leading_context_lines
;
1694 $ntrail = $this->trailing_context_lines
;
1696 $this->_start_diff();
1698 foreach ($diff->edits
as $edit) {
1699 if ($edit->type
== 'copy') {
1700 if (is_array($block)) {
1701 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1706 $context = array_slice($edit->orig
, 0, $ntrail);
1707 $block[] = new _DiffOp_Copy($context);
1709 $this->_block($x0, $ntrail +
$xi - $x0,
1710 $y0, $ntrail +
$yi - $y0,
1715 $context = $edit->orig
;
1718 if (! is_array($block)) {
1719 $context = array_slice($context, sizeof($context) - $nlead);
1720 $x0 = $xi - sizeof($context);
1721 $y0 = $yi - sizeof($context);
1724 $block[] = new _DiffOp_Copy($context);
1730 $xi +
= sizeof($edit->orig
);
1732 $yi +
= sizeof($edit->closing
);
1735 if (is_array($block))
1736 $this->_block($x0, $xi - $x0,
1740 $end = $this->_end_diff();
1741 wfProfileOut( __METHOD__
);
1745 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1746 wfProfileIn( __METHOD__
);
1747 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1748 foreach ($edits as $edit) {
1749 if ($edit->type
== 'copy')
1750 $this->_context($edit->orig
);
1751 elseif ($edit->type
== 'add')
1752 $this->_added($edit->closing
);
1753 elseif ($edit->type
== 'delete')
1754 $this->_deleted($edit->orig
);
1755 elseif ($edit->type
== 'change')
1756 $this->_changed($edit->orig
, $edit->closing
);
1758 trigger_error('Unknown edit type', E_USER_ERROR
);
1760 $this->_end_block();
1761 wfProfileOut( __METHOD__
);
1764 function _start_diff() {
1768 function _end_diff() {
1769 $val = ob_get_contents();
1774 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1776 $xbeg .= "," . ($xbeg +
$xlen - 1);
1778 $ybeg .= "," . ($ybeg +
$ylen - 1);
1780 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1783 function _start_block($header) {
1784 echo $header . "\n";
1787 function _end_block() {
1790 function _lines($lines, $prefix = ' ') {
1791 foreach ($lines as $line)
1792 echo "$prefix $line\n";
1795 function _context($lines) {
1796 $this->_lines($lines);
1799 function _added($lines) {
1800 $this->_lines($lines, '>');
1802 function _deleted($lines) {
1803 $this->_lines($lines, '<');
1806 function _changed($orig, $closing) {
1807 $this->_deleted($orig);
1809 $this->_added($closing);
1814 * A formatter that outputs unified diffs
1815 * @ingroup DifferenceEngine
1818 class UnifiedDiffFormatter
extends DiffFormatter
{
1819 var $leading_context_lines = 2;
1820 var $trailing_context_lines = 2;
1822 function _added($lines) {
1823 $this->_lines($lines, '+');
1825 function _deleted($lines) {
1826 $this->_lines($lines, '-');
1828 function _changed($orig, $closing) {
1829 $this->_deleted($orig);
1830 $this->_added($closing);
1832 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1833 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1838 * A pseudo-formatter that just passes along the Diff::$edits array
1839 * @ingroup DifferenceEngine
1841 class ArrayDiffFormatter
extends DiffFormatter
{
1842 function format($diff) {
1846 foreach($diff->edits
as $edit)
1847 switch($edit->type
) {
1849 foreach($edit->closing
as $l) {
1853 'newline' => $newline++
1858 foreach($edit->orig
as $l) {
1860 'action' => 'delete',
1862 'oldline' => $oldline++
,
1867 foreach($edit->orig
as $i => $l) {
1869 'action' => 'change',
1871 'new' => @$edit->closing
[$i],
1872 'oldline' => $oldline++
,
1873 'newline' => $newline++
,
1878 $oldline +
= count($edit->orig
);
1879 $newline +
= count($edit->orig
);
1886 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1890 define('NBSP', ' '); // iso-8859-x non-breaking space.
1895 * @ingroup DifferenceEngine
1897 class _HWLDF_WordAccumulator
{
1898 function _HWLDF_WordAccumulator () {
1899 $this->_lines
= array();
1905 function _flushGroup ($new_tag) {
1906 if ($this->_group
!== '') {
1907 if ($this->_tag
== 'ins')
1908 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1909 htmlspecialchars ( $this->_group
) . '</ins>';
1910 elseif ($this->_tag
== 'del')
1911 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1912 htmlspecialchars ( $this->_group
) . '</del>';
1914 $this->_line
.= htmlspecialchars ( $this->_group
);
1917 $this->_tag
= $new_tag;
1920 function _flushLine ($new_tag) {
1921 $this->_flushGroup($new_tag);
1922 if ($this->_line
!= '')
1923 array_push ( $this->_lines
, $this->_line
);
1925 # make empty lines visible by inserting an NBSP
1926 array_push ( $this->_lines
, NBSP
);
1930 function addWords ($words, $tag = '') {
1931 if ($tag != $this->_tag
)
1932 $this->_flushGroup($tag);
1934 foreach ($words as $word) {
1935 // new-line should only come as first char of word.
1938 if ($word[0] == "\n") {
1939 $this->_flushLine($tag);
1940 $word = substr($word, 1);
1942 assert(!strstr($word, "\n"));
1943 $this->_group
.= $word;
1947 function getLines() {
1948 $this->_flushLine('~done');
1949 return $this->_lines
;
1956 * @ingroup DifferenceEngine
1958 class WordLevelDiff
extends MappedDiff
{
1959 const MAX_LINE_LENGTH
= 10000;
1961 function WordLevelDiff ($orig_lines, $closing_lines) {
1962 wfProfileIn( __METHOD__
);
1964 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1965 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1967 $this->MappedDiff($orig_words, $closing_words,
1968 $orig_stripped, $closing_stripped);
1969 wfProfileOut( __METHOD__
);
1972 function _split($lines) {
1973 wfProfileIn( __METHOD__
);
1976 $stripped = array();
1978 foreach ( $lines as $line ) {
1979 # If the line is too long, just pretend the entire line is one big word
1980 # This prevents resource exhaustion problems
1987 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1989 $stripped[] = $line;
1992 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1995 $words = array_merge( $words, $m[0] );
1996 $stripped = array_merge( $stripped, $m[1] );
2000 wfProfileOut( __METHOD__
);
2001 return array($words, $stripped);
2005 wfProfileIn( __METHOD__
);
2006 $orig = new _HWLDF_WordAccumulator
;
2008 foreach ($this->edits
as $edit) {
2009 if ($edit->type
== 'copy')
2010 $orig->addWords($edit->orig
);
2011 elseif ($edit->orig
)
2012 $orig->addWords($edit->orig
, 'del');
2014 $lines = $orig->getLines();
2015 wfProfileOut( __METHOD__
);
2019 function closing () {
2020 wfProfileIn( __METHOD__
);
2021 $closing = new _HWLDF_WordAccumulator
;
2023 foreach ($this->edits
as $edit) {
2024 if ($edit->type
== 'copy')
2025 $closing->addWords($edit->closing
);
2026 elseif ($edit->closing
)
2027 $closing->addWords($edit->closing
, 'ins');
2029 $lines = $closing->getLines();
2030 wfProfileOut( __METHOD__
);
2036 * Wikipedia Table style diff formatter.
2039 * @ingroup DifferenceEngine
2041 class TableDiffFormatter
extends DiffFormatter
{
2042 function TableDiffFormatter() {
2043 $this->leading_context_lines
= 2;
2044 $this->trailing_context_lines
= 2;
2047 public static function escapeWhiteSpace( $msg ) {
2048 $msg = preg_replace( '/^ /m', ' ', $msg );
2049 $msg = preg_replace( '/ $/m', ' ', $msg );
2050 $msg = preg_replace( '/ /', ' ', $msg );
2054 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2055 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2056 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2060 function _start_block( $header ) {
2064 function _end_block() {
2067 function _lines( $lines, $prefix=' ', $color='white' ) {
2070 # HTML-escape parameter before calling this
2071 function addedLine( $line ) {
2072 return $this->wrapLine( '+', 'diff-addedline', $line );
2075 # HTML-escape parameter before calling this
2076 function deletedLine( $line ) {
2077 return $this->wrapLine( '-', 'diff-deletedline', $line );
2080 # HTML-escape parameter before calling this
2081 function contextLine( $line ) {
2082 return $this->wrapLine( ' ', 'diff-context', $line );
2085 private function wrapLine( $marker, $class, $line ) {
2086 if( $line !== '' ) {
2087 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2088 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2090 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2093 function emptyLine() {
2094 return '<td colspan="2"> </td>';
2097 function _added( $lines ) {
2098 foreach ($lines as $line) {
2099 echo '<tr>' . $this->emptyLine() .
2100 $this->addedLine( '<ins class="diffchange">' .
2101 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2105 function _deleted($lines) {
2106 foreach ($lines as $line) {
2107 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2108 htmlspecialchars ( $line ) . '</del>' ) .
2109 $this->emptyLine() . "</tr>\n";
2113 function _context( $lines ) {
2114 foreach ($lines as $line) {
2116 $this->contextLine( htmlspecialchars ( $line ) ) .
2117 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2121 function _changed( $orig, $closing ) {
2122 wfProfileIn( __METHOD__
);
2124 $diff = new WordLevelDiff( $orig, $closing );
2125 $del = $diff->orig();
2126 $add = $diff->closing();
2128 # Notice that WordLevelDiff returns HTML-escaped output.
2129 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2131 while ( $line = array_shift( $del ) ) {
2132 $aline = array_shift( $add );
2133 echo '<tr>' . $this->deletedLine( $line ) .
2134 $this->addedLine( $aline ) . "</tr>\n";
2136 foreach ($add as $line) { # If any leftovers
2137 echo '<tr>' . $this->emptyLine() .
2138 $this->addedLine( $line ) . "</tr>\n";
2140 wfProfileOut( __METHOD__
);