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
41 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false , $htmldiff = false) {
42 $this->mTitle
= $titleObj;
43 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
45 if ( 'prev' === $new ) {
46 # Show diff between revision $old and the previous one.
47 # Get previous one from DB.
49 $this->mNewid
= intval($old);
51 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
53 } elseif ( 'next' === $new ) {
54 # Show diff between revision $old and the previous one.
55 # Get previous one from DB.
57 $this->mOldid
= intval($old);
58 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
59 if ( false === $this->mNewid
) {
60 # if no result, NewId points to the newest old revision. The only newer
61 # revision is cur, which is "0".
66 $this->mOldid
= intval($old);
67 $this->mNewid
= intval($new);
69 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
70 $this->mRefreshCache
= $refreshCache;
71 $this->htmldiff
= $htmldiff;
78 function showDiffPage( $diffOnly = false ) {
79 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
80 wfProfileIn( __METHOD__
);
83 # If external diffs are enabled both globally and for the user,
84 # we'll use the application/x-external-editor interface to call
85 # an external diff tool like kompare, kdiff3, etc.
86 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
87 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
89 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
90 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
91 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
92 $special=$wgLang->getNsText(NS_SPECIAL
);
97 Script={$wgServer}{$wgScript}
98 Special namespace={$special}
112 $wgOut->setArticleFlag( false );
113 if ( ! $this->loadRevisionData() ) {
114 $t = $this->mTitle
->getPrefixedText();
115 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
116 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
117 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
118 wfProfileOut( __METHOD__
);
122 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
124 if ( $this->mNewRev
->isCurrent() ) {
125 $wgOut->setArticleFlag( true );
128 # mOldid is false if the difference engine is called with a "vague" query for
129 # a diff between a version V and its previous version V' AND the version V
130 # is the first version of that article. In that case, V' does not exist.
131 if ( $this->mOldid
=== false ) {
132 $this->showFirstRevision();
133 $this->renderNewRevision(); // should we respect $diffOnly here or not?
134 wfProfileOut( __METHOD__
);
138 $wgOut->suppressQuickbar();
140 $oldTitle = $this->mOldPage
->getPrefixedText();
141 $newTitle = $this->mNewPage
->getPrefixedText();
142 if( $oldTitle == $newTitle ) {
143 $wgOut->setPageTitle( $newTitle );
145 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
147 $wgOut->setSubtitle( wfMsg( 'difference' ) );
148 $wgOut->setRobotPolicy( 'noindex,nofollow' );
150 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
151 $wgOut->loginToUse();
153 wfProfileOut( __METHOD__
);
157 $sk = $wgUser->getSkin();
159 // Check if page is editable
160 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
161 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
162 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
167 // Prepare a change patrol link, if applicable
168 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
169 // If we've been given an explicit change identifier, use it; saves time
170 if( $this->mRcidMarkPatrolled
) {
171 $rcid = $this->mRcidMarkPatrolled
;
173 // Look for an unpatrolled change corresponding to this diff
174 $db = wfGetDB( DB_SLAVE
);
175 $change = RecentChange
::newFromConds(
177 // Add redundant user,timestamp condition so we can use the existing index
178 'rc_user_text' => $this->mNewRev
->getRawUserText(),
179 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
180 'rc_this_oldid' => $this->mNewid
,
181 'rc_last_oldid' => $this->mOldid
,
186 if( $change instanceof RecentChange
) {
187 $rcid = $change->mAttribs
['rc_id'];
195 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
197 wfMsgHtml( 'markaspatrolleddiff' ),
198 "action=markpatrolled&rcid={$rcid}"
207 $htmldiffarg = $this->htmlDiffArgument();
208 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
209 'diff=prev&oldid='.$this->mOldid
.$htmldiffarg, '', '', 'id="differences-prevlink"' );
210 if ( $this->mNewRev
->isCurrent() ) {
211 $nextlink = ' ';
213 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
214 'diff=next&oldid='.$this->mNewid
.$htmldiffarg, '', '', 'id="differences-nextlink"' );
220 if ($this->mOldRev
->mMinorEdit
== 1) {
221 $oldminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
224 if ($this->mNewRev
->mMinorEdit
== 1) {
225 $newminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
228 $rdel = ''; $ldel = '';
229 if( $wgUser->isAllowed( 'deleterevision' ) ) {
230 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
231 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
232 // If revision was hidden from sysops
233 $ldel = wfMsgHtml('rev-delundel');
235 $ldel = $sk->makeKnownLinkObj( $revdel,
236 wfMsgHtml('rev-delundel'),
237 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
238 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
239 // Bolden oversighted content
240 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
241 $ldel = "<strong>$ldel</strong>";
243 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
244 // We don't currently handle well changing the top revision's settings
245 if( $this->mNewRev
->isCurrent() ) {
246 // If revision was hidden from sysops
247 $rdel = wfMsgHtml('rev-delundel');
248 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
249 // If revision was hidden from sysops
250 $rdel = wfMsgHtml('rev-delundel');
252 $rdel = $sk->makeKnownLinkObj( $revdel,
253 wfMsgHtml('rev-delundel'),
254 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
255 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
256 // Bolden oversighted content
257 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
258 $rdel = "<strong>$rdel</strong>";
260 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
263 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
264 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
265 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
266 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
267 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
268 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
269 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
270 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
272 if( $wgEnableHtmlDiff && $this->htmldiff
) {
273 $multi = $this->getMultiNotice();
274 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
275 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
276 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
277 $this->renderHtmlDiff();
279 if($wgEnableHtmlDiff){
280 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
281 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
283 $this->showDiff( $oldHeader, $newHeader );
285 $this->renderNewRevision();
288 wfProfileOut( __METHOD__
);
292 * Show the new revision of the page.
294 function renderNewRevision() {
296 wfProfileIn( __METHOD__
);
298 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
299 #add deleted rev tag if needed
300 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
301 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
302 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
303 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
306 if( !$this->mNewRev
->isCurrent() ) {
307 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
310 $this->loadNewText();
311 if( is_object( $this->mNewRev
) ) {
312 $wgOut->setRevisionId( $this->mNewRev
->getId() );
315 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
316 // Stolen from Article::view --AG 2007-10-11
318 // Give hooks a chance to customise the output
319 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
320 // Wrap the whole lot in a <pre> and don't parse
322 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
323 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
324 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
325 $wgOut->addHtml( "\n</pre>\n" );
328 $wgOut->addWikiTextTidy( $this->mNewtext
);
330 if( !$this->mNewRev
->isCurrent() ) {
331 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
334 wfProfileOut( __METHOD__
);
338 function renderHtmlDiff() {
339 global $wgOut, $wgTitle, $wgParser;
340 wfProfileIn( __METHOD__
);
342 $this->showDiffStyle();
344 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
345 #add deleted rev tag if needed
346 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
347 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
348 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
349 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
352 if( !$this->mNewRev
->isCurrent() ) {
353 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
359 if( is_object( $this->mOldRev
) ) {
360 $wgOut->setRevisionId( $this->mOldRev
->getId() );
363 $popts = $wgOut->parserOptions();
364 $oldTidy = $popts->setTidy( true );
366 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
367 $popts->setTidy( $oldTidy );
370 //$wgOut->addParserOutputNoText( $parserOutput );
371 $oldHtml = $parserOutput->getText();
372 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
375 if( is_object( $this->mNewRev
) ) {
376 $wgOut->setRevisionId( $this->mNewRev
->getId() );
379 $popts = $wgOut->parserOptions();
380 $oldTidy = $popts->setTidy( true );
382 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
383 $popts->setTidy( $oldTidy );
385 $wgOut->addParserOutputNoText( $parserOutput );
386 $newHtml = $parserOutput->getText();
387 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
389 unset($parserOutput, $popts);
391 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
392 $differ->htmlDiff($oldHtml, $newHtml);
394 wfProfileOut( __METHOD__
);
398 * Show the first revision of an article. Uses normal diff headers in
399 * contrast to normal "old revision" display style.
401 function showFirstRevision() {
402 global $wgOut, $wgUser;
403 wfProfileIn( __METHOD__
);
405 # Get article text from the DB
407 if ( ! $this->loadNewText() ) {
408 $t = $this->mTitle
->getPrefixedText();
409 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
410 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
411 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
412 wfProfileOut( __METHOD__
);
415 if ( $this->mNewRev
->isCurrent() ) {
416 $wgOut->setArticleFlag( true );
419 # Check if user is allowed to look at this page. If not, bail out.
421 if ( !( $this->mTitle
->userCanRead() ) ) {
422 $wgOut->loginToUse();
424 wfProfileOut( __METHOD__
);
428 # Prepare the header box
430 $sk = $wgUser->getSkin();
432 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
433 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
434 $sk->revUserTools( $this->mNewRev
) . "<br />" .
435 $sk->revComment( $this->mNewRev
) . "<br />" .
436 $nextlink . "</div>\n";
438 $wgOut->addHTML( $header );
440 $wgOut->setSubtitle( wfMsg( 'difference' ) );
441 $wgOut->setRobotPolicy( 'noindex,nofollow' );
443 wfProfileOut( __METHOD__
);
446 function htmlDiffArgument(){
447 global $wgEnableHtmlDiff;
448 if($wgEnableHtmlDiff){
450 return '&htmldiff=1';
452 return '&htmldiff=0';
460 * Get the diff text, send it to $wgOut
461 * Returns false if the diff could not be generated, otherwise returns true
463 function showDiff( $otitle, $ntitle ) {
465 $diff = $this->getDiff( $otitle, $ntitle );
466 if ( $diff === false ) {
467 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
470 $this->showDiffStyle();
471 $wgOut->addHTML( $diff );
477 * Add style sheets and supporting JS for diff display.
479 function showDiffStyle() {
480 global $wgStylePath, $wgStyleVersion, $wgOut;
481 $wgOut->addStyle( 'common/diff.css' );
483 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
484 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
488 * Get complete diff table, including header
490 * @param Title $otitle Old title
491 * @param Title $ntitle New title
494 function getDiff( $otitle, $ntitle ) {
495 $body = $this->getDiffBody();
496 if ( $body === false ) {
499 $multi = $this->getMultiNotice();
500 return $this->addHeader( $body, $otitle, $ntitle, $multi );
505 * Get the diff table body, without header
509 function getDiffBody() {
511 wfProfileIn( __METHOD__
);
512 // Check if the diff should be hidden from this user
513 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
515 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
520 if ( $this->mOldid
&& $this->mNewid
) {
521 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
523 if ( !$this->mRefreshCache
) {
524 $difftext = $wgMemc->get( $key );
526 wfIncrStats( 'diff_cache_hit' );
527 $difftext = $this->localiseLineNumbers( $difftext );
528 $difftext .= "\n<!-- diff cache key $key -->\n";
529 wfProfileOut( __METHOD__
);
532 } // don't try to load but save the result
535 // Loadtext is permission safe, this just clears out the diff
536 if ( !$this->loadText() ) {
537 wfProfileOut( __METHOD__
);
541 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
543 // Save to cache for 7 days
544 if ( $key !== false && $difftext !== false ) {
545 wfIncrStats( 'diff_cache_miss' );
546 $wgMemc->set( $key, $difftext, 7*86400 );
548 wfIncrStats( 'diff_uncacheable' );
550 // Replace line numbers with the text in the user's language
551 if ( $difftext !== false ) {
552 $difftext = $this->localiseLineNumbers( $difftext );
554 wfProfileOut( __METHOD__
);
559 * Generate a diff, no caching
560 * $otext and $ntext must be already segmented
562 function generateDiffBody( $otext, $ntext ) {
563 global $wgExternalDiffEngine, $wgContLang;
565 $otext = str_replace( "\r\n", "\n", $otext );
566 $ntext = str_replace( "\r\n", "\n", $ntext );
568 if ( $wgExternalDiffEngine == 'wikidiff' ) {
569 # For historical reasons, external diff engine expects
570 # input text to be HTML-escaped already
571 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
572 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
573 if( !function_exists( 'wikidiff_do_diff' ) ) {
574 dl('php_wikidiff.so');
576 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
577 $this->debug( 'wikidiff1' );
580 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
581 # Better external diff engine, the 2 may some day be dropped
582 # This one does the escaping and segmenting itself
583 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
584 wfProfileIn( __METHOD__
. "-dl" );
585 @dl
('php_wikidiff2.so');
586 wfProfileOut( __METHOD__
. "-dl" );
588 if ( function_exists( 'wikidiff2_do_diff' ) ) {
589 wfProfileIn( 'wikidiff2_do_diff' );
590 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
591 $text .= $this->debug( 'wikidiff2' );
592 wfProfileOut( 'wikidiff2_do_diff' );
596 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
598 global $wgTmpDirectory;
599 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
600 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
602 $tempFile1 = fopen( $tempName1, "w" );
604 wfProfileOut( __METHOD__
);
607 $tempFile2 = fopen( $tempName2, "w" );
609 wfProfileOut( __METHOD__
);
612 fwrite( $tempFile1, $otext );
613 fwrite( $tempFile2, $ntext );
614 fclose( $tempFile1 );
615 fclose( $tempFile2 );
616 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
617 wfProfileIn( __METHOD__
. "-shellexec" );
618 $difftext = wfShellExec( $cmd );
619 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
620 wfProfileOut( __METHOD__
. "-shellexec" );
621 unlink( $tempName1 );
622 unlink( $tempName2 );
627 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
628 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
629 $diffs = new Diff( $ota, $nta );
630 $formatter = new TableDiffFormatter();
631 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
636 * Generate a debug comment indicating diff generating time,
637 * server node, and generator backend.
639 protected function debug( $generator="internal" ) {
640 global $wgShowHostnames, $wgNodeName;
641 $data = array( $generator );
642 if( $wgShowHostnames ) {
643 $data[] = $wgNodeName;
645 $data[] = wfTimestamp( TS_DB
);
646 return "<!-- diff generator: " .
655 * Replace line numbers with the text in the user's language
657 function localiseLineNumbers( $text ) {
658 return preg_replace_callback( '/<!--LINE (\d+)-->/',
659 array( &$this, 'localiseLineNumbersCb' ), $text );
662 function localiseLineNumbersCb( $matches ) {
664 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
669 * If there are revisions between the ones being compared, return a note saying so.
671 function getMultiNotice() {
672 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
675 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
676 // Comparing two different pages? Count would be meaningless.
680 $oldid = $this->mOldRev
->getId();
681 $newid = $this->mNewRev
->getId();
682 if ( $oldid > $newid ) {
683 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
686 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
690 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
695 * Add the header to a diff body
697 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
700 <col class='diff-marker' />
701 <col class='diff-content' />
702 <col class='diff-marker' />
703 <col class='diff-content' />
705 <td colspan='2' class='diff-otitle'>{$otitle}</td>
706 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
711 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
713 return $header . $diff . "</table>";
717 * Use specified text instead of loading from the database
719 function setText( $oldText, $newText ) {
720 $this->mOldtext
= $oldText;
721 $this->mNewtext
= $newText;
722 $this->mTextLoaded
= 2;
726 * Load revision metadata for the specified articles. If newid is 0, then compare
727 * the old article in oldid to the current article; if oldid is 0, then
728 * compare the current article to the immediately previous one (ignoring the
731 * If oldid is false, leave the corresponding revision object set
732 * to false. This is impossible via ordinary user input, and is provided for
735 function loadRevisionData() {
737 if ( $this->mRevisionsLoaded
) {
740 // Whether it succeeds or fails, we don't want to try again
741 $this->mRevisionsLoaded
= true;
744 // Load the new revision object
745 $this->mNewRev
= $this->mNewid
746 ? Revision
::newFromId( $this->mNewid
)
747 : Revision
::newFromTitle( $this->mTitle
);
748 if( !$this->mNewRev
instanceof Revision
)
751 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
752 $this->mNewid
= $this->mNewRev
->getId();
754 // Check if page is editable
755 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
757 // Set assorted variables
758 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
759 $this->mNewPage
= $this->mNewRev
->getTitle();
760 if( $this->mNewRev
->isCurrent() ) {
761 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
762 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
763 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
765 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
766 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
769 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
770 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
771 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
773 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
774 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
776 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
777 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
778 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
779 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
782 // Load the old revision object
783 $this->mOldRev
= false;
784 if( $this->mOldid
) {
785 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
786 } elseif ( $this->mOldid
=== 0 ) {
787 $rev = $this->mNewRev
->getPrevious();
789 $this->mOldid
= $rev->getId();
790 $this->mOldRev
= $rev;
792 // No previous revision; mark to show as first-version only.
793 $this->mOldid
= false;
794 $this->mOldRev
= false;
796 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
798 if( is_null( $this->mOldRev
) ) {
802 if ( $this->mOldRev
) {
803 $this->mOldPage
= $this->mOldRev
->getTitle();
805 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
806 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
807 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
808 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
810 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
811 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
812 // Add an "undo" link
813 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
814 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
815 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
818 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
819 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
820 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
821 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
829 * Load the text of the revisions, as well as revision data.
831 function loadText() {
832 if ( $this->mTextLoaded
== 2 ) {
835 // Whether it succeeds or fails, we don't want to try again
836 $this->mTextLoaded
= 2;
839 if ( !$this->loadRevisionData() ) {
842 if ( $this->mOldRev
) {
843 $this->mOldtext
= $this->mOldRev
->revText();
844 if ( $this->mOldtext
=== false ) {
848 if ( $this->mNewRev
) {
849 $this->mNewtext
= $this->mNewRev
->revText();
850 if ( $this->mNewtext
=== false ) {
858 * Load the text of the new revision, not the old one
860 function loadNewText() {
861 if ( $this->mTextLoaded
>= 1 ) {
864 $this->mTextLoaded
= 1;
866 if ( !$this->loadRevisionData() ) {
869 $this->mNewtext
= $this->mNewRev
->getText();
876 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
878 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
879 // You may copy this code freely under the conditions of the GPL.
882 define('USE_ASSERTS', function_exists('assert'));
887 * @ingroup DifferenceEngine
895 trigger_error('pure virtual', E_USER_ERROR
);
899 return $this->orig ?
sizeof($this->orig
) : 0;
902 function nclosing() {
903 return $this->closing ?
sizeof($this->closing
) : 0;
910 * @ingroup DifferenceEngine
912 class _DiffOp_Copy
extends _DiffOp
{
915 function _DiffOp_Copy ($orig, $closing = false) {
916 if (!is_array($closing))
919 $this->closing
= $closing;
923 return new _DiffOp_Copy($this->closing
, $this->orig
);
930 * @ingroup DifferenceEngine
932 class _DiffOp_Delete
extends _DiffOp
{
933 var $type = 'delete';
935 function _DiffOp_Delete ($lines) {
936 $this->orig
= $lines;
937 $this->closing
= false;
941 return new _DiffOp_Add($this->orig
);
948 * @ingroup DifferenceEngine
950 class _DiffOp_Add
extends _DiffOp
{
953 function _DiffOp_Add ($lines) {
954 $this->closing
= $lines;
959 return new _DiffOp_Delete($this->closing
);
966 * @ingroup DifferenceEngine
968 class _DiffOp_Change
extends _DiffOp
{
969 var $type = 'change';
971 function _DiffOp_Change ($orig, $closing) {
973 $this->closing
= $closing;
977 return new _DiffOp_Change($this->closing
, $this->orig
);
982 * Class used internally by Diff to actually compute the diffs.
984 * The algorithm used here is mostly lifted from the perl module
985 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
986 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
988 * More ideas are taken from:
989 * http://www.ics.uci.edu/~eppstein/161/960229.html
991 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
992 * diffutils-2.7, which can be found at:
993 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
995 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
998 * Line length limits for robustness added by Tim Starling, 2005-08-31
999 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1001 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1003 * @ingroup DifferenceEngine
1007 const MAX_XREF_LENGTH
= 10000;
1009 function diff ($from_lines, $to_lines){
1010 wfProfileIn( __METHOD__
);
1012 // Diff and store locally
1013 $this->diff_local($from_lines, $to_lines);
1015 // Merge edits when possible
1016 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1017 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1019 // Compute the edit operations.
1020 $n_from = sizeof($from_lines);
1021 $n_to = sizeof($to_lines);
1025 while ($xi < $n_from ||
$yi < $n_to) {
1026 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1027 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1029 // Skip matching "snake".
1031 while ( $xi < $n_from && $yi < $n_to
1032 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1033 $copy[] = $from_lines[$xi++
];
1037 $edits[] = new _DiffOp_Copy($copy);
1039 // Find deletes & adds.
1041 while ($xi < $n_from && $this->xchanged
[$xi])
1042 $delete[] = $from_lines[$xi++
];
1045 while ($yi < $n_to && $this->ychanged
[$yi])
1046 $add[] = $to_lines[$yi++
];
1048 if ($delete && $add)
1049 $edits[] = new _DiffOp_Change($delete, $add);
1051 $edits[] = new _DiffOp_Delete($delete);
1053 $edits[] = new _DiffOp_Add($add);
1055 wfProfileOut( __METHOD__
);
1059 function diff_local ($from_lines, $to_lines) {
1060 global $wgExternalDiffEngine;
1061 wfProfileIn( __METHOD__
);
1063 if($wgExternalDiffEngine == 'wikidiff3'){
1065 $wikidiff3 = new WikiDiff3();
1066 $wikidiff3->diff($from_lines, $to_lines);
1067 $this->xchanged
= $wikidiff3->removed
;
1068 $this->ychanged
= $wikidiff3->added
;
1072 $n_from = sizeof($from_lines);
1073 $n_to = sizeof($to_lines);
1074 $this->xchanged
= $this->ychanged
= array();
1075 $this->xv
= $this->yv
= array();
1076 $this->xind
= $this->yind
= array();
1078 unset($this->in_seq
);
1081 // Skip leading common lines.
1082 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1083 if ($from_lines[$skip] !== $to_lines[$skip])
1085 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1087 // Skip trailing common lines.
1088 $xi = $n_from; $yi = $n_to;
1089 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1090 if ($from_lines[$xi] !== $to_lines[$yi])
1092 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1095 // Ignore lines which do not exist in both files.
1096 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1097 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1100 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1101 $line = $to_lines[$yi];
1102 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1104 $yhash[$this->_line_hash($line)] = 1;
1105 $this->yv
[] = $line;
1106 $this->yind
[] = $yi;
1108 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1109 $line = $from_lines[$xi];
1110 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1112 $this->xv
[] = $line;
1113 $this->xind
[] = $xi;
1117 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1119 wfProfileOut( __METHOD__
);
1123 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1125 function _line_hash( $line ) {
1126 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1127 return md5( $line );
1133 /* Divide the Largest Common Subsequence (LCS) of the sequences
1134 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1137 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1138 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1139 * sub sequences. The first sub-sequence is contained in [X0, X1),
1140 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1141 * that (X0, Y0) == (XOFF, YOFF) and
1142 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1144 * This function assumes that the first lines of the specified portions
1145 * of the two files do not match, and likewise that the last lines do not
1146 * match. The caller must trim matching lines from the beginning and end
1147 * of the portions it is going to specify.
1149 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1152 if ($xlim - $xoff > $ylim - $yoff) {
1153 // Things seems faster (I'm not sure I understand why)
1154 // when the shortest sequence in X.
1156 list ($xoff, $xlim, $yoff, $ylim)
1157 = array( $yoff, $ylim, $xoff, $xlim);
1161 for ($i = $ylim - 1; $i >= $yoff; $i--)
1162 $ymatches[$this->xv
[$i]][] = $i;
1164 for ($i = $ylim - 1; $i >= $yoff; $i--)
1165 $ymatches[$this->yv
[$i]][] = $i;
1168 $this->seq
[0]= $yoff - 1;
1169 $this->in_seq
= array();
1170 $ymids[0] = array();
1172 $numer = $xlim - $xoff +
$nchunks - 1;
1174 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1176 for ($i = 0; $i <= $this->lcs
; $i++
)
1177 $ymids[$i][$chunk-1] = $this->seq
[$i];
1179 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1180 for ( ; $x < $x1; $x++
) {
1181 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1182 if (empty($ymatches[$line]))
1184 $matches = $ymatches[$line];
1186 while (list ($junk, $y) = each($matches))
1187 if (empty($this->in_seq
[$y])) {
1188 $k = $this->_lcs_pos($y);
1189 USE_ASSERTS
&& assert($k > 0);
1190 $ymids[$k] = $ymids[$k-1];
1193 while (list ( /* $junk */, $y) = each($matches)) {
1194 if ($y > $this->seq
[$k-1]) {
1195 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1196 // Optimization: this is a common case:
1197 // next match is just replacing previous match.
1198 $this->in_seq
[$this->seq
[$k]] = false;
1199 $this->seq
[$k] = $y;
1200 $this->in_seq
[$y] = 1;
1201 } else if (empty($this->in_seq
[$y])) {
1202 $k = $this->_lcs_pos($y);
1203 USE_ASSERTS
&& assert($k > 0);
1204 $ymids[$k] = $ymids[$k-1];
1210 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1211 $ymid = $ymids[$this->lcs
];
1212 for ($n = 0; $n < $nchunks - 1; $n++
) {
1213 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1214 $y1 = $ymid[$n] +
1;
1215 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1217 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1219 return array($this->lcs
, $seps);
1222 function _lcs_pos ($ypos) {
1224 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1225 $this->seq
[++
$this->lcs
] = $ypos;
1226 $this->in_seq
[$ypos] = 1;
1231 while ($beg < $end) {
1232 $mid = (int)(($beg +
$end) / 2);
1233 if ( $ypos > $this->seq
[$mid] )
1239 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1241 $this->in_seq
[$this->seq
[$end]] = false;
1242 $this->seq
[$end] = $ypos;
1243 $this->in_seq
[$ypos] = 1;
1247 /* Find LCS of two sequences.
1249 * The results are recorded in the vectors $this->{x,y}changed[], by
1250 * storing a 1 in the element for each line that is an insertion
1251 * or deletion (ie. is not in the LCS).
1253 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1255 * Note that XLIM, YLIM are exclusive bounds.
1256 * All line numbers are origin-0 and discarded lines are not counted.
1258 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1259 // Slide down the bottom initial diagonal.
1260 while ($xoff < $xlim && $yoff < $ylim
1261 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1266 // Slide up the top initial diagonal.
1267 while ($xlim > $xoff && $ylim > $yoff
1268 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1273 if ($xoff == $xlim ||
$yoff == $ylim)
1276 // This is ad hoc but seems to work well.
1277 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1278 //$nchunks = max(2,min(8,(int)$nchunks));
1279 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1281 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1285 // X and Y sequences have no common subsequence:
1286 // mark all changed.
1287 while ($yoff < $ylim)
1288 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1289 while ($xoff < $xlim)
1290 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1292 // Use the partitions to split this problem into subproblems.
1295 while ($pt2 = next($seps)) {
1296 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1302 /* Adjust inserts/deletes of identical lines to join changes
1303 * as much as possible.
1305 * We do something when a run of changed lines include a
1306 * line at one end and has an excluded, identical line at the other.
1307 * We are free to choose which identical line is included.
1308 * `compareseq' usually chooses the one at the beginning,
1309 * but usually it is cleaner to consider the following identical line
1310 * to be the "change".
1312 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1314 function _shift_boundaries ($lines, &$changed, $other_changed) {
1315 wfProfileIn( __METHOD__
);
1319 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1320 $len = sizeof($lines);
1321 $other_len = sizeof($other_changed);
1325 * Scan forwards to find beginning of another run of changes.
1326 * Also keep track of the corresponding point in the other file.
1328 * Throughout this code, $i and $j are adjusted together so that
1329 * the first $i elements of $changed and the first $j elements
1330 * of $other_changed both contain the same number of zeros
1331 * (unchanged lines).
1332 * Furthermore, $j is always kept so that $j == $other_len or
1333 * $other_changed[$j] == false.
1335 while ($j < $other_len && $other_changed[$j])
1338 while ($i < $len && ! $changed[$i]) {
1339 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1341 while ($j < $other_len && $other_changed[$j])
1350 // Find the end of this run of changes.
1351 while (++
$i < $len && $changed[$i])
1356 * Record the length of this run of changes, so that
1357 * we can later determine whether the run has grown.
1359 $runlength = $i - $start;
1362 * Move the changed region back, so long as the
1363 * previous unchanged line matches the last changed one.
1364 * This merges with previous changed regions.
1366 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1367 $changed[--$start] = 1;
1368 $changed[--$i] = false;
1369 while ($start > 0 && $changed[$start - 1])
1371 USE_ASSERTS
&& assert('$j > 0');
1372 while ($other_changed[--$j])
1374 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1378 * Set CORRESPONDING to the end of the changed run, at the last
1379 * point where it corresponds to a changed run in the other file.
1380 * CORRESPONDING == LEN means no such point has been found.
1382 $corresponding = $j < $other_len ?
$i : $len;
1385 * Move the changed region forward, so long as the
1386 * first changed line matches the following unchanged one.
1387 * This merges with following changed regions.
1388 * Do this second, so that if there are no merges,
1389 * the changed region is moved forward as far as possible.
1391 while ($i < $len && $lines[$start] == $lines[$i]) {
1392 $changed[$start++
] = false;
1394 while ($i < $len && $changed[$i])
1397 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1399 if ($j < $other_len && $other_changed[$j]) {
1400 $corresponding = $i;
1401 while ($j < $other_len && $other_changed[$j])
1405 } while ($runlength != $i - $start);
1408 * If possible, move the fully-merged run of changes
1409 * back to a corresponding run in the other file.
1411 while ($corresponding < $i) {
1412 $changed[--$start] = 1;
1414 USE_ASSERTS
&& assert('$j > 0');
1415 while ($other_changed[--$j])
1417 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1420 wfProfileOut( __METHOD__
);
1425 * Class representing a 'diff' between two sequences of strings.
1428 * @ingroup DifferenceEngine
1436 * Computes diff between sequences of strings.
1438 * @param $from_lines array An array of strings.
1439 * (Typically these are lines from a file.)
1440 * @param $to_lines array An array of strings.
1442 function Diff($from_lines, $to_lines) {
1443 $eng = new _DiffEngine
;
1444 $this->edits
= $eng->diff($from_lines, $to_lines);
1445 //$this->_check($from_lines, $to_lines);
1449 * Compute reversed Diff.
1453 * $diff = new Diff($lines1, $lines2);
1454 * $rev = $diff->reverse();
1455 * @return object A Diff object representing the inverse of the
1458 function reverse () {
1460 $rev->edits
= array();
1461 foreach ($this->edits
as $edit) {
1462 $rev->edits
[] = $edit->reverse();
1468 * Check for empty diff.
1470 * @return bool True iff two sequences were identical.
1472 function isEmpty () {
1473 foreach ($this->edits
as $edit) {
1474 if ($edit->type
!= 'copy')
1481 * Compute the length of the Longest Common Subsequence (LCS).
1483 * This is mostly for diagnostic purposed.
1485 * @return int The length of the LCS.
1489 foreach ($this->edits
as $edit) {
1490 if ($edit->type
== 'copy')
1491 $lcs +
= sizeof($edit->orig
);
1497 * Get the original set of lines.
1499 * This reconstructs the $from_lines parameter passed to the
1502 * @return array The original sequence of strings.
1507 foreach ($this->edits
as $edit) {
1509 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1515 * Get the closing set of lines.
1517 * This reconstructs the $to_lines parameter passed to the
1520 * @return array The sequence of strings.
1522 function closing() {
1525 foreach ($this->edits
as $edit) {
1527 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1533 * Check a Diff for validity.
1535 * This is here only for debugging purposes.
1537 function _check ($from_lines, $to_lines) {
1538 wfProfileIn( __METHOD__
);
1539 if (serialize($from_lines) != serialize($this->orig()))
1540 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1541 if (serialize($to_lines) != serialize($this->closing()))
1542 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1544 $rev = $this->reverse();
1545 if (serialize($to_lines) != serialize($rev->orig()))
1546 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1547 if (serialize($from_lines) != serialize($rev->closing()))
1548 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1552 foreach ($this->edits
as $edit) {
1553 if ( $prevtype == $edit->type
)
1554 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1555 $prevtype = $edit->type
;
1558 $lcs = $this->lcs();
1559 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1560 wfProfileOut( __METHOD__
);
1565 * @todo document, bad name.
1567 * @ingroup DifferenceEngine
1569 class MappedDiff
extends Diff
1574 * Computes diff between sequences of strings.
1576 * This can be used to compute things like
1577 * case-insensitve diffs, or diffs which ignore
1578 * changes in white-space.
1580 * @param $from_lines array An array of strings.
1581 * (Typically these are lines from a file.)
1583 * @param $to_lines array An array of strings.
1585 * @param $mapped_from_lines array This array should
1586 * have the same size number of elements as $from_lines.
1587 * The elements in $mapped_from_lines and
1588 * $mapped_to_lines are what is actually compared
1589 * when computing the diff.
1591 * @param $mapped_to_lines array This array should
1592 * have the same number of elements as $to_lines.
1594 function MappedDiff($from_lines, $to_lines,
1595 $mapped_from_lines, $mapped_to_lines) {
1596 wfProfileIn( __METHOD__
);
1598 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1599 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1601 $this->Diff($mapped_from_lines, $mapped_to_lines);
1604 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1605 $orig = &$this->edits
[$i]->orig
;
1606 if (is_array($orig)) {
1607 $orig = array_slice($from_lines, $xi, sizeof($orig));
1608 $xi +
= sizeof($orig);
1611 $closing = &$this->edits
[$i]->closing
;
1612 if (is_array($closing)) {
1613 $closing = array_slice($to_lines, $yi, sizeof($closing));
1614 $yi +
= sizeof($closing);
1617 wfProfileOut( __METHOD__
);
1622 * A class to format Diffs
1624 * This class formats the diff in classic diff format.
1625 * It is intended that this class be customized via inheritance,
1626 * to obtain fancier outputs.
1629 * @ingroup DifferenceEngine
1631 class DiffFormatter
{
1633 * Number of leading context "lines" to preserve.
1635 * This should be left at zero for this class, but subclasses
1636 * may want to set this to other values.
1638 var $leading_context_lines = 0;
1641 * Number of trailing context "lines" to preserve.
1643 * This should be left at zero for this class, but subclasses
1644 * may want to set this to other values.
1646 var $trailing_context_lines = 0;
1651 * @param $diff object A Diff object.
1652 * @return string The formatted output.
1654 function format($diff) {
1655 wfProfileIn( __METHOD__
);
1661 $nlead = $this->leading_context_lines
;
1662 $ntrail = $this->trailing_context_lines
;
1664 $this->_start_diff();
1666 foreach ($diff->edits
as $edit) {
1667 if ($edit->type
== 'copy') {
1668 if (is_array($block)) {
1669 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1674 $context = array_slice($edit->orig
, 0, $ntrail);
1675 $block[] = new _DiffOp_Copy($context);
1677 $this->_block($x0, $ntrail +
$xi - $x0,
1678 $y0, $ntrail +
$yi - $y0,
1683 $context = $edit->orig
;
1686 if (! is_array($block)) {
1687 $context = array_slice($context, sizeof($context) - $nlead);
1688 $x0 = $xi - sizeof($context);
1689 $y0 = $yi - sizeof($context);
1692 $block[] = new _DiffOp_Copy($context);
1698 $xi +
= sizeof($edit->orig
);
1700 $yi +
= sizeof($edit->closing
);
1703 if (is_array($block))
1704 $this->_block($x0, $xi - $x0,
1708 $end = $this->_end_diff();
1709 wfProfileOut( __METHOD__
);
1713 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1714 wfProfileIn( __METHOD__
);
1715 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1716 foreach ($edits as $edit) {
1717 if ($edit->type
== 'copy')
1718 $this->_context($edit->orig
);
1719 elseif ($edit->type
== 'add')
1720 $this->_added($edit->closing
);
1721 elseif ($edit->type
== 'delete')
1722 $this->_deleted($edit->orig
);
1723 elseif ($edit->type
== 'change')
1724 $this->_changed($edit->orig
, $edit->closing
);
1726 trigger_error('Unknown edit type', E_USER_ERROR
);
1728 $this->_end_block();
1729 wfProfileOut( __METHOD__
);
1732 function _start_diff() {
1736 function _end_diff() {
1737 $val = ob_get_contents();
1742 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1744 $xbeg .= "," . ($xbeg +
$xlen - 1);
1746 $ybeg .= "," . ($ybeg +
$ylen - 1);
1748 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1751 function _start_block($header) {
1752 echo $header . "\n";
1755 function _end_block() {
1758 function _lines($lines, $prefix = ' ') {
1759 foreach ($lines as $line)
1760 echo "$prefix $line\n";
1763 function _context($lines) {
1764 $this->_lines($lines);
1767 function _added($lines) {
1768 $this->_lines($lines, '>');
1770 function _deleted($lines) {
1771 $this->_lines($lines, '<');
1774 function _changed($orig, $closing) {
1775 $this->_deleted($orig);
1777 $this->_added($closing);
1782 * A formatter that outputs unified diffs
1783 * @ingroup DifferenceEngine
1786 class UnifiedDiffFormatter
extends DiffFormatter
{
1787 var $leading_context_lines = 2;
1788 var $trailing_context_lines = 2;
1790 function _added($lines) {
1791 $this->_lines($lines, '+');
1793 function _deleted($lines) {
1794 $this->_lines($lines, '-');
1796 function _changed($orig, $closing) {
1797 $this->_deleted($orig);
1798 $this->_added($closing);
1800 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1801 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1806 * A pseudo-formatter that just passes along the Diff::$edits array
1807 * @ingroup DifferenceEngine
1809 class ArrayDiffFormatter
extends DiffFormatter
{
1810 function format($diff) {
1814 foreach($diff->edits
as $edit)
1815 switch($edit->type
) {
1817 foreach($edit->closing
as $l) {
1821 'newline' => $newline++
1826 foreach($edit->orig
as $l) {
1828 'action' => 'delete',
1830 'oldline' => $oldline++
,
1835 foreach($edit->orig
as $i => $l) {
1837 'action' => 'change',
1839 'new' => @$edit->closing
[$i],
1840 'oldline' => $oldline++
,
1841 'newline' => $newline++
,
1846 $oldline +
= count($edit->orig
);
1847 $newline +
= count($edit->orig
);
1854 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1858 define('NBSP', ' '); // iso-8859-x non-breaking space.
1863 * @ingroup DifferenceEngine
1865 class _HWLDF_WordAccumulator
{
1866 function _HWLDF_WordAccumulator () {
1867 $this->_lines
= array();
1873 function _flushGroup ($new_tag) {
1874 if ($this->_group
!== '') {
1875 if ($this->_tag
== 'ins')
1876 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1877 htmlspecialchars ( $this->_group
) . '</ins>';
1878 elseif ($this->_tag
== 'del')
1879 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1880 htmlspecialchars ( $this->_group
) . '</del>';
1882 $this->_line
.= htmlspecialchars ( $this->_group
);
1885 $this->_tag
= $new_tag;
1888 function _flushLine ($new_tag) {
1889 $this->_flushGroup($new_tag);
1890 if ($this->_line
!= '')
1891 array_push ( $this->_lines
, $this->_line
);
1893 # make empty lines visible by inserting an NBSP
1894 array_push ( $this->_lines
, NBSP
);
1898 function addWords ($words, $tag = '') {
1899 if ($tag != $this->_tag
)
1900 $this->_flushGroup($tag);
1902 foreach ($words as $word) {
1903 // new-line should only come as first char of word.
1906 if ($word[0] == "\n") {
1907 $this->_flushLine($tag);
1908 $word = substr($word, 1);
1910 assert(!strstr($word, "\n"));
1911 $this->_group
.= $word;
1915 function getLines() {
1916 $this->_flushLine('~done');
1917 return $this->_lines
;
1924 * @ingroup DifferenceEngine
1926 class WordLevelDiff
extends MappedDiff
{
1927 const MAX_LINE_LENGTH
= 10000;
1929 function WordLevelDiff ($orig_lines, $closing_lines) {
1930 wfProfileIn( __METHOD__
);
1932 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1933 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1935 $this->MappedDiff($orig_words, $closing_words,
1936 $orig_stripped, $closing_stripped);
1937 wfProfileOut( __METHOD__
);
1940 function _split($lines) {
1941 wfProfileIn( __METHOD__
);
1944 $stripped = array();
1946 foreach ( $lines as $line ) {
1947 # If the line is too long, just pretend the entire line is one big word
1948 # This prevents resource exhaustion problems
1955 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1957 $stripped[] = $line;
1960 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1963 $words = array_merge( $words, $m[0] );
1964 $stripped = array_merge( $stripped, $m[1] );
1968 wfProfileOut( __METHOD__
);
1969 return array($words, $stripped);
1973 wfProfileIn( __METHOD__
);
1974 $orig = new _HWLDF_WordAccumulator
;
1976 foreach ($this->edits
as $edit) {
1977 if ($edit->type
== 'copy')
1978 $orig->addWords($edit->orig
);
1979 elseif ($edit->orig
)
1980 $orig->addWords($edit->orig
, 'del');
1982 $lines = $orig->getLines();
1983 wfProfileOut( __METHOD__
);
1987 function closing () {
1988 wfProfileIn( __METHOD__
);
1989 $closing = new _HWLDF_WordAccumulator
;
1991 foreach ($this->edits
as $edit) {
1992 if ($edit->type
== 'copy')
1993 $closing->addWords($edit->closing
);
1994 elseif ($edit->closing
)
1995 $closing->addWords($edit->closing
, 'ins');
1997 $lines = $closing->getLines();
1998 wfProfileOut( __METHOD__
);
2004 * Wikipedia Table style diff formatter.
2007 * @ingroup DifferenceEngine
2009 class TableDiffFormatter
extends DiffFormatter
{
2010 function TableDiffFormatter() {
2011 $this->leading_context_lines
= 2;
2012 $this->trailing_context_lines
= 2;
2015 public static function escapeWhiteSpace( $msg ) {
2016 $msg = preg_replace( '/^ /m', ' ', $msg );
2017 $msg = preg_replace( '/ $/m', ' ', $msg );
2018 $msg = preg_replace( '/ /', ' ', $msg );
2022 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2023 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2024 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2028 function _start_block( $header ) {
2032 function _end_block() {
2035 function _lines( $lines, $prefix=' ', $color='white' ) {
2038 # HTML-escape parameter before calling this
2039 function addedLine( $line ) {
2040 return $this->wrapLine( '+', 'diff-addedline', $line );
2043 # HTML-escape parameter before calling this
2044 function deletedLine( $line ) {
2045 return $this->wrapLine( '-', 'diff-deletedline', $line );
2048 # HTML-escape parameter before calling this
2049 function contextLine( $line ) {
2050 return $this->wrapLine( ' ', 'diff-context', $line );
2053 private function wrapLine( $marker, $class, $line ) {
2054 if( $line !== '' ) {
2055 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2056 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2058 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2061 function emptyLine() {
2062 return '<td colspan="2"> </td>';
2065 function _added( $lines ) {
2066 foreach ($lines as $line) {
2067 echo '<tr>' . $this->emptyLine() .
2068 $this->addedLine( '<ins class="diffchange">' .
2069 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2073 function _deleted($lines) {
2074 foreach ($lines as $line) {
2075 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2076 htmlspecialchars ( $line ) . '</del>' ) .
2077 $this->emptyLine() . "</tr>\n";
2081 function _context( $lines ) {
2082 foreach ($lines as $line) {
2084 $this->contextLine( htmlspecialchars ( $line ) ) .
2085 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2089 function _changed( $orig, $closing ) {
2090 wfProfileIn( __METHOD__
);
2092 $diff = new WordLevelDiff( $orig, $closing );
2093 $del = $diff->orig();
2094 $add = $diff->closing();
2096 # Notice that WordLevelDiff returns HTML-escaped output.
2097 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2099 while ( $line = array_shift( $del ) ) {
2100 $aline = array_shift( $add );
2101 echo '<tr>' . $this->deletedLine( $line ) .
2102 $this->addedLine( $aline ) . "</tr>\n";
2104 foreach ($add as $line) { # If any leftovers
2105 echo '<tr>' . $this->emptyLine() .
2106 $this->addedLine( $line ) . "</tr>\n";
2108 wfProfileOut( __METHOD__
);