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.
50 $this->mNewid
= intval($old);
52 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
54 } elseif ( 'next' === $new ) {
55 # Show diff between revision $old and the previous one.
56 # Get previous one from DB.
58 $this->mOldid
= intval($old);
59 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
60 if ( false === $this->mNewid
) {
61 # if no result, NewId points to the newest old revision. The only newer
62 # revision is cur, which is "0".
67 $this->mOldid
= intval($old);
68 $this->mNewid
= intval($new);
70 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
71 $this->mRefreshCache
= $refreshCache;
72 $this->htmldiff
= $htmldiff;
79 function showDiffPage( $diffOnly = false ) {
80 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
81 wfProfileIn( __METHOD__
);
84 # If external diffs are enabled both globally and for the user,
85 # we'll use the application/x-external-editor interface to call
86 # an external diff tool like kompare, kdiff3, etc.
87 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
88 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
90 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
91 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
92 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
93 $special=$wgLang->getNsText(NS_SPECIAL
);
98 Script={$wgServer}{$wgScript}
99 Special namespace={$special}
113 $wgOut->setArticleFlag( false );
114 if ( ! $this->loadRevisionData() ) {
115 $t = $this->mTitle
->getPrefixedText();
116 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
117 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
118 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
119 wfProfileOut( __METHOD__
);
123 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
125 if ( $this->mNewRev
->isCurrent() ) {
126 $wgOut->setArticleFlag( true );
129 # mOldid is false if the difference engine is called with a "vague" query for
130 # a diff between a version V and its previous version V' AND the version V
131 # is the first version of that article. In that case, V' does not exist.
132 if ( $this->mOldid
=== false ) {
133 $this->showFirstRevision();
134 $this->renderNewRevision(); // should we respect $diffOnly here or not?
135 wfProfileOut( __METHOD__
);
139 $wgOut->suppressQuickbar();
141 $oldTitle = $this->mOldPage
->getPrefixedText();
142 $newTitle = $this->mNewPage
->getPrefixedText();
143 if( $oldTitle == $newTitle ) {
144 $wgOut->setPageTitle( $newTitle );
146 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
148 $wgOut->setSubtitle( wfMsg( 'difference' ) );
149 $wgOut->setRobotPolicy( 'noindex,nofollow' );
151 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
152 $wgOut->loginToUse();
154 wfProfileOut( __METHOD__
);
158 $sk = $wgUser->getSkin();
160 // Check if page is editable
161 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
162 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
163 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
168 // Prepare a change patrol link, if applicable
169 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
170 // If we've been given an explicit change identifier, use it; saves time
171 if( $this->mRcidMarkPatrolled
) {
172 $rcid = $this->mRcidMarkPatrolled
;
174 // Look for an unpatrolled change corresponding to this diff
175 $db = wfGetDB( DB_SLAVE
);
176 $change = RecentChange
::newFromConds(
178 // Add redundant user,timestamp condition so we can use the existing index
179 'rc_user_text' => $this->mNewRev
->getRawUserText(),
180 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
181 'rc_this_oldid' => $this->mNewid
,
182 'rc_last_oldid' => $this->mOldid
,
187 if( $change instanceof RecentChange
) {
188 $rcid = $change->mAttribs
['rc_id'];
196 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
198 wfMsgHtml( 'markaspatrolleddiff' ),
199 "action=markpatrolled&rcid={$rcid}"
208 $htmldiffarg = $this->htmlDiffArgument();
209 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
210 'diff=prev&oldid='.$this->mOldid
.$htmldiffarg, '', '', 'id="differences-prevlink"' );
211 if ( $this->mNewRev
->isCurrent() ) {
212 $nextlink = ' ';
214 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
215 'diff=next&oldid='.$this->mNewid
.$htmldiffarg, '', '', 'id="differences-nextlink"' );
221 if ($this->mOldRev
->mMinorEdit
== 1) {
222 $oldminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
225 if ($this->mNewRev
->mMinorEdit
== 1) {
226 $newminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
229 $rdel = ''; $ldel = '';
230 if( $wgUser->isAllowed( 'deleterevision' ) ) {
231 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
232 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
233 // If revision was hidden from sysops
234 $ldel = wfMsgHtml('rev-delundel');
236 $ldel = $sk->makeKnownLinkObj( $revdel,
237 wfMsgHtml('rev-delundel'),
238 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
239 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
240 // Bolden oversighted content
241 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
242 $ldel = "<strong>$ldel</strong>";
244 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
245 // We don't currently handle well changing the top revision's settings
246 if( $this->mNewRev
->isCurrent() ) {
247 // If revision was hidden from sysops
248 $rdel = wfMsgHtml('rev-delundel');
249 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
250 // If revision was hidden from sysops
251 $rdel = wfMsgHtml('rev-delundel');
253 $rdel = $sk->makeKnownLinkObj( $revdel,
254 wfMsgHtml('rev-delundel'),
255 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
256 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
257 // Bolden oversighted content
258 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
259 $rdel = "<strong>$rdel</strong>";
261 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
264 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
265 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
266 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
267 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
268 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
269 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
270 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
271 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
273 if( $wgEnableHtmlDiff && $this->htmldiff
) {
274 $multi = $this->getMultiNotice();
275 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'wikicodecomparison' ),
276 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=0', '', '', 'id="differences-switchtype"' ).'</div>');
277 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
278 $this->renderHtmlDiff();
280 if($wgEnableHtmlDiff){
281 $wgOut->addHTML('<div class="diff-switchtype">'.$sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'visualcomparison' ),
282 'diff='.$this->mNewid
.'&oldid='.$this->mOldid
.'&htmldiff=1', '', '', 'id="differences-switchtype"' ).'</div>');
284 $this->showDiff( $oldHeader, $newHeader );
286 $this->renderNewRevision();
289 wfProfileOut( __METHOD__
);
293 * Show the new revision of the page.
295 function renderNewRevision() {
297 wfProfileIn( __METHOD__
);
299 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
300 #add deleted rev tag if needed
301 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
302 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
303 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
304 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
307 if( !$this->mNewRev
->isCurrent() ) {
308 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
311 $this->loadNewText();
312 if( is_object( $this->mNewRev
) ) {
313 $wgOut->setRevisionId( $this->mNewRev
->getId() );
316 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
317 // Stolen from Article::view --AG 2007-10-11
319 // Give hooks a chance to customise the output
320 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
321 // Wrap the whole lot in a <pre> and don't parse
323 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
324 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
325 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
326 $wgOut->addHtml( "\n</pre>\n" );
329 $wgOut->addWikiTextTidy( $this->mNewtext
);
331 if( !$this->mNewRev
->isCurrent() ) {
332 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
335 wfProfileOut( __METHOD__
);
339 function renderHtmlDiff() {
340 global $wgOut, $wgTitle, $wgParser;
341 wfProfileIn( __METHOD__
);
343 $this->showDiffStyle();
345 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
346 #add deleted rev tag if needed
347 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
348 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
349 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
350 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
353 if( !$this->mNewRev
->isCurrent() ) {
354 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
360 if( is_object( $this->mOldRev
) ) {
361 $wgOut->setRevisionId( $this->mOldRev
->getId() );
364 $popts = $wgOut->parserOptions();
365 $oldTidy = $popts->setTidy( true );
367 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
368 $popts->setTidy( $oldTidy );
371 //$wgOut->addParserOutputNoText( $parserOutput );
372 $oldHtml = $parserOutput->getText();
373 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
376 if( is_object( $this->mNewRev
) ) {
377 $wgOut->setRevisionId( $this->mNewRev
->getId() );
380 $popts = $wgOut->parserOptions();
381 $oldTidy = $popts->setTidy( true );
383 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
384 $popts->setTidy( $oldTidy );
386 $wgOut->addParserOutputNoText( $parserOutput );
387 $newHtml = $parserOutput->getText();
388 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
390 unset($parserOutput, $popts);
392 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
393 $differ->htmlDiff($oldHtml, $newHtml);
395 wfProfileOut( __METHOD__
);
399 * Show the first revision of an article. Uses normal diff headers in
400 * contrast to normal "old revision" display style.
402 function showFirstRevision() {
403 global $wgOut, $wgUser;
404 wfProfileIn( __METHOD__
);
406 # Get article text from the DB
408 if ( ! $this->loadNewText() ) {
409 $t = $this->mTitle
->getPrefixedText();
410 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
411 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
412 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
413 wfProfileOut( __METHOD__
);
416 if ( $this->mNewRev
->isCurrent() ) {
417 $wgOut->setArticleFlag( true );
420 # Check if user is allowed to look at this page. If not, bail out.
422 if ( !( $this->mTitle
->userCanRead() ) ) {
423 $wgOut->loginToUse();
425 wfProfileOut( __METHOD__
);
429 # Prepare the header box
431 $sk = $wgUser->getSkin();
433 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
434 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
435 $sk->revUserTools( $this->mNewRev
) . "<br />" .
436 $sk->revComment( $this->mNewRev
) . "<br />" .
437 $nextlink . "</div>\n";
439 $wgOut->addHTML( $header );
441 $wgOut->setSubtitle( wfMsg( 'difference' ) );
442 $wgOut->setRobotPolicy( 'noindex,nofollow' );
444 wfProfileOut( __METHOD__
);
447 function htmlDiffArgument(){
448 global $wgEnableHtmlDiff;
449 if($wgEnableHtmlDiff){
451 return '&htmldiff=1';
453 return '&htmldiff=0';
461 * Get the diff text, send it to $wgOut
462 * Returns false if the diff could not be generated, otherwise returns true
464 function showDiff( $otitle, $ntitle ) {
466 $diff = $this->getDiff( $otitle, $ntitle );
467 if ( $diff === false ) {
468 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
471 $this->showDiffStyle();
472 $wgOut->addHTML( $diff );
478 * Add style sheets and supporting JS for diff display.
480 function showDiffStyle() {
481 global $wgStylePath, $wgStyleVersion, $wgOut;
482 $wgOut->addStyle( 'common/diff.css' );
484 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
485 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
489 * Get complete diff table, including header
491 * @param Title $otitle Old title
492 * @param Title $ntitle New title
495 function getDiff( $otitle, $ntitle ) {
496 $body = $this->getDiffBody();
497 if ( $body === false ) {
500 $multi = $this->getMultiNotice();
501 return $this->addHeader( $body, $otitle, $ntitle, $multi );
506 * Get the diff table body, without header
510 function getDiffBody() {
512 wfProfileIn( __METHOD__
);
513 // Check if the diff should be hidden from this user
514 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
516 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
521 if ( $this->mOldid
&& $this->mNewid
) {
522 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
524 if ( !$this->mRefreshCache
) {
525 $difftext = $wgMemc->get( $key );
527 wfIncrStats( 'diff_cache_hit' );
528 $difftext = $this->localiseLineNumbers( $difftext );
529 $difftext .= "\n<!-- diff cache key $key -->\n";
530 wfProfileOut( __METHOD__
);
533 } // don't try to load but save the result
536 // Loadtext is permission safe, this just clears out the diff
537 if ( !$this->loadText() ) {
538 wfProfileOut( __METHOD__
);
542 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
544 // Save to cache for 7 days
545 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, $wgNodeName;
642 $data = array( $generator );
643 if( $wgShowHostnames ) {
644 $data[] = $wgNodeName;
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() {
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
= htmlspecialchars( wfMsg( 'currentrev' ) );
764 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
766 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
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 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
816 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
819 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
820 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
821 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
822 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
830 * Load the text of the revisions, as well as revision data.
832 function loadText() {
833 if ( $this->mTextLoaded
== 2 ) {
836 // Whether it succeeds or fails, we don't want to try again
837 $this->mTextLoaded
= 2;
840 if ( !$this->loadRevisionData() ) {
843 if ( $this->mOldRev
) {
844 $this->mOldtext
= $this->mOldRev
->revText();
845 if ( $this->mOldtext
=== false ) {
849 if ( $this->mNewRev
) {
850 $this->mNewtext
= $this->mNewRev
->revText();
851 if ( $this->mNewtext
=== false ) {
859 * Load the text of the new revision, not the old one
861 function loadNewText() {
862 if ( $this->mTextLoaded
>= 1 ) {
865 $this->mTextLoaded
= 1;
867 if ( !$this->loadRevisionData() ) {
870 $this->mNewtext
= $this->mNewRev
->getText();
877 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
879 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
880 // You may copy this code freely under the conditions of the GPL.
883 define('USE_ASSERTS', function_exists('assert'));
888 * @ingroup DifferenceEngine
896 trigger_error('pure virtual', E_USER_ERROR
);
900 return $this->orig ?
sizeof($this->orig
) : 0;
903 function nclosing() {
904 return $this->closing ?
sizeof($this->closing
) : 0;
911 * @ingroup DifferenceEngine
913 class _DiffOp_Copy
extends _DiffOp
{
916 function _DiffOp_Copy ($orig, $closing = false) {
917 if (!is_array($closing))
920 $this->closing
= $closing;
924 return new _DiffOp_Copy($this->closing
, $this->orig
);
931 * @ingroup DifferenceEngine
933 class _DiffOp_Delete
extends _DiffOp
{
934 var $type = 'delete';
936 function _DiffOp_Delete ($lines) {
937 $this->orig
= $lines;
938 $this->closing
= false;
942 return new _DiffOp_Add($this->orig
);
949 * @ingroup DifferenceEngine
951 class _DiffOp_Add
extends _DiffOp
{
954 function _DiffOp_Add ($lines) {
955 $this->closing
= $lines;
960 return new _DiffOp_Delete($this->closing
);
967 * @ingroup DifferenceEngine
969 class _DiffOp_Change
extends _DiffOp
{
970 var $type = 'change';
972 function _DiffOp_Change ($orig, $closing) {
974 $this->closing
= $closing;
978 return new _DiffOp_Change($this->closing
, $this->orig
);
983 * Class used internally by Diff to actually compute the diffs.
985 * The algorithm used here is mostly lifted from the perl module
986 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
987 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
989 * More ideas are taken from:
990 * http://www.ics.uci.edu/~eppstein/161/960229.html
992 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
993 * diffutils-2.7, which can be found at:
994 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
996 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
999 * Line length limits for robustness added by Tim Starling, 2005-08-31
1000 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1002 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1004 * @ingroup DifferenceEngine
1008 const MAX_XREF_LENGTH
= 10000;
1010 function diff ($from_lines, $to_lines){
1011 wfProfileIn( __METHOD__
);
1013 // Diff and store locally
1014 $this->diff_local($from_lines, $to_lines);
1016 // Merge edits when possible
1017 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1018 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1020 // Compute the edit operations.
1021 $n_from = sizeof($from_lines);
1022 $n_to = sizeof($to_lines);
1026 while ($xi < $n_from ||
$yi < $n_to) {
1027 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1028 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1030 // Skip matching "snake".
1032 while ( $xi < $n_from && $yi < $n_to
1033 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1034 $copy[] = $from_lines[$xi++
];
1038 $edits[] = new _DiffOp_Copy($copy);
1040 // Find deletes & adds.
1042 while ($xi < $n_from && $this->xchanged
[$xi])
1043 $delete[] = $from_lines[$xi++
];
1046 while ($yi < $n_to && $this->ychanged
[$yi])
1047 $add[] = $to_lines[$yi++
];
1049 if ($delete && $add)
1050 $edits[] = new _DiffOp_Change($delete, $add);
1052 $edits[] = new _DiffOp_Delete($delete);
1054 $edits[] = new _DiffOp_Add($add);
1056 wfProfileOut( __METHOD__
);
1060 function diff_local ($from_lines, $to_lines) {
1061 global $wgExternalDiffEngine;
1062 wfProfileIn( __METHOD__
);
1064 if($wgExternalDiffEngine == 'wikidiff3'){
1066 $wikidiff3 = new WikiDiff3();
1067 $wikidiff3->diff($from_lines, $to_lines);
1068 $this->xchanged
= $wikidiff3->removed
;
1069 $this->ychanged
= $wikidiff3->added
;
1073 $n_from = sizeof($from_lines);
1074 $n_to = sizeof($to_lines);
1075 $this->xchanged
= $this->ychanged
= array();
1076 $this->xv
= $this->yv
= array();
1077 $this->xind
= $this->yind
= array();
1079 unset($this->in_seq
);
1082 // Skip leading common lines.
1083 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1084 if ($from_lines[$skip] !== $to_lines[$skip])
1086 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1088 // Skip trailing common lines.
1089 $xi = $n_from; $yi = $n_to;
1090 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1091 if ($from_lines[$xi] !== $to_lines[$yi])
1093 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1096 // Ignore lines which do not exist in both files.
1097 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1098 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1101 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1102 $line = $to_lines[$yi];
1103 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1105 $yhash[$this->_line_hash($line)] = 1;
1106 $this->yv
[] = $line;
1107 $this->yind
[] = $yi;
1109 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1110 $line = $from_lines[$xi];
1111 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1113 $this->xv
[] = $line;
1114 $this->xind
[] = $xi;
1118 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1120 wfProfileOut( __METHOD__
);
1124 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1126 function _line_hash( $line ) {
1127 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1128 return md5( $line );
1134 /* Divide the Largest Common Subsequence (LCS) of the sequences
1135 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1138 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1139 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1140 * sub sequences. The first sub-sequence is contained in [X0, X1),
1141 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1142 * that (X0, Y0) == (XOFF, YOFF) and
1143 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1145 * This function assumes that the first lines of the specified portions
1146 * of the two files do not match, and likewise that the last lines do not
1147 * match. The caller must trim matching lines from the beginning and end
1148 * of the portions it is going to specify.
1150 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1153 if ($xlim - $xoff > $ylim - $yoff) {
1154 // Things seems faster (I'm not sure I understand why)
1155 // when the shortest sequence in X.
1157 list ($xoff, $xlim, $yoff, $ylim)
1158 = array( $yoff, $ylim, $xoff, $xlim);
1162 for ($i = $ylim - 1; $i >= $yoff; $i--)
1163 $ymatches[$this->xv
[$i]][] = $i;
1165 for ($i = $ylim - 1; $i >= $yoff; $i--)
1166 $ymatches[$this->yv
[$i]][] = $i;
1169 $this->seq
[0]= $yoff - 1;
1170 $this->in_seq
= array();
1171 $ymids[0] = array();
1173 $numer = $xlim - $xoff +
$nchunks - 1;
1175 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1177 for ($i = 0; $i <= $this->lcs
; $i++
)
1178 $ymids[$i][$chunk-1] = $this->seq
[$i];
1180 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1181 for ( ; $x < $x1; $x++
) {
1182 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1183 if (empty($ymatches[$line]))
1185 $matches = $ymatches[$line];
1187 while (list ($junk, $y) = each($matches))
1188 if (empty($this->in_seq
[$y])) {
1189 $k = $this->_lcs_pos($y);
1190 USE_ASSERTS
&& assert($k > 0);
1191 $ymids[$k] = $ymids[$k-1];
1194 while (list ( /* $junk */, $y) = each($matches)) {
1195 if ($y > $this->seq
[$k-1]) {
1196 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1197 // Optimization: this is a common case:
1198 // next match is just replacing previous match.
1199 $this->in_seq
[$this->seq
[$k]] = false;
1200 $this->seq
[$k] = $y;
1201 $this->in_seq
[$y] = 1;
1202 } else if (empty($this->in_seq
[$y])) {
1203 $k = $this->_lcs_pos($y);
1204 USE_ASSERTS
&& assert($k > 0);
1205 $ymids[$k] = $ymids[$k-1];
1211 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1212 $ymid = $ymids[$this->lcs
];
1213 for ($n = 0; $n < $nchunks - 1; $n++
) {
1214 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1215 $y1 = $ymid[$n] +
1;
1216 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1218 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1220 return array($this->lcs
, $seps);
1223 function _lcs_pos ($ypos) {
1225 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1226 $this->seq
[++
$this->lcs
] = $ypos;
1227 $this->in_seq
[$ypos] = 1;
1232 while ($beg < $end) {
1233 $mid = (int)(($beg +
$end) / 2);
1234 if ( $ypos > $this->seq
[$mid] )
1240 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1242 $this->in_seq
[$this->seq
[$end]] = false;
1243 $this->seq
[$end] = $ypos;
1244 $this->in_seq
[$ypos] = 1;
1248 /* Find LCS of two sequences.
1250 * The results are recorded in the vectors $this->{x,y}changed[], by
1251 * storing a 1 in the element for each line that is an insertion
1252 * or deletion (ie. is not in the LCS).
1254 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1256 * Note that XLIM, YLIM are exclusive bounds.
1257 * All line numbers are origin-0 and discarded lines are not counted.
1259 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1260 // Slide down the bottom initial diagonal.
1261 while ($xoff < $xlim && $yoff < $ylim
1262 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1267 // Slide up the top initial diagonal.
1268 while ($xlim > $xoff && $ylim > $yoff
1269 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1274 if ($xoff == $xlim ||
$yoff == $ylim)
1277 // This is ad hoc but seems to work well.
1278 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1279 //$nchunks = max(2,min(8,(int)$nchunks));
1280 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1282 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1286 // X and Y sequences have no common subsequence:
1287 // mark all changed.
1288 while ($yoff < $ylim)
1289 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1290 while ($xoff < $xlim)
1291 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1293 // Use the partitions to split this problem into subproblems.
1296 while ($pt2 = next($seps)) {
1297 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1303 /* Adjust inserts/deletes of identical lines to join changes
1304 * as much as possible.
1306 * We do something when a run of changed lines include a
1307 * line at one end and has an excluded, identical line at the other.
1308 * We are free to choose which identical line is included.
1309 * `compareseq' usually chooses the one at the beginning,
1310 * but usually it is cleaner to consider the following identical line
1311 * to be the "change".
1313 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1315 function _shift_boundaries ($lines, &$changed, $other_changed) {
1316 wfProfileIn( __METHOD__
);
1320 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1321 $len = sizeof($lines);
1322 $other_len = sizeof($other_changed);
1326 * Scan forwards to find beginning of another run of changes.
1327 * Also keep track of the corresponding point in the other file.
1329 * Throughout this code, $i and $j are adjusted together so that
1330 * the first $i elements of $changed and the first $j elements
1331 * of $other_changed both contain the same number of zeros
1332 * (unchanged lines).
1333 * Furthermore, $j is always kept so that $j == $other_len or
1334 * $other_changed[$j] == false.
1336 while ($j < $other_len && $other_changed[$j])
1339 while ($i < $len && ! $changed[$i]) {
1340 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1342 while ($j < $other_len && $other_changed[$j])
1351 // Find the end of this run of changes.
1352 while (++
$i < $len && $changed[$i])
1357 * Record the length of this run of changes, so that
1358 * we can later determine whether the run has grown.
1360 $runlength = $i - $start;
1363 * Move the changed region back, so long as the
1364 * previous unchanged line matches the last changed one.
1365 * This merges with previous changed regions.
1367 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1368 $changed[--$start] = 1;
1369 $changed[--$i] = false;
1370 while ($start > 0 && $changed[$start - 1])
1372 USE_ASSERTS
&& assert('$j > 0');
1373 while ($other_changed[--$j])
1375 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1379 * Set CORRESPONDING to the end of the changed run, at the last
1380 * point where it corresponds to a changed run in the other file.
1381 * CORRESPONDING == LEN means no such point has been found.
1383 $corresponding = $j < $other_len ?
$i : $len;
1386 * Move the changed region forward, so long as the
1387 * first changed line matches the following unchanged one.
1388 * This merges with following changed regions.
1389 * Do this second, so that if there are no merges,
1390 * the changed region is moved forward as far as possible.
1392 while ($i < $len && $lines[$start] == $lines[$i]) {
1393 $changed[$start++
] = false;
1395 while ($i < $len && $changed[$i])
1398 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1400 if ($j < $other_len && $other_changed[$j]) {
1401 $corresponding = $i;
1402 while ($j < $other_len && $other_changed[$j])
1406 } while ($runlength != $i - $start);
1409 * If possible, move the fully-merged run of changes
1410 * back to a corresponding run in the other file.
1412 while ($corresponding < $i) {
1413 $changed[--$start] = 1;
1415 USE_ASSERTS
&& assert('$j > 0');
1416 while ($other_changed[--$j])
1418 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1421 wfProfileOut( __METHOD__
);
1426 * Class representing a 'diff' between two sequences of strings.
1429 * @ingroup DifferenceEngine
1437 * Computes diff between sequences of strings.
1439 * @param $from_lines array An array of strings.
1440 * (Typically these are lines from a file.)
1441 * @param $to_lines array An array of strings.
1443 function Diff($from_lines, $to_lines) {
1444 $eng = new _DiffEngine
;
1445 $this->edits
= $eng->diff($from_lines, $to_lines);
1446 //$this->_check($from_lines, $to_lines);
1450 * Compute reversed Diff.
1454 * $diff = new Diff($lines1, $lines2);
1455 * $rev = $diff->reverse();
1456 * @return object A Diff object representing the inverse of the
1459 function reverse () {
1461 $rev->edits
= array();
1462 foreach ($this->edits
as $edit) {
1463 $rev->edits
[] = $edit->reverse();
1469 * Check for empty diff.
1471 * @return bool True iff two sequences were identical.
1473 function isEmpty () {
1474 foreach ($this->edits
as $edit) {
1475 if ($edit->type
!= 'copy')
1482 * Compute the length of the Longest Common Subsequence (LCS).
1484 * This is mostly for diagnostic purposed.
1486 * @return int The length of the LCS.
1490 foreach ($this->edits
as $edit) {
1491 if ($edit->type
== 'copy')
1492 $lcs +
= sizeof($edit->orig
);
1498 * Get the original set of lines.
1500 * This reconstructs the $from_lines parameter passed to the
1503 * @return array The original sequence of strings.
1508 foreach ($this->edits
as $edit) {
1510 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1516 * Get the closing set of lines.
1518 * This reconstructs the $to_lines parameter passed to the
1521 * @return array The sequence of strings.
1523 function closing() {
1526 foreach ($this->edits
as $edit) {
1528 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1534 * Check a Diff for validity.
1536 * This is here only for debugging purposes.
1538 function _check ($from_lines, $to_lines) {
1539 wfProfileIn( __METHOD__
);
1540 if (serialize($from_lines) != serialize($this->orig()))
1541 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1542 if (serialize($to_lines) != serialize($this->closing()))
1543 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1545 $rev = $this->reverse();
1546 if (serialize($to_lines) != serialize($rev->orig()))
1547 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1548 if (serialize($from_lines) != serialize($rev->closing()))
1549 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1553 foreach ($this->edits
as $edit) {
1554 if ( $prevtype == $edit->type
)
1555 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1556 $prevtype = $edit->type
;
1559 $lcs = $this->lcs();
1560 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1561 wfProfileOut( __METHOD__
);
1566 * @todo document, bad name.
1568 * @ingroup DifferenceEngine
1570 class MappedDiff
extends Diff
1575 * Computes diff between sequences of strings.
1577 * This can be used to compute things like
1578 * case-insensitve diffs, or diffs which ignore
1579 * changes in white-space.
1581 * @param $from_lines array An array of strings.
1582 * (Typically these are lines from a file.)
1584 * @param $to_lines array An array of strings.
1586 * @param $mapped_from_lines array This array should
1587 * have the same size number of elements as $from_lines.
1588 * The elements in $mapped_from_lines and
1589 * $mapped_to_lines are what is actually compared
1590 * when computing the diff.
1592 * @param $mapped_to_lines array This array should
1593 * have the same number of elements as $to_lines.
1595 function MappedDiff($from_lines, $to_lines,
1596 $mapped_from_lines, $mapped_to_lines) {
1597 wfProfileIn( __METHOD__
);
1599 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1600 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1602 $this->Diff($mapped_from_lines, $mapped_to_lines);
1605 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1606 $orig = &$this->edits
[$i]->orig
;
1607 if (is_array($orig)) {
1608 $orig = array_slice($from_lines, $xi, sizeof($orig));
1609 $xi +
= sizeof($orig);
1612 $closing = &$this->edits
[$i]->closing
;
1613 if (is_array($closing)) {
1614 $closing = array_slice($to_lines, $yi, sizeof($closing));
1615 $yi +
= sizeof($closing);
1618 wfProfileOut( __METHOD__
);
1623 * A class to format Diffs
1625 * This class formats the diff in classic diff format.
1626 * It is intended that this class be customized via inheritance,
1627 * to obtain fancier outputs.
1630 * @ingroup DifferenceEngine
1632 class DiffFormatter
{
1634 * Number of leading context "lines" to preserve.
1636 * This should be left at zero for this class, but subclasses
1637 * may want to set this to other values.
1639 var $leading_context_lines = 0;
1642 * Number of trailing context "lines" to preserve.
1644 * This should be left at zero for this class, but subclasses
1645 * may want to set this to other values.
1647 var $trailing_context_lines = 0;
1652 * @param $diff object A Diff object.
1653 * @return string The formatted output.
1655 function format($diff) {
1656 wfProfileIn( __METHOD__
);
1662 $nlead = $this->leading_context_lines
;
1663 $ntrail = $this->trailing_context_lines
;
1665 $this->_start_diff();
1667 foreach ($diff->edits
as $edit) {
1668 if ($edit->type
== 'copy') {
1669 if (is_array($block)) {
1670 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1675 $context = array_slice($edit->orig
, 0, $ntrail);
1676 $block[] = new _DiffOp_Copy($context);
1678 $this->_block($x0, $ntrail +
$xi - $x0,
1679 $y0, $ntrail +
$yi - $y0,
1684 $context = $edit->orig
;
1687 if (! is_array($block)) {
1688 $context = array_slice($context, sizeof($context) - $nlead);
1689 $x0 = $xi - sizeof($context);
1690 $y0 = $yi - sizeof($context);
1693 $block[] = new _DiffOp_Copy($context);
1699 $xi +
= sizeof($edit->orig
);
1701 $yi +
= sizeof($edit->closing
);
1704 if (is_array($block))
1705 $this->_block($x0, $xi - $x0,
1709 $end = $this->_end_diff();
1710 wfProfileOut( __METHOD__
);
1714 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1715 wfProfileIn( __METHOD__
);
1716 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1717 foreach ($edits as $edit) {
1718 if ($edit->type
== 'copy')
1719 $this->_context($edit->orig
);
1720 elseif ($edit->type
== 'add')
1721 $this->_added($edit->closing
);
1722 elseif ($edit->type
== 'delete')
1723 $this->_deleted($edit->orig
);
1724 elseif ($edit->type
== 'change')
1725 $this->_changed($edit->orig
, $edit->closing
);
1727 trigger_error('Unknown edit type', E_USER_ERROR
);
1729 $this->_end_block();
1730 wfProfileOut( __METHOD__
);
1733 function _start_diff() {
1737 function _end_diff() {
1738 $val = ob_get_contents();
1743 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1745 $xbeg .= "," . ($xbeg +
$xlen - 1);
1747 $ybeg .= "," . ($ybeg +
$ylen - 1);
1749 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1752 function _start_block($header) {
1753 echo $header . "\n";
1756 function _end_block() {
1759 function _lines($lines, $prefix = ' ') {
1760 foreach ($lines as $line)
1761 echo "$prefix $line\n";
1764 function _context($lines) {
1765 $this->_lines($lines);
1768 function _added($lines) {
1769 $this->_lines($lines, '>');
1771 function _deleted($lines) {
1772 $this->_lines($lines, '<');
1775 function _changed($orig, $closing) {
1776 $this->_deleted($orig);
1778 $this->_added($closing);
1783 * A formatter that outputs unified diffs
1784 * @ingroup DifferenceEngine
1787 class UnifiedDiffFormatter
extends DiffFormatter
{
1788 var $leading_context_lines = 2;
1789 var $trailing_context_lines = 2;
1791 function _added($lines) {
1792 $this->_lines($lines, '+');
1794 function _deleted($lines) {
1795 $this->_lines($lines, '-');
1797 function _changed($orig, $closing) {
1798 $this->_deleted($orig);
1799 $this->_added($closing);
1801 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1802 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1807 * A pseudo-formatter that just passes along the Diff::$edits array
1808 * @ingroup DifferenceEngine
1810 class ArrayDiffFormatter
extends DiffFormatter
{
1811 function format($diff) {
1815 foreach($diff->edits
as $edit)
1816 switch($edit->type
) {
1818 foreach($edit->closing
as $l) {
1822 'newline' => $newline++
1827 foreach($edit->orig
as $l) {
1829 'action' => 'delete',
1831 'oldline' => $oldline++
,
1836 foreach($edit->orig
as $i => $l) {
1838 'action' => 'change',
1840 'new' => @$edit->closing
[$i],
1841 'oldline' => $oldline++
,
1842 'newline' => $newline++
,
1847 $oldline +
= count($edit->orig
);
1848 $newline +
= count($edit->orig
);
1855 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1859 define('NBSP', ' '); // iso-8859-x non-breaking space.
1864 * @ingroup DifferenceEngine
1866 class _HWLDF_WordAccumulator
{
1867 function _HWLDF_WordAccumulator () {
1868 $this->_lines
= array();
1874 function _flushGroup ($new_tag) {
1875 if ($this->_group
!== '') {
1876 if ($this->_tag
== 'ins')
1877 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1878 htmlspecialchars ( $this->_group
) . '</ins>';
1879 elseif ($this->_tag
== 'del')
1880 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1881 htmlspecialchars ( $this->_group
) . '</del>';
1883 $this->_line
.= htmlspecialchars ( $this->_group
);
1886 $this->_tag
= $new_tag;
1889 function _flushLine ($new_tag) {
1890 $this->_flushGroup($new_tag);
1891 if ($this->_line
!= '')
1892 array_push ( $this->_lines
, $this->_line
);
1894 # make empty lines visible by inserting an NBSP
1895 array_push ( $this->_lines
, NBSP
);
1899 function addWords ($words, $tag = '') {
1900 if ($tag != $this->_tag
)
1901 $this->_flushGroup($tag);
1903 foreach ($words as $word) {
1904 // new-line should only come as first char of word.
1907 if ($word[0] == "\n") {
1908 $this->_flushLine($tag);
1909 $word = substr($word, 1);
1911 assert(!strstr($word, "\n"));
1912 $this->_group
.= $word;
1916 function getLines() {
1917 $this->_flushLine('~done');
1918 return $this->_lines
;
1925 * @ingroup DifferenceEngine
1927 class WordLevelDiff
extends MappedDiff
{
1928 const MAX_LINE_LENGTH
= 10000;
1930 function WordLevelDiff ($orig_lines, $closing_lines) {
1931 wfProfileIn( __METHOD__
);
1933 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1934 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1936 $this->MappedDiff($orig_words, $closing_words,
1937 $orig_stripped, $closing_stripped);
1938 wfProfileOut( __METHOD__
);
1941 function _split($lines) {
1942 wfProfileIn( __METHOD__
);
1945 $stripped = array();
1947 foreach ( $lines as $line ) {
1948 # If the line is too long, just pretend the entire line is one big word
1949 # This prevents resource exhaustion problems
1956 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1958 $stripped[] = $line;
1961 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1964 $words = array_merge( $words, $m[0] );
1965 $stripped = array_merge( $stripped, $m[1] );
1969 wfProfileOut( __METHOD__
);
1970 return array($words, $stripped);
1974 wfProfileIn( __METHOD__
);
1975 $orig = new _HWLDF_WordAccumulator
;
1977 foreach ($this->edits
as $edit) {
1978 if ($edit->type
== 'copy')
1979 $orig->addWords($edit->orig
);
1980 elseif ($edit->orig
)
1981 $orig->addWords($edit->orig
, 'del');
1983 $lines = $orig->getLines();
1984 wfProfileOut( __METHOD__
);
1988 function closing () {
1989 wfProfileIn( __METHOD__
);
1990 $closing = new _HWLDF_WordAccumulator
;
1992 foreach ($this->edits
as $edit) {
1993 if ($edit->type
== 'copy')
1994 $closing->addWords($edit->closing
);
1995 elseif ($edit->closing
)
1996 $closing->addWords($edit->closing
, 'ins');
1998 $lines = $closing->getLines();
1999 wfProfileOut( __METHOD__
);
2005 * Wikipedia Table style diff formatter.
2008 * @ingroup DifferenceEngine
2010 class TableDiffFormatter
extends DiffFormatter
{
2011 function TableDiffFormatter() {
2012 $this->leading_context_lines
= 2;
2013 $this->trailing_context_lines
= 2;
2016 public static function escapeWhiteSpace( $msg ) {
2017 $msg = preg_replace( '/^ /m', ' ', $msg );
2018 $msg = preg_replace( '/ $/m', ' ', $msg );
2019 $msg = preg_replace( '/ /', ' ', $msg );
2023 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2024 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2025 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2029 function _start_block( $header ) {
2033 function _end_block() {
2036 function _lines( $lines, $prefix=' ', $color='white' ) {
2039 # HTML-escape parameter before calling this
2040 function addedLine( $line ) {
2041 return $this->wrapLine( '+', 'diff-addedline', $line );
2044 # HTML-escape parameter before calling this
2045 function deletedLine( $line ) {
2046 return $this->wrapLine( '-', 'diff-deletedline', $line );
2049 # HTML-escape parameter before calling this
2050 function contextLine( $line ) {
2051 return $this->wrapLine( ' ', 'diff-context', $line );
2054 private function wrapLine( $marker, $class, $line ) {
2055 if( $line !== '' ) {
2056 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2057 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2059 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2062 function emptyLine() {
2063 return '<td colspan="2"> </td>';
2066 function _added( $lines ) {
2067 foreach ($lines as $line) {
2068 echo '<tr>' . $this->emptyLine() .
2069 $this->addedLine( '<ins class="diffchange">' .
2070 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2074 function _deleted($lines) {
2075 foreach ($lines as $line) {
2076 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2077 htmlspecialchars ( $line ) . '</del>' ) .
2078 $this->emptyLine() . "</tr>\n";
2082 function _context( $lines ) {
2083 foreach ($lines as $line) {
2085 $this->contextLine( htmlspecialchars ( $line ) ) .
2086 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2090 function _changed( $orig, $closing ) {
2091 wfProfileIn( __METHOD__
);
2093 $diff = new WordLevelDiff( $orig, $closing );
2094 $del = $diff->orig();
2095 $add = $diff->closing();
2097 # Notice that WordLevelDiff returns HTML-escaped output.
2098 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2100 while ( $line = array_shift( $del ) ) {
2101 $aline = array_shift( $add );
2102 echo '<tr>' . $this->deletedLine( $line ) .
2103 $this->addedLine( $aline ) . "</tr>\n";
2105 foreach ($add as $line) { # If any leftovers
2106 echo '<tr>' . $this->emptyLine() .
2107 $this->addedLine( $line ) . "</tr>\n";
2109 wfProfileOut( __METHOD__
);