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?
35 * @param $titleObj Title object that the diff is associated with
36 * @param $old Integer: old ID we want to show and diff with.
37 * @param $new String: either 'prev' or 'next'.
38 * @param $rcid Integer: ??? FIXME (default 0)
39 * @param $refreshCache boolean If set, refreshes the diff cache
40 * @param $htmldiff boolean If set, output using HTMLDiff instead of raw wikicode diff
42 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false , $htmldiff = false) {
43 $this->mTitle
= $titleObj;
44 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
46 if ( 'prev' === $new ) {
47 # Show diff between revision $old and the previous one.
48 # Get previous one from DB.
49 $this->mNewid
= intval($old);
50 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
51 } elseif ( 'next' === $new ) {
52 # Show diff between revision $old and the previous one.
53 # Get previous one from DB.
55 $this->mOldid
= intval($old);
56 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
57 if ( false === $this->mNewid
) {
58 # if no result, NewId points to the newest old revision. The only newer
59 # revision is cur, which is "0".
63 $this->mOldid
= intval($old);
64 $this->mNewid
= intval($new);
65 wfRunHooks( 'NewDifferenceEngine', array(&$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new) );
67 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
68 $this->mRefreshCache
= $refreshCache;
69 $this->htmldiff
= $htmldiff;
76 function showDiffPage( $diffOnly = false ) {
77 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
78 wfProfileIn( __METHOD__
);
81 # If external diffs are enabled both globally and for the user,
82 # we'll use the application/x-external-editor interface to call
83 # an external diff tool like kompare, kdiff3, etc.
84 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
85 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
87 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
88 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
89 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
90 $special=$wgLang->getNsText(NS_SPECIAL
);
95 Script={$wgServer}{$wgScript}
96 Special namespace={$special}
110 $wgOut->setArticleFlag( false );
111 if ( !$this->loadRevisionData() ) {
112 $t = $this->mTitle
->getPrefixedText();
113 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
114 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
115 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
116 wfProfileOut( __METHOD__
);
120 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
122 if ( $this->mNewRev
->isCurrent() ) {
123 $wgOut->setArticleFlag( true );
126 # mOldid is false if the difference engine is called with a "vague" query for
127 # a diff between a version V and its previous version V' AND the version V
128 # is the first version of that article. In that case, V' does not exist.
129 if ( $this->mOldid
=== false ) {
130 $this->showFirstRevision();
131 $this->renderNewRevision(); // should we respect $diffOnly here or not?
132 wfProfileOut( __METHOD__
);
136 $wgOut->suppressQuickbar();
138 $oldTitle = $this->mOldPage
->getPrefixedText();
139 $newTitle = $this->mNewPage
->getPrefixedText();
140 if( $oldTitle == $newTitle ) {
141 $wgOut->setPageTitle( $newTitle );
143 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
145 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
146 $wgOut->setRobotPolicy( 'noindex,nofollow' );
148 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
149 $wgOut->loginToUse();
152 wfProfileOut( __METHOD__
);
156 $sk = $wgUser->getSkin();
158 // Check if page is editable
159 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
160 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
161 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
166 // Prepare a change patrol link, if applicable
167 if( $wgUseRCPatrol && $this->mTitle
->userCan('patrol') ) {
168 // If we've been given an explicit change identifier, use it; saves time
169 if( $this->mRcidMarkPatrolled
) {
170 $rcid = $this->mRcidMarkPatrolled
;
172 // Look for an unpatrolled change corresponding to this diff
173 $db = wfGetDB( DB_SLAVE
);
174 $change = RecentChange
::newFromConds(
176 // Add redundant user,timestamp condition so we can use the existing index
177 'rc_user_text' => $this->mNewRev
->getRawUserText(),
178 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
179 'rc_this_oldid' => $this->mNewid
,
180 'rc_last_oldid' => $this->mOldid
,
185 if( $change instanceof RecentChange
) {
186 $rcid = $change->mAttribs
['rc_id'];
194 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
196 wfMsgHtml( 'markaspatrolleddiff' ),
197 "action=markpatrolled&rcid={$rcid}"
206 $htmldiffarg = $this->htmlDiffArgument();
207 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
208 'diff=prev&oldid='.$this->mOldid
.$htmldiffarg, '', '', 'id="differences-prevlink"' );
209 if ( $this->mNewRev
->isCurrent() ) {
210 $nextlink = ' ';
212 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
213 'diff=next&oldid='.$this->mNewid
.$htmldiffarg, '', '', 'id="differences-nextlink"' );
219 if ($this->mOldRev
->mMinorEdit
== 1) {
220 $oldminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
223 if ($this->mNewRev
->mMinorEdit
== 1) {
224 $newminor = Xml
::span( wfMsg( 'minoreditletter' ), 'minor' ) . ' ';
227 $rdel = ''; $ldel = '';
228 if( $wgUser->isAllowed( 'deleterevision' ) ) {
229 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
230 // If revision was hidden from sysops
231 $ldel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
233 $query = array( 'target' => $this->mOldRev
->mTitle
->getPrefixedDbkey(),
234 'oldid' => $this->mOldRev
->getId()
236 $ldel = $sk->revDeleteLink( $query, $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
238 $ldel = " $ldel ";
239 // We don't currently handle well changing the top revision's settings
240 if( $this->mNewRev
->isCurrent() ) {
241 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
242 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
243 // If revision was hidden from sysops
244 $rdel = Xml
::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
246 $query = array( 'target' => $this->mNewRev
->mTitle
->getPrefixedDbkey(),
247 'oldid' => $this->mNewRev
->getId()
249 $rdel = $sk->revDeleteLink( $query, $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) );
251 $rdel = " $rdel ";
254 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
255 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
256 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
257 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
258 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
259 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
260 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
261 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
263 if( $wgEnableHtmlDiff && $this->htmldiff
) {
264 $multi = $this->getMultiNotice();
265 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
266 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
267 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
268 $this->renderHtmlDiff();
270 if($wgEnableHtmlDiff){
271 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
272 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
274 $this->showDiff( $oldHeader, $newHeader );
276 $this->renderNewRevision();
279 wfProfileOut( __METHOD__
);
283 * Show the new revision of the page.
285 function renderNewRevision() {
287 wfProfileIn( __METHOD__
);
289 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
290 #add deleted rev tag if needed
291 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
292 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
293 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
294 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
297 if( !$this->mNewRev
->isCurrent() ) {
298 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
301 $this->loadNewText();
302 if( is_object( $this->mNewRev
) ) {
303 $wgOut->setRevisionId( $this->mNewRev
->getId() );
306 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
307 // Stolen from Article::view --AG 2007-10-11
309 // Give hooks a chance to customise the output
310 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
311 // Wrap the whole lot in a <pre> and don't parse
313 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
314 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
315 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
316 $wgOut->addHTML( "\n</pre>\n" );
319 $wgOut->addWikiTextTidy( $this->mNewtext
);
321 if( !$this->mNewRev
->isCurrent() ) {
322 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
325 wfProfileOut( __METHOD__
);
329 function renderHtmlDiff() {
330 global $wgOut, $wgTitle, $wgParser, $wgDebugComments;
331 wfProfileIn( __METHOD__
);
333 $this->showDiffStyle();
335 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
336 #add deleted rev tag if needed
337 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
338 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
339 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
340 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
343 if( !$this->mNewRev
->isCurrent() ) {
344 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
350 if( is_object( $this->mOldRev
) ) {
351 $wgOut->setRevisionId( $this->mOldRev
->getId() );
354 $popts = $wgOut->parserOptions();
355 $oldTidy = $popts->setTidy( true );
356 $popts->setEditSection( false );
358 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
359 $popts->setTidy( $oldTidy );
362 //$wgOut->addParserOutputNoText( $parserOutput );
363 $oldHtml = $parserOutput->getText();
364 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
367 if( is_object( $this->mNewRev
) ) {
368 $wgOut->setRevisionId( $this->mNewRev
->getId() );
371 $popts = $wgOut->parserOptions();
372 $oldTidy = $popts->setTidy( true );
374 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
375 $popts->setTidy( $oldTidy );
377 $wgOut->addParserOutputNoText( $parserOutput );
378 $newHtml = $parserOutput->getText();
379 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
381 unset($parserOutput, $popts);
383 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
384 $differ->htmlDiff($oldHtml, $newHtml);
385 if ( $wgDebugComments ) {
386 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
389 wfProfileOut( __METHOD__
);
393 * Show the first revision of an article. Uses normal diff headers in
394 * contrast to normal "old revision" display style.
396 function showFirstRevision() {
397 global $wgOut, $wgUser;
398 wfProfileIn( __METHOD__
);
400 # Get article text from the DB
402 if ( ! $this->loadNewText() ) {
403 $t = $this->mTitle
->getPrefixedText();
404 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
405 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
406 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
407 wfProfileOut( __METHOD__
);
410 if ( $this->mNewRev
->isCurrent() ) {
411 $wgOut->setArticleFlag( true );
414 # Check if user is allowed to look at this page. If not, bail out.
416 if ( !$this->mTitle
->userCanRead() ) {
417 $wgOut->loginToUse();
419 wfProfileOut( __METHOD__
);
420 throw new MWException("Permission Error: you do not have access to view this page");
423 # Prepare the header box
425 $sk = $wgUser->getSkin();
427 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
431 $nextlink = '<br/>' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
432 'diff=next&oldid=' . $this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
434 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
435 $sk->revUserTools( $this->mNewRev
) . "<br/>" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
437 $wgOut->addHTML( $header );
439 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
440 $wgOut->setRobotPolicy( 'noindex,nofollow' );
442 wfProfileOut( __METHOD__
);
445 function htmlDiffArgument(){
446 global $wgEnableHtmlDiff;
447 if($wgEnableHtmlDiff){
449 return '&htmldiff=1';
451 return '&htmldiff=0';
459 * Get the diff text, send it to $wgOut
460 * Returns false if the diff could not be generated, otherwise returns true
462 function showDiff( $otitle, $ntitle ) {
464 $diff = $this->getDiff( $otitle, $ntitle );
465 if ( $diff === false ) {
466 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
469 $this->showDiffStyle();
470 $wgOut->addHTML( $diff );
476 * Add style sheets and supporting JS for diff display.
478 function showDiffStyle() {
479 global $wgStylePath, $wgStyleVersion, $wgOut;
480 $wgOut->addStyle( 'common/diff.css' );
482 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
483 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
487 * Get complete diff table, including header
489 * @param Title $otitle Old title
490 * @param Title $ntitle New title
493 function getDiff( $otitle, $ntitle ) {
494 $body = $this->getDiffBody();
495 if ( $body === false ) {
498 $multi = $this->getMultiNotice();
499 return $this->addHeader( $body, $otitle, $ntitle, $multi );
504 * Get the diff table body, without header
508 function getDiffBody() {
510 wfProfileIn( __METHOD__
);
511 // Check if the diff should be hidden from this user
512 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
514 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
519 if ( $this->mOldid
&& $this->mNewid
) {
520 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
522 if ( !$this->mRefreshCache
) {
523 $difftext = $wgMemc->get( $key );
525 wfIncrStats( 'diff_cache_hit' );
526 $difftext = $this->localiseLineNumbers( $difftext );
527 $difftext .= "\n<!-- diff cache key $key -->\n";
528 wfProfileOut( __METHOD__
);
531 } // don't try to load but save the result
534 // Loadtext is permission safe, this just clears out the diff
535 if ( !$this->loadText() ) {
536 wfProfileOut( __METHOD__
);
540 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
542 // Save to cache for 7 days
543 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
544 wfIncrStats( 'diff_uncacheable' );
545 } else if ( $key !== false && $difftext !== false ) {
546 wfIncrStats( 'diff_cache_miss' );
547 $wgMemc->set( $key, $difftext, 7*86400 );
549 wfIncrStats( 'diff_uncacheable' );
551 // Replace line numbers with the text in the user's language
552 if ( $difftext !== false ) {
553 $difftext = $this->localiseLineNumbers( $difftext );
555 wfProfileOut( __METHOD__
);
560 * Generate a diff, no caching
561 * $otext and $ntext must be already segmented
563 function generateDiffBody( $otext, $ntext ) {
564 global $wgExternalDiffEngine, $wgContLang;
566 $otext = str_replace( "\r\n", "\n", $otext );
567 $ntext = str_replace( "\r\n", "\n", $ntext );
569 if ( $wgExternalDiffEngine == 'wikidiff' ) {
570 # For historical reasons, external diff engine expects
571 # input text to be HTML-escaped already
572 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
573 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
574 if( !function_exists( 'wikidiff_do_diff' ) ) {
575 dl('php_wikidiff.so');
577 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
578 $this->debug( 'wikidiff1' );
581 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
582 # Better external diff engine, the 2 may some day be dropped
583 # This one does the escaping and segmenting itself
584 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
585 wfProfileIn( __METHOD__
. "-dl" );
586 @dl
('php_wikidiff2.so');
587 wfProfileOut( __METHOD__
. "-dl" );
589 if ( function_exists( 'wikidiff2_do_diff' ) ) {
590 wfProfileIn( 'wikidiff2_do_diff' );
591 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
592 $text .= $this->debug( 'wikidiff2' );
593 wfProfileOut( 'wikidiff2_do_diff' );
597 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
599 global $wgTmpDirectory;
600 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
601 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
603 $tempFile1 = fopen( $tempName1, "w" );
605 wfProfileOut( __METHOD__
);
608 $tempFile2 = fopen( $tempName2, "w" );
610 wfProfileOut( __METHOD__
);
613 fwrite( $tempFile1, $otext );
614 fwrite( $tempFile2, $ntext );
615 fclose( $tempFile1 );
616 fclose( $tempFile2 );
617 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
618 wfProfileIn( __METHOD__
. "-shellexec" );
619 $difftext = wfShellExec( $cmd );
620 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
621 wfProfileOut( __METHOD__
. "-shellexec" );
622 unlink( $tempName1 );
623 unlink( $tempName2 );
628 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
629 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
630 $diffs = new Diff( $ota, $nta );
631 $formatter = new TableDiffFormatter();
632 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
637 * Generate a debug comment indicating diff generating time,
638 * server node, and generator backend.
640 protected function debug( $generator="internal" ) {
641 global $wgShowHostnames;
642 $data = array( $generator );
643 if( $wgShowHostnames ) {
644 $data[] = wfHostname();
646 $data[] = wfTimestamp( TS_DB
);
647 return "<!-- diff generator: " .
656 * Replace line numbers with the text in the user's language
658 function localiseLineNumbers( $text ) {
659 return preg_replace_callback( '/<!--LINE (\d+)-->/',
660 array( &$this, 'localiseLineNumbersCb' ), $text );
663 function localiseLineNumbersCb( $matches ) {
665 return wfMsgExt( 'lineno', array( 'parseinline' ), $wgLang->formatNum( $matches[1] ) );
670 * If there are revisions between the ones being compared, return a note saying so.
672 function getMultiNotice() {
673 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
676 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
677 // Comparing two different pages? Count would be meaningless.
681 $oldid = $this->mOldRev
->getId();
682 $newid = $this->mNewRev
->getId();
683 if ( $oldid > $newid ) {
684 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
687 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
691 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
696 * Add the header to a diff body
698 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
701 <col class='diff-marker' />
702 <col class='diff-content' />
703 <col class='diff-marker' />
704 <col class='diff-content' />
706 <td colspan='2' class='diff-otitle'>{$otitle}</td>
707 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
712 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
714 return $header . $diff . "</table>";
718 * Use specified text instead of loading from the database
720 function setText( $oldText, $newText ) {
721 $this->mOldtext
= $oldText;
722 $this->mNewtext
= $newText;
723 $this->mTextLoaded
= 2;
727 * Load revision metadata for the specified articles. If newid is 0, then compare
728 * the old article in oldid to the current article; if oldid is 0, then
729 * compare the current article to the immediately previous one (ignoring the
732 * If oldid is false, leave the corresponding revision object set
733 * to false. This is impossible via ordinary user input, and is provided for
736 function loadRevisionData() {
737 global $wgLang, $wgUser;
738 if ( $this->mRevisionsLoaded
) {
741 // Whether it succeeds or fails, we don't want to try again
742 $this->mRevisionsLoaded
= true;
745 // Load the new revision object
746 $this->mNewRev
= $this->mNewid
747 ? Revision
::newFromId( $this->mNewid
)
748 : Revision
::newFromTitle( $this->mTitle
);
749 if( !$this->mNewRev
instanceof Revision
)
752 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
753 $this->mNewid
= $this->mNewRev
->getId();
755 // Check if page is editable
756 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
758 // Set assorted variables
759 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
760 $this->mNewPage
= $this->mNewRev
->getTitle();
761 if( $this->mNewRev
->isCurrent() ) {
762 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
763 $this->mPagetitle
= wfMsgHTML( 'currentrev-asof', $timestamp );
764 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
766 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
767 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
770 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
771 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
772 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
774 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
775 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
777 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
778 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
779 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
780 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
783 // Load the old revision object
784 $this->mOldRev
= false;
785 if( $this->mOldid
) {
786 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
787 } elseif ( $this->mOldid
=== 0 ) {
788 $rev = $this->mNewRev
->getPrevious();
790 $this->mOldid
= $rev->getId();
791 $this->mOldRev
= $rev;
793 // No previous revision; mark to show as first-version only.
794 $this->mOldid
= false;
795 $this->mOldRev
= false;
797 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
799 if( is_null( $this->mOldRev
) ) {
803 if ( $this->mOldRev
) {
804 $this->mOldPage
= $this->mOldRev
->getTitle();
806 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
807 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
808 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
809 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
811 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
812 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
813 // Add an "undo" link
814 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
815 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
816 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
817 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
818 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
821 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
822 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
823 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
824 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
832 * Load the text of the revisions, as well as revision data.
834 function loadText() {
835 if ( $this->mTextLoaded
== 2 ) {
838 // Whether it succeeds or fails, we don't want to try again
839 $this->mTextLoaded
= 2;
842 if ( !$this->loadRevisionData() ) {
845 if ( $this->mOldRev
) {
846 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
847 if ( $this->mOldtext
=== false ) {
851 if ( $this->mNewRev
) {
852 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
853 if ( $this->mNewtext
=== false ) {
861 * Load the text of the new revision, not the old one
863 function loadNewText() {
864 if ( $this->mTextLoaded
>= 1 ) {
867 $this->mTextLoaded
= 1;
869 if ( !$this->loadRevisionData() ) {
872 $this->mNewtext
= $this->mNewRev
->getText();
879 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
881 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
882 // You may copy this code freely under the conditions of the GPL.
885 define('USE_ASSERTS', function_exists('assert'));
890 * @ingroup DifferenceEngine
898 trigger_error('pure virtual', E_USER_ERROR
);
902 return $this->orig ?
sizeof($this->orig
) : 0;
905 function nclosing() {
906 return $this->closing ?
sizeof($this->closing
) : 0;
913 * @ingroup DifferenceEngine
915 class _DiffOp_Copy
extends _DiffOp
{
918 function _DiffOp_Copy ($orig, $closing = false) {
919 if (!is_array($closing))
922 $this->closing
= $closing;
926 return new _DiffOp_Copy($this->closing
, $this->orig
);
933 * @ingroup DifferenceEngine
935 class _DiffOp_Delete
extends _DiffOp
{
936 var $type = 'delete';
938 function _DiffOp_Delete ($lines) {
939 $this->orig
= $lines;
940 $this->closing
= false;
944 return new _DiffOp_Add($this->orig
);
951 * @ingroup DifferenceEngine
953 class _DiffOp_Add
extends _DiffOp
{
956 function _DiffOp_Add ($lines) {
957 $this->closing
= $lines;
962 return new _DiffOp_Delete($this->closing
);
969 * @ingroup DifferenceEngine
971 class _DiffOp_Change
extends _DiffOp
{
972 var $type = 'change';
974 function _DiffOp_Change ($orig, $closing) {
976 $this->closing
= $closing;
980 return new _DiffOp_Change($this->closing
, $this->orig
);
985 * Class used internally by Diff to actually compute the diffs.
987 * The algorithm used here is mostly lifted from the perl module
988 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
989 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
991 * More ideas are taken from:
992 * http://www.ics.uci.edu/~eppstein/161/960229.html
994 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
995 * diffutils-2.7, which can be found at:
996 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
998 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1001 * Line length limits for robustness added by Tim Starling, 2005-08-31
1002 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1004 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1006 * @ingroup DifferenceEngine
1010 const MAX_XREF_LENGTH
= 10000;
1012 function diff ($from_lines, $to_lines){
1013 wfProfileIn( __METHOD__
);
1015 // Diff and store locally
1016 $this->diff_local($from_lines, $to_lines);
1018 // Merge edits when possible
1019 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1020 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1022 // Compute the edit operations.
1023 $n_from = sizeof($from_lines);
1024 $n_to = sizeof($to_lines);
1028 while ($xi < $n_from ||
$yi < $n_to) {
1029 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1030 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1032 // Skip matching "snake".
1034 while ( $xi < $n_from && $yi < $n_to
1035 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1036 $copy[] = $from_lines[$xi++
];
1040 $edits[] = new _DiffOp_Copy($copy);
1042 // Find deletes & adds.
1044 while ($xi < $n_from && $this->xchanged
[$xi])
1045 $delete[] = $from_lines[$xi++
];
1048 while ($yi < $n_to && $this->ychanged
[$yi])
1049 $add[] = $to_lines[$yi++
];
1051 if ($delete && $add)
1052 $edits[] = new _DiffOp_Change($delete, $add);
1054 $edits[] = new _DiffOp_Delete($delete);
1056 $edits[] = new _DiffOp_Add($add);
1058 wfProfileOut( __METHOD__
);
1062 function diff_local ($from_lines, $to_lines) {
1063 global $wgExternalDiffEngine;
1064 wfProfileIn( __METHOD__
);
1066 if($wgExternalDiffEngine == 'wikidiff3'){
1068 $wikidiff3 = new WikiDiff3();
1069 $wikidiff3->diff($from_lines, $to_lines);
1070 $this->xchanged
= $wikidiff3->removed
;
1071 $this->ychanged
= $wikidiff3->added
;
1075 $n_from = sizeof($from_lines);
1076 $n_to = sizeof($to_lines);
1077 $this->xchanged
= $this->ychanged
= array();
1078 $this->xv
= $this->yv
= array();
1079 $this->xind
= $this->yind
= array();
1081 unset($this->in_seq
);
1084 // Skip leading common lines.
1085 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1086 if ($from_lines[$skip] !== $to_lines[$skip])
1088 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1090 // Skip trailing common lines.
1091 $xi = $n_from; $yi = $n_to;
1092 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1093 if ($from_lines[$xi] !== $to_lines[$yi])
1095 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1098 // Ignore lines which do not exist in both files.
1099 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1100 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1103 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1104 $line = $to_lines[$yi];
1105 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1107 $yhash[$this->_line_hash($line)] = 1;
1108 $this->yv
[] = $line;
1109 $this->yind
[] = $yi;
1111 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1112 $line = $from_lines[$xi];
1113 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1115 $this->xv
[] = $line;
1116 $this->xind
[] = $xi;
1120 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1122 wfProfileOut( __METHOD__
);
1126 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1128 function _line_hash( $line ) {
1129 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1130 return md5( $line );
1136 /* Divide the Largest Common Subsequence (LCS) of the sequences
1137 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1140 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1141 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1142 * sub sequences. The first sub-sequence is contained in [X0, X1),
1143 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1144 * that (X0, Y0) == (XOFF, YOFF) and
1145 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1147 * This function assumes that the first lines of the specified portions
1148 * of the two files do not match, and likewise that the last lines do not
1149 * match. The caller must trim matching lines from the beginning and end
1150 * of the portions it is going to specify.
1152 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1155 if ($xlim - $xoff > $ylim - $yoff) {
1156 // Things seems faster (I'm not sure I understand why)
1157 // when the shortest sequence in X.
1159 list ($xoff, $xlim, $yoff, $ylim)
1160 = array( $yoff, $ylim, $xoff, $xlim);
1164 for ($i = $ylim - 1; $i >= $yoff; $i--)
1165 $ymatches[$this->xv
[$i]][] = $i;
1167 for ($i = $ylim - 1; $i >= $yoff; $i--)
1168 $ymatches[$this->yv
[$i]][] = $i;
1171 $this->seq
[0]= $yoff - 1;
1172 $this->in_seq
= array();
1173 $ymids[0] = array();
1175 $numer = $xlim - $xoff +
$nchunks - 1;
1177 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1179 for ($i = 0; $i <= $this->lcs
; $i++
)
1180 $ymids[$i][$chunk-1] = $this->seq
[$i];
1182 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1183 for ( ; $x < $x1; $x++
) {
1184 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1185 if (empty($ymatches[$line]))
1187 $matches = $ymatches[$line];
1189 while (list ($junk, $y) = each($matches))
1190 if (empty($this->in_seq
[$y])) {
1191 $k = $this->_lcs_pos($y);
1192 USE_ASSERTS
&& assert($k > 0);
1193 $ymids[$k] = $ymids[$k-1];
1196 while (list ( /* $junk */, $y) = each($matches)) {
1197 if ($y > $this->seq
[$k-1]) {
1198 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1199 // Optimization: this is a common case:
1200 // next match is just replacing previous match.
1201 $this->in_seq
[$this->seq
[$k]] = false;
1202 $this->seq
[$k] = $y;
1203 $this->in_seq
[$y] = 1;
1204 } else if (empty($this->in_seq
[$y])) {
1205 $k = $this->_lcs_pos($y);
1206 USE_ASSERTS
&& assert($k > 0);
1207 $ymids[$k] = $ymids[$k-1];
1213 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1214 $ymid = $ymids[$this->lcs
];
1215 for ($n = 0; $n < $nchunks - 1; $n++
) {
1216 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1217 $y1 = $ymid[$n] +
1;
1218 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1220 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1222 return array($this->lcs
, $seps);
1225 function _lcs_pos ($ypos) {
1227 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1228 $this->seq
[++
$this->lcs
] = $ypos;
1229 $this->in_seq
[$ypos] = 1;
1234 while ($beg < $end) {
1235 $mid = (int)(($beg +
$end) / 2);
1236 if ( $ypos > $this->seq
[$mid] )
1242 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1244 $this->in_seq
[$this->seq
[$end]] = false;
1245 $this->seq
[$end] = $ypos;
1246 $this->in_seq
[$ypos] = 1;
1250 /* Find LCS of two sequences.
1252 * The results are recorded in the vectors $this->{x,y}changed[], by
1253 * storing a 1 in the element for each line that is an insertion
1254 * or deletion (ie. is not in the LCS).
1256 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1258 * Note that XLIM, YLIM are exclusive bounds.
1259 * All line numbers are origin-0 and discarded lines are not counted.
1261 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1262 // Slide down the bottom initial diagonal.
1263 while ($xoff < $xlim && $yoff < $ylim
1264 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1269 // Slide up the top initial diagonal.
1270 while ($xlim > $xoff && $ylim > $yoff
1271 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1276 if ($xoff == $xlim ||
$yoff == $ylim)
1279 // This is ad hoc but seems to work well.
1280 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1281 //$nchunks = max(2,min(8,(int)$nchunks));
1282 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1284 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1288 // X and Y sequences have no common subsequence:
1289 // mark all changed.
1290 while ($yoff < $ylim)
1291 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1292 while ($xoff < $xlim)
1293 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1295 // Use the partitions to split this problem into subproblems.
1298 while ($pt2 = next($seps)) {
1299 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1305 /* Adjust inserts/deletes of identical lines to join changes
1306 * as much as possible.
1308 * We do something when a run of changed lines include a
1309 * line at one end and has an excluded, identical line at the other.
1310 * We are free to choose which identical line is included.
1311 * `compareseq' usually chooses the one at the beginning,
1312 * but usually it is cleaner to consider the following identical line
1313 * to be the "change".
1315 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1317 function _shift_boundaries ($lines, &$changed, $other_changed) {
1318 wfProfileIn( __METHOD__
);
1322 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1323 $len = sizeof($lines);
1324 $other_len = sizeof($other_changed);
1328 * Scan forwards to find beginning of another run of changes.
1329 * Also keep track of the corresponding point in the other file.
1331 * Throughout this code, $i and $j are adjusted together so that
1332 * the first $i elements of $changed and the first $j elements
1333 * of $other_changed both contain the same number of zeros
1334 * (unchanged lines).
1335 * Furthermore, $j is always kept so that $j == $other_len or
1336 * $other_changed[$j] == false.
1338 while ($j < $other_len && $other_changed[$j])
1341 while ($i < $len && ! $changed[$i]) {
1342 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1344 while ($j < $other_len && $other_changed[$j])
1353 // Find the end of this run of changes.
1354 while (++
$i < $len && $changed[$i])
1359 * Record the length of this run of changes, so that
1360 * we can later determine whether the run has grown.
1362 $runlength = $i - $start;
1365 * Move the changed region back, so long as the
1366 * previous unchanged line matches the last changed one.
1367 * This merges with previous changed regions.
1369 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1370 $changed[--$start] = 1;
1371 $changed[--$i] = false;
1372 while ($start > 0 && $changed[$start - 1])
1374 USE_ASSERTS
&& assert('$j > 0');
1375 while ($other_changed[--$j])
1377 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1381 * Set CORRESPONDING to the end of the changed run, at the last
1382 * point where it corresponds to a changed run in the other file.
1383 * CORRESPONDING == LEN means no such point has been found.
1385 $corresponding = $j < $other_len ?
$i : $len;
1388 * Move the changed region forward, so long as the
1389 * first changed line matches the following unchanged one.
1390 * This merges with following changed regions.
1391 * Do this second, so that if there are no merges,
1392 * the changed region is moved forward as far as possible.
1394 while ($i < $len && $lines[$start] == $lines[$i]) {
1395 $changed[$start++
] = false;
1397 while ($i < $len && $changed[$i])
1400 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1402 if ($j < $other_len && $other_changed[$j]) {
1403 $corresponding = $i;
1404 while ($j < $other_len && $other_changed[$j])
1408 } while ($runlength != $i - $start);
1411 * If possible, move the fully-merged run of changes
1412 * back to a corresponding run in the other file.
1414 while ($corresponding < $i) {
1415 $changed[--$start] = 1;
1417 USE_ASSERTS
&& assert('$j > 0');
1418 while ($other_changed[--$j])
1420 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1423 wfProfileOut( __METHOD__
);
1428 * Class representing a 'diff' between two sequences of strings.
1431 * @ingroup DifferenceEngine
1439 * Computes diff between sequences of strings.
1441 * @param $from_lines array An array of strings.
1442 * (Typically these are lines from a file.)
1443 * @param $to_lines array An array of strings.
1445 function Diff($from_lines, $to_lines) {
1446 $eng = new _DiffEngine
;
1447 $this->edits
= $eng->diff($from_lines, $to_lines);
1448 //$this->_check($from_lines, $to_lines);
1452 * Compute reversed Diff.
1456 * $diff = new Diff($lines1, $lines2);
1457 * $rev = $diff->reverse();
1458 * @return object A Diff object representing the inverse of the
1461 function reverse () {
1463 $rev->edits
= array();
1464 foreach ($this->edits
as $edit) {
1465 $rev->edits
[] = $edit->reverse();
1471 * Check for empty diff.
1473 * @return bool True iff two sequences were identical.
1475 function isEmpty () {
1476 foreach ($this->edits
as $edit) {
1477 if ($edit->type
!= 'copy')
1484 * Compute the length of the Longest Common Subsequence (LCS).
1486 * This is mostly for diagnostic purposed.
1488 * @return int The length of the LCS.
1492 foreach ($this->edits
as $edit) {
1493 if ($edit->type
== 'copy')
1494 $lcs +
= sizeof($edit->orig
);
1500 * Get the original set of lines.
1502 * This reconstructs the $from_lines parameter passed to the
1505 * @return array The original sequence of strings.
1510 foreach ($this->edits
as $edit) {
1512 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1518 * Get the closing set of lines.
1520 * This reconstructs the $to_lines parameter passed to the
1523 * @return array The sequence of strings.
1525 function closing() {
1528 foreach ($this->edits
as $edit) {
1530 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1536 * Check a Diff for validity.
1538 * This is here only for debugging purposes.
1540 function _check ($from_lines, $to_lines) {
1541 wfProfileIn( __METHOD__
);
1542 if (serialize($from_lines) != serialize($this->orig()))
1543 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1544 if (serialize($to_lines) != serialize($this->closing()))
1545 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1547 $rev = $this->reverse();
1548 if (serialize($to_lines) != serialize($rev->orig()))
1549 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1550 if (serialize($from_lines) != serialize($rev->closing()))
1551 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1555 foreach ($this->edits
as $edit) {
1556 if ( $prevtype == $edit->type
)
1557 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1558 $prevtype = $edit->type
;
1561 $lcs = $this->lcs();
1562 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1563 wfProfileOut( __METHOD__
);
1568 * @todo document, bad name.
1570 * @ingroup DifferenceEngine
1572 class MappedDiff
extends Diff
1577 * Computes diff between sequences of strings.
1579 * This can be used to compute things like
1580 * case-insensitve diffs, or diffs which ignore
1581 * changes in white-space.
1583 * @param $from_lines array An array of strings.
1584 * (Typically these are lines from a file.)
1586 * @param $to_lines array An array of strings.
1588 * @param $mapped_from_lines array This array should
1589 * have the same size number of elements as $from_lines.
1590 * The elements in $mapped_from_lines and
1591 * $mapped_to_lines are what is actually compared
1592 * when computing the diff.
1594 * @param $mapped_to_lines array This array should
1595 * have the same number of elements as $to_lines.
1597 function MappedDiff($from_lines, $to_lines,
1598 $mapped_from_lines, $mapped_to_lines) {
1599 wfProfileIn( __METHOD__
);
1601 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1602 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1604 $this->Diff($mapped_from_lines, $mapped_to_lines);
1607 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1608 $orig = &$this->edits
[$i]->orig
;
1609 if (is_array($orig)) {
1610 $orig = array_slice($from_lines, $xi, sizeof($orig));
1611 $xi +
= sizeof($orig);
1614 $closing = &$this->edits
[$i]->closing
;
1615 if (is_array($closing)) {
1616 $closing = array_slice($to_lines, $yi, sizeof($closing));
1617 $yi +
= sizeof($closing);
1620 wfProfileOut( __METHOD__
);
1625 * A class to format Diffs
1627 * This class formats the diff in classic diff format.
1628 * It is intended that this class be customized via inheritance,
1629 * to obtain fancier outputs.
1632 * @ingroup DifferenceEngine
1634 class DiffFormatter
{
1636 * Number of leading context "lines" to preserve.
1638 * This should be left at zero for this class, but subclasses
1639 * may want to set this to other values.
1641 var $leading_context_lines = 0;
1644 * Number of trailing context "lines" to preserve.
1646 * This should be left at zero for this class, but subclasses
1647 * may want to set this to other values.
1649 var $trailing_context_lines = 0;
1654 * @param $diff object A Diff object.
1655 * @return string The formatted output.
1657 function format($diff) {
1658 wfProfileIn( __METHOD__
);
1664 $nlead = $this->leading_context_lines
;
1665 $ntrail = $this->trailing_context_lines
;
1667 $this->_start_diff();
1669 foreach ($diff->edits
as $edit) {
1670 if ($edit->type
== 'copy') {
1671 if (is_array($block)) {
1672 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1677 $context = array_slice($edit->orig
, 0, $ntrail);
1678 $block[] = new _DiffOp_Copy($context);
1680 $this->_block($x0, $ntrail +
$xi - $x0,
1681 $y0, $ntrail +
$yi - $y0,
1686 $context = $edit->orig
;
1689 if (! is_array($block)) {
1690 $context = array_slice($context, sizeof($context) - $nlead);
1691 $x0 = $xi - sizeof($context);
1692 $y0 = $yi - sizeof($context);
1695 $block[] = new _DiffOp_Copy($context);
1701 $xi +
= sizeof($edit->orig
);
1703 $yi +
= sizeof($edit->closing
);
1706 if (is_array($block))
1707 $this->_block($x0, $xi - $x0,
1711 $end = $this->_end_diff();
1712 wfProfileOut( __METHOD__
);
1716 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1717 wfProfileIn( __METHOD__
);
1718 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1719 foreach ($edits as $edit) {
1720 if ($edit->type
== 'copy')
1721 $this->_context($edit->orig
);
1722 elseif ($edit->type
== 'add')
1723 $this->_added($edit->closing
);
1724 elseif ($edit->type
== 'delete')
1725 $this->_deleted($edit->orig
);
1726 elseif ($edit->type
== 'change')
1727 $this->_changed($edit->orig
, $edit->closing
);
1729 trigger_error('Unknown edit type', E_USER_ERROR
);
1731 $this->_end_block();
1732 wfProfileOut( __METHOD__
);
1735 function _start_diff() {
1739 function _end_diff() {
1740 $val = ob_get_contents();
1745 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1747 $xbeg .= "," . ($xbeg +
$xlen - 1);
1749 $ybeg .= "," . ($ybeg +
$ylen - 1);
1751 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1754 function _start_block($header) {
1755 echo $header . "\n";
1758 function _end_block() {
1761 function _lines($lines, $prefix = ' ') {
1762 foreach ($lines as $line)
1763 echo "$prefix $line\n";
1766 function _context($lines) {
1767 $this->_lines($lines);
1770 function _added($lines) {
1771 $this->_lines($lines, '>');
1773 function _deleted($lines) {
1774 $this->_lines($lines, '<');
1777 function _changed($orig, $closing) {
1778 $this->_deleted($orig);
1780 $this->_added($closing);
1785 * A formatter that outputs unified diffs
1786 * @ingroup DifferenceEngine
1789 class UnifiedDiffFormatter
extends DiffFormatter
{
1790 var $leading_context_lines = 2;
1791 var $trailing_context_lines = 2;
1793 function _added($lines) {
1794 $this->_lines($lines, '+');
1796 function _deleted($lines) {
1797 $this->_lines($lines, '-');
1799 function _changed($orig, $closing) {
1800 $this->_deleted($orig);
1801 $this->_added($closing);
1803 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1804 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1809 * A pseudo-formatter that just passes along the Diff::$edits array
1810 * @ingroup DifferenceEngine
1812 class ArrayDiffFormatter
extends DiffFormatter
{
1813 function format($diff) {
1817 foreach($diff->edits
as $edit)
1818 switch($edit->type
) {
1820 foreach($edit->closing
as $l) {
1824 'newline' => $newline++
1829 foreach($edit->orig
as $l) {
1831 'action' => 'delete',
1833 'oldline' => $oldline++
,
1838 foreach($edit->orig
as $i => $l) {
1840 'action' => 'change',
1842 'new' => @$edit->closing
[$i],
1843 'oldline' => $oldline++
,
1844 'newline' => $newline++
,
1849 $oldline +
= count($edit->orig
);
1850 $newline +
= count($edit->orig
);
1857 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1861 define('NBSP', ' '); // iso-8859-x non-breaking space.
1866 * @ingroup DifferenceEngine
1868 class _HWLDF_WordAccumulator
{
1869 function _HWLDF_WordAccumulator () {
1870 $this->_lines
= array();
1876 function _flushGroup ($new_tag) {
1877 if ($this->_group
!== '') {
1878 if ($this->_tag
== 'ins')
1879 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1880 htmlspecialchars ( $this->_group
) . '</ins>';
1881 elseif ($this->_tag
== 'del')
1882 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1883 htmlspecialchars ( $this->_group
) . '</del>';
1885 $this->_line
.= htmlspecialchars ( $this->_group
);
1888 $this->_tag
= $new_tag;
1891 function _flushLine ($new_tag) {
1892 $this->_flushGroup($new_tag);
1893 if ($this->_line
!= '')
1894 array_push ( $this->_lines
, $this->_line
);
1896 # make empty lines visible by inserting an NBSP
1897 array_push ( $this->_lines
, NBSP
);
1901 function addWords ($words, $tag = '') {
1902 if ($tag != $this->_tag
)
1903 $this->_flushGroup($tag);
1905 foreach ($words as $word) {
1906 // new-line should only come as first char of word.
1909 if ($word[0] == "\n") {
1910 $this->_flushLine($tag);
1911 $word = substr($word, 1);
1913 assert(!strstr($word, "\n"));
1914 $this->_group
.= $word;
1918 function getLines() {
1919 $this->_flushLine('~done');
1920 return $this->_lines
;
1927 * @ingroup DifferenceEngine
1929 class WordLevelDiff
extends MappedDiff
{
1930 const MAX_LINE_LENGTH
= 10000;
1932 function WordLevelDiff ($orig_lines, $closing_lines) {
1933 wfProfileIn( __METHOD__
);
1935 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1936 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1938 $this->MappedDiff($orig_words, $closing_words,
1939 $orig_stripped, $closing_stripped);
1940 wfProfileOut( __METHOD__
);
1943 function _split($lines) {
1944 wfProfileIn( __METHOD__
);
1947 $stripped = array();
1949 foreach ( $lines as $line ) {
1950 # If the line is too long, just pretend the entire line is one big word
1951 # This prevents resource exhaustion problems
1958 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1960 $stripped[] = $line;
1963 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1966 $words = array_merge( $words, $m[0] );
1967 $stripped = array_merge( $stripped, $m[1] );
1971 wfProfileOut( __METHOD__
);
1972 return array($words, $stripped);
1976 wfProfileIn( __METHOD__
);
1977 $orig = new _HWLDF_WordAccumulator
;
1979 foreach ($this->edits
as $edit) {
1980 if ($edit->type
== 'copy')
1981 $orig->addWords($edit->orig
);
1982 elseif ($edit->orig
)
1983 $orig->addWords($edit->orig
, 'del');
1985 $lines = $orig->getLines();
1986 wfProfileOut( __METHOD__
);
1990 function closing () {
1991 wfProfileIn( __METHOD__
);
1992 $closing = new _HWLDF_WordAccumulator
;
1994 foreach ($this->edits
as $edit) {
1995 if ($edit->type
== 'copy')
1996 $closing->addWords($edit->closing
);
1997 elseif ($edit->closing
)
1998 $closing->addWords($edit->closing
, 'ins');
2000 $lines = $closing->getLines();
2001 wfProfileOut( __METHOD__
);
2007 * Wikipedia Table style diff formatter.
2010 * @ingroup DifferenceEngine
2012 class TableDiffFormatter
extends DiffFormatter
{
2013 function TableDiffFormatter() {
2014 $this->leading_context_lines
= 2;
2015 $this->trailing_context_lines
= 2;
2018 public static function escapeWhiteSpace( $msg ) {
2019 $msg = preg_replace( '/^ /m', ' ', $msg );
2020 $msg = preg_replace( '/ $/m', ' ', $msg );
2021 $msg = preg_replace( '/ /', ' ', $msg );
2025 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2026 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2027 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2031 function _start_block( $header ) {
2035 function _end_block() {
2038 function _lines( $lines, $prefix=' ', $color='white' ) {
2041 # HTML-escape parameter before calling this
2042 function addedLine( $line ) {
2043 return $this->wrapLine( '+', 'diff-addedline', $line );
2046 # HTML-escape parameter before calling this
2047 function deletedLine( $line ) {
2048 return $this->wrapLine( '-', 'diff-deletedline', $line );
2051 # HTML-escape parameter before calling this
2052 function contextLine( $line ) {
2053 return $this->wrapLine( ' ', 'diff-context', $line );
2056 private function wrapLine( $marker, $class, $line ) {
2057 if( $line !== '' ) {
2058 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2059 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2061 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2064 function emptyLine() {
2065 return '<td colspan="2"> </td>';
2068 function _added( $lines ) {
2069 foreach ($lines as $line) {
2070 echo '<tr>' . $this->emptyLine() .
2071 $this->addedLine( '<ins class="diffchange">' .
2072 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2076 function _deleted($lines) {
2077 foreach ($lines as $line) {
2078 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2079 htmlspecialchars ( $line ) . '</del>' ) .
2080 $this->emptyLine() . "</tr>\n";
2084 function _context( $lines ) {
2085 foreach ($lines as $line) {
2087 $this->contextLine( htmlspecialchars ( $line ) ) .
2088 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2092 function _changed( $orig, $closing ) {
2093 wfProfileIn( __METHOD__
);
2095 $diff = new WordLevelDiff( $orig, $closing );
2096 $del = $diff->orig();
2097 $add = $diff->closing();
2099 # Notice that WordLevelDiff returns HTML-escaped output.
2100 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2102 while ( $line = array_shift( $del ) ) {
2103 $aline = array_shift( $add );
2104 echo '<tr>' . $this->deletedLine( $line ) .
2105 $this->addedLine( $aline ) . "</tr>\n";
2107 foreach ($add as $line) { # If any leftovers
2108 echo '<tr>' . $this->emptyLine() .
2109 $this->addedLine( $line ) . "</tr>\n";
2111 wfProfileOut( __METHOD__
);