393cdd1e8020eda165cced6b1268976de5202769
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
->getUserText( Revision
::FOR_THIS_USER
),
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, $wgDebugComments;
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 );
366 $popts->setEditSection( false );
368 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
369 $popts->setTidy( $oldTidy );
372 //$wgOut->addParserOutputNoText( $parserOutput );
373 $oldHtml = $parserOutput->getText();
374 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
377 if( is_object( $this->mNewRev
) ) {
378 $wgOut->setRevisionId( $this->mNewRev
->getId() );
381 $popts = $wgOut->parserOptions();
382 $oldTidy = $popts->setTidy( true );
384 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
385 $popts->setTidy( $oldTidy );
387 $wgOut->addParserOutputNoText( $parserOutput );
388 $newHtml = $parserOutput->getText();
389 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
391 unset($parserOutput, $popts);
393 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
394 $differ->htmlDiff($oldHtml, $newHtml);
395 if ( $wgDebugComments ) {
396 $wgOut->addHtml( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer
::getDebugOutput() . " End Debug -->" );
399 wfProfileOut( __METHOD__
);
403 * Show the first revision of an article. Uses normal diff headers in
404 * contrast to normal "old revision" display style.
406 function showFirstRevision() {
407 global $wgOut, $wgUser;
408 wfProfileIn( __METHOD__
);
410 # Get article text from the DB
412 if ( ! $this->loadNewText() ) {
413 $t = $this->mTitle
->getPrefixedText();
414 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
415 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
416 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
417 wfProfileOut( __METHOD__
);
420 if ( $this->mNewRev
->isCurrent() ) {
421 $wgOut->setArticleFlag( true );
424 # Check if user is allowed to look at this page. If not, bail out.
426 if ( !( $this->mTitle
->userCanRead() ) ) {
427 $wgOut->loginToUse();
429 wfProfileOut( __METHOD__
);
433 # Prepare the header box
435 $sk = $wgUser->getSkin();
437 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
.$this->htmlDiffArgument(), '', '', 'id="differences-nextlink"' );
438 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
439 $sk->revUserTools( $this->mNewRev
) . "<br />" .
440 $sk->revComment( $this->mNewRev
) . "<br />" .
441 $nextlink . "</div>\n";
443 $wgOut->addHTML( $header );
445 $wgOut->setSubtitle( wfMsg( 'difference' ) );
446 $wgOut->setRobotPolicy( 'noindex,nofollow' );
448 wfProfileOut( __METHOD__
);
451 function htmlDiffArgument(){
452 global $wgEnableHtmlDiff;
453 if($wgEnableHtmlDiff){
455 return '&htmldiff=1';
457 return '&htmldiff=0';
465 * Get the diff text, send it to $wgOut
466 * Returns false if the diff could not be generated, otherwise returns true
468 function showDiff( $otitle, $ntitle ) {
470 $diff = $this->getDiff( $otitle, $ntitle );
471 if ( $diff === false ) {
472 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
475 $this->showDiffStyle();
476 $wgOut->addHTML( $diff );
482 * Add style sheets and supporting JS for diff display.
484 function showDiffStyle() {
485 global $wgStylePath, $wgStyleVersion, $wgOut;
486 $wgOut->addStyle( 'common/diff.css' );
488 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
489 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
493 * Get complete diff table, including header
495 * @param Title $otitle Old title
496 * @param Title $ntitle New title
499 function getDiff( $otitle, $ntitle ) {
500 $body = $this->getDiffBody();
501 if ( $body === false ) {
504 $multi = $this->getMultiNotice();
505 return $this->addHeader( $body, $otitle, $ntitle, $multi );
510 * Get the diff table body, without header
514 function getDiffBody() {
516 wfProfileIn( __METHOD__
);
517 // Check if the diff should be hidden from this user
518 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
520 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
525 if ( $this->mOldid
&& $this->mNewid
) {
526 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
528 if ( !$this->mRefreshCache
) {
529 $difftext = $wgMemc->get( $key );
531 wfIncrStats( 'diff_cache_hit' );
532 $difftext = $this->localiseLineNumbers( $difftext );
533 $difftext .= "\n<!-- diff cache key $key -->\n";
534 wfProfileOut( __METHOD__
);
537 } // don't try to load but save the result
540 // Loadtext is permission safe, this just clears out the diff
541 if ( !$this->loadText() ) {
542 wfProfileOut( __METHOD__
);
546 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
548 // Save to cache for 7 days
549 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
550 wfIncrStats( 'diff_uncacheable' );
551 } else if ( $key !== false && $difftext !== false ) {
552 wfIncrStats( 'diff_cache_miss' );
553 $wgMemc->set( $key, $difftext, 7*86400 );
555 wfIncrStats( 'diff_uncacheable' );
557 // Replace line numbers with the text in the user's language
558 if ( $difftext !== false ) {
559 $difftext = $this->localiseLineNumbers( $difftext );
561 wfProfileOut( __METHOD__
);
566 * Generate a diff, no caching
567 * $otext and $ntext must be already segmented
569 function generateDiffBody( $otext, $ntext ) {
570 global $wgExternalDiffEngine, $wgContLang;
572 $otext = str_replace( "\r\n", "\n", $otext );
573 $ntext = str_replace( "\r\n", "\n", $ntext );
575 if ( $wgExternalDiffEngine == 'wikidiff' ) {
576 # For historical reasons, external diff engine expects
577 # input text to be HTML-escaped already
578 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
579 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
580 if( !function_exists( 'wikidiff_do_diff' ) ) {
581 dl('php_wikidiff.so');
583 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
584 $this->debug( 'wikidiff1' );
587 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
588 # Better external diff engine, the 2 may some day be dropped
589 # This one does the escaping and segmenting itself
590 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
591 wfProfileIn( __METHOD__
. "-dl" );
592 @dl
('php_wikidiff2.so');
593 wfProfileOut( __METHOD__
. "-dl" );
595 if ( function_exists( 'wikidiff2_do_diff' ) ) {
596 wfProfileIn( 'wikidiff2_do_diff' );
597 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
598 $text .= $this->debug( 'wikidiff2' );
599 wfProfileOut( 'wikidiff2_do_diff' );
603 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
605 global $wgTmpDirectory;
606 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
607 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
609 $tempFile1 = fopen( $tempName1, "w" );
611 wfProfileOut( __METHOD__
);
614 $tempFile2 = fopen( $tempName2, "w" );
616 wfProfileOut( __METHOD__
);
619 fwrite( $tempFile1, $otext );
620 fwrite( $tempFile2, $ntext );
621 fclose( $tempFile1 );
622 fclose( $tempFile2 );
623 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
624 wfProfileIn( __METHOD__
. "-shellexec" );
625 $difftext = wfShellExec( $cmd );
626 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
627 wfProfileOut( __METHOD__
. "-shellexec" );
628 unlink( $tempName1 );
629 unlink( $tempName2 );
634 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
635 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
636 $diffs = new Diff( $ota, $nta );
637 $formatter = new TableDiffFormatter();
638 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
643 * Generate a debug comment indicating diff generating time,
644 * server node, and generator backend.
646 protected function debug( $generator="internal" ) {
647 global $wgShowHostnames;
648 $data = array( $generator );
649 if( $wgShowHostnames ) {
650 $data[] = wfHostname();
652 $data[] = wfTimestamp( TS_DB
);
653 return "<!-- diff generator: " .
662 * Replace line numbers with the text in the user's language
664 function localiseLineNumbers( $text ) {
665 return preg_replace_callback( '/<!--LINE (\d+)-->/',
666 array( &$this, 'localiseLineNumbersCb' ), $text );
669 function localiseLineNumbersCb( $matches ) {
671 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
676 * If there are revisions between the ones being compared, return a note saying so.
678 function getMultiNotice() {
679 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
682 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
683 // Comparing two different pages? Count would be meaningless.
687 $oldid = $this->mOldRev
->getId();
688 $newid = $this->mNewRev
->getId();
689 if ( $oldid > $newid ) {
690 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
693 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
697 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
702 * Add the header to a diff body
704 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
707 <col class='diff-marker' />
708 <col class='diff-content' />
709 <col class='diff-marker' />
710 <col class='diff-content' />
712 <td colspan='2' class='diff-otitle'>{$otitle}</td>
713 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
718 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
720 return $header . $diff . "</table>";
724 * Use specified text instead of loading from the database
726 function setText( $oldText, $newText ) {
727 $this->mOldtext
= $oldText;
728 $this->mNewtext
= $newText;
729 $this->mTextLoaded
= 2;
733 * Load revision metadata for the specified articles. If newid is 0, then compare
734 * the old article in oldid to the current article; if oldid is 0, then
735 * compare the current article to the immediately previous one (ignoring the
738 * If oldid is false, leave the corresponding revision object set
739 * to false. This is impossible via ordinary user input, and is provided for
742 function loadRevisionData() {
743 global $wgLang, $wgUser;
744 if ( $this->mRevisionsLoaded
) {
747 // Whether it succeeds or fails, we don't want to try again
748 $this->mRevisionsLoaded
= true;
751 // Load the new revision object
752 $this->mNewRev
= $this->mNewid
753 ? Revision
::newFromId( $this->mNewid
)
754 : Revision
::newFromTitle( $this->mTitle
);
755 if( !$this->mNewRev
instanceof Revision
)
758 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
759 $this->mNewid
= $this->mNewRev
->getId();
761 // Check if page is editable
762 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
764 // Set assorted variables
765 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
766 $this->mNewPage
= $this->mNewRev
->getTitle();
767 if( $this->mNewRev
->isCurrent() ) {
768 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
769 $this->mPagetitle
= wfMsgHTML( 'currentrev-asof', $timestamp );
770 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
772 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
773 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
776 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
777 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
778 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
780 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
781 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
783 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
784 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
785 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
786 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
789 // Load the old revision object
790 $this->mOldRev
= false;
791 if( $this->mOldid
) {
792 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
793 } elseif ( $this->mOldid
=== 0 ) {
794 $rev = $this->mNewRev
->getPrevious();
796 $this->mOldid
= $rev->getId();
797 $this->mOldRev
= $rev;
799 // No previous revision; mark to show as first-version only.
800 $this->mOldid
= false;
801 $this->mOldRev
= false;
803 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
805 if( is_null( $this->mOldRev
) ) {
809 if ( $this->mOldRev
) {
810 $this->mOldPage
= $this->mOldRev
->getTitle();
812 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
813 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
814 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
815 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
817 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
818 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
819 // Add an "undo" link
820 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
821 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
822 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
823 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
824 $this->mNewtitle
.= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
827 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
828 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
829 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
830 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
838 * Load the text of the revisions, as well as revision data.
840 function loadText() {
841 if ( $this->mTextLoaded
== 2 ) {
844 // Whether it succeeds or fails, we don't want to try again
845 $this->mTextLoaded
= 2;
848 if ( !$this->loadRevisionData() ) {
851 if ( $this->mOldRev
) {
852 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
853 if ( $this->mOldtext
=== false ) {
857 if ( $this->mNewRev
) {
858 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
859 if ( $this->mNewtext
=== false ) {
867 * Load the text of the new revision, not the old one
869 function loadNewText() {
870 if ( $this->mTextLoaded
>= 1 ) {
873 $this->mTextLoaded
= 1;
875 if ( !$this->loadRevisionData() ) {
878 $this->mNewtext
= $this->mNewRev
->getText();
885 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
887 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
888 // You may copy this code freely under the conditions of the GPL.
891 define('USE_ASSERTS', function_exists('assert'));
896 * @ingroup DifferenceEngine
904 trigger_error('pure virtual', E_USER_ERROR
);
908 return $this->orig ?
sizeof($this->orig
) : 0;
911 function nclosing() {
912 return $this->closing ?
sizeof($this->closing
) : 0;
919 * @ingroup DifferenceEngine
921 class _DiffOp_Copy
extends _DiffOp
{
924 function _DiffOp_Copy ($orig, $closing = false) {
925 if (!is_array($closing))
928 $this->closing
= $closing;
932 return new _DiffOp_Copy($this->closing
, $this->orig
);
939 * @ingroup DifferenceEngine
941 class _DiffOp_Delete
extends _DiffOp
{
942 var $type = 'delete';
944 function _DiffOp_Delete ($lines) {
945 $this->orig
= $lines;
946 $this->closing
= false;
950 return new _DiffOp_Add($this->orig
);
957 * @ingroup DifferenceEngine
959 class _DiffOp_Add
extends _DiffOp
{
962 function _DiffOp_Add ($lines) {
963 $this->closing
= $lines;
968 return new _DiffOp_Delete($this->closing
);
975 * @ingroup DifferenceEngine
977 class _DiffOp_Change
extends _DiffOp
{
978 var $type = 'change';
980 function _DiffOp_Change ($orig, $closing) {
982 $this->closing
= $closing;
986 return new _DiffOp_Change($this->closing
, $this->orig
);
991 * Class used internally by Diff to actually compute the diffs.
993 * The algorithm used here is mostly lifted from the perl module
994 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
995 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
997 * More ideas are taken from:
998 * http://www.ics.uci.edu/~eppstein/161/960229.html
1000 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
1001 * diffutils-2.7, which can be found at:
1002 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1004 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1007 * Line length limits for robustness added by Tim Starling, 2005-08-31
1008 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1010 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1012 * @ingroup DifferenceEngine
1016 const MAX_XREF_LENGTH
= 10000;
1018 function diff ($from_lines, $to_lines){
1019 wfProfileIn( __METHOD__
);
1021 // Diff and store locally
1022 $this->diff_local($from_lines, $to_lines);
1024 // Merge edits when possible
1025 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1026 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1028 // Compute the edit operations.
1029 $n_from = sizeof($from_lines);
1030 $n_to = sizeof($to_lines);
1034 while ($xi < $n_from ||
$yi < $n_to) {
1035 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1036 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1038 // Skip matching "snake".
1040 while ( $xi < $n_from && $yi < $n_to
1041 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1042 $copy[] = $from_lines[$xi++
];
1046 $edits[] = new _DiffOp_Copy($copy);
1048 // Find deletes & adds.
1050 while ($xi < $n_from && $this->xchanged
[$xi])
1051 $delete[] = $from_lines[$xi++
];
1054 while ($yi < $n_to && $this->ychanged
[$yi])
1055 $add[] = $to_lines[$yi++
];
1057 if ($delete && $add)
1058 $edits[] = new _DiffOp_Change($delete, $add);
1060 $edits[] = new _DiffOp_Delete($delete);
1062 $edits[] = new _DiffOp_Add($add);
1064 wfProfileOut( __METHOD__
);
1068 function diff_local ($from_lines, $to_lines) {
1069 global $wgExternalDiffEngine;
1070 wfProfileIn( __METHOD__
);
1072 if($wgExternalDiffEngine == 'wikidiff3'){
1074 $wikidiff3 = new WikiDiff3();
1075 $wikidiff3->diff($from_lines, $to_lines);
1076 $this->xchanged
= $wikidiff3->removed
;
1077 $this->ychanged
= $wikidiff3->added
;
1081 $n_from = sizeof($from_lines);
1082 $n_to = sizeof($to_lines);
1083 $this->xchanged
= $this->ychanged
= array();
1084 $this->xv
= $this->yv
= array();
1085 $this->xind
= $this->yind
= array();
1087 unset($this->in_seq
);
1090 // Skip leading common lines.
1091 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1092 if ($from_lines[$skip] !== $to_lines[$skip])
1094 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1096 // Skip trailing common lines.
1097 $xi = $n_from; $yi = $n_to;
1098 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1099 if ($from_lines[$xi] !== $to_lines[$yi])
1101 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1104 // Ignore lines which do not exist in both files.
1105 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1106 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1109 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1110 $line = $to_lines[$yi];
1111 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1113 $yhash[$this->_line_hash($line)] = 1;
1114 $this->yv
[] = $line;
1115 $this->yind
[] = $yi;
1117 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1118 $line = $from_lines[$xi];
1119 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1121 $this->xv
[] = $line;
1122 $this->xind
[] = $xi;
1126 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1128 wfProfileOut( __METHOD__
);
1132 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1134 function _line_hash( $line ) {
1135 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1136 return md5( $line );
1142 /* Divide the Largest Common Subsequence (LCS) of the sequences
1143 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1146 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1147 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1148 * sub sequences. The first sub-sequence is contained in [X0, X1),
1149 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1150 * that (X0, Y0) == (XOFF, YOFF) and
1151 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1153 * This function assumes that the first lines of the specified portions
1154 * of the two files do not match, and likewise that the last lines do not
1155 * match. The caller must trim matching lines from the beginning and end
1156 * of the portions it is going to specify.
1158 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1161 if ($xlim - $xoff > $ylim - $yoff) {
1162 // Things seems faster (I'm not sure I understand why)
1163 // when the shortest sequence in X.
1165 list ($xoff, $xlim, $yoff, $ylim)
1166 = array( $yoff, $ylim, $xoff, $xlim);
1170 for ($i = $ylim - 1; $i >= $yoff; $i--)
1171 $ymatches[$this->xv
[$i]][] = $i;
1173 for ($i = $ylim - 1; $i >= $yoff; $i--)
1174 $ymatches[$this->yv
[$i]][] = $i;
1177 $this->seq
[0]= $yoff - 1;
1178 $this->in_seq
= array();
1179 $ymids[0] = array();
1181 $numer = $xlim - $xoff +
$nchunks - 1;
1183 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1185 for ($i = 0; $i <= $this->lcs
; $i++
)
1186 $ymids[$i][$chunk-1] = $this->seq
[$i];
1188 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1189 for ( ; $x < $x1; $x++
) {
1190 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1191 if (empty($ymatches[$line]))
1193 $matches = $ymatches[$line];
1195 while (list ($junk, $y) = each($matches))
1196 if (empty($this->in_seq
[$y])) {
1197 $k = $this->_lcs_pos($y);
1198 USE_ASSERTS
&& assert($k > 0);
1199 $ymids[$k] = $ymids[$k-1];
1202 while (list ( /* $junk */, $y) = each($matches)) {
1203 if ($y > $this->seq
[$k-1]) {
1204 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1205 // Optimization: this is a common case:
1206 // next match is just replacing previous match.
1207 $this->in_seq
[$this->seq
[$k]] = false;
1208 $this->seq
[$k] = $y;
1209 $this->in_seq
[$y] = 1;
1210 } else if (empty($this->in_seq
[$y])) {
1211 $k = $this->_lcs_pos($y);
1212 USE_ASSERTS
&& assert($k > 0);
1213 $ymids[$k] = $ymids[$k-1];
1219 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1220 $ymid = $ymids[$this->lcs
];
1221 for ($n = 0; $n < $nchunks - 1; $n++
) {
1222 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1223 $y1 = $ymid[$n] +
1;
1224 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1226 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1228 return array($this->lcs
, $seps);
1231 function _lcs_pos ($ypos) {
1233 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1234 $this->seq
[++
$this->lcs
] = $ypos;
1235 $this->in_seq
[$ypos] = 1;
1240 while ($beg < $end) {
1241 $mid = (int)(($beg +
$end) / 2);
1242 if ( $ypos > $this->seq
[$mid] )
1248 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1250 $this->in_seq
[$this->seq
[$end]] = false;
1251 $this->seq
[$end] = $ypos;
1252 $this->in_seq
[$ypos] = 1;
1256 /* Find LCS of two sequences.
1258 * The results are recorded in the vectors $this->{x,y}changed[], by
1259 * storing a 1 in the element for each line that is an insertion
1260 * or deletion (ie. is not in the LCS).
1262 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1264 * Note that XLIM, YLIM are exclusive bounds.
1265 * All line numbers are origin-0 and discarded lines are not counted.
1267 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1268 // Slide down the bottom initial diagonal.
1269 while ($xoff < $xlim && $yoff < $ylim
1270 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1275 // Slide up the top initial diagonal.
1276 while ($xlim > $xoff && $ylim > $yoff
1277 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1282 if ($xoff == $xlim ||
$yoff == $ylim)
1285 // This is ad hoc but seems to work well.
1286 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1287 //$nchunks = max(2,min(8,(int)$nchunks));
1288 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1290 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1294 // X and Y sequences have no common subsequence:
1295 // mark all changed.
1296 while ($yoff < $ylim)
1297 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1298 while ($xoff < $xlim)
1299 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1301 // Use the partitions to split this problem into subproblems.
1304 while ($pt2 = next($seps)) {
1305 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1311 /* Adjust inserts/deletes of identical lines to join changes
1312 * as much as possible.
1314 * We do something when a run of changed lines include a
1315 * line at one end and has an excluded, identical line at the other.
1316 * We are free to choose which identical line is included.
1317 * `compareseq' usually chooses the one at the beginning,
1318 * but usually it is cleaner to consider the following identical line
1319 * to be the "change".
1321 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1323 function _shift_boundaries ($lines, &$changed, $other_changed) {
1324 wfProfileIn( __METHOD__
);
1328 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1329 $len = sizeof($lines);
1330 $other_len = sizeof($other_changed);
1334 * Scan forwards to find beginning of another run of changes.
1335 * Also keep track of the corresponding point in the other file.
1337 * Throughout this code, $i and $j are adjusted together so that
1338 * the first $i elements of $changed and the first $j elements
1339 * of $other_changed both contain the same number of zeros
1340 * (unchanged lines).
1341 * Furthermore, $j is always kept so that $j == $other_len or
1342 * $other_changed[$j] == false.
1344 while ($j < $other_len && $other_changed[$j])
1347 while ($i < $len && ! $changed[$i]) {
1348 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1350 while ($j < $other_len && $other_changed[$j])
1359 // Find the end of this run of changes.
1360 while (++
$i < $len && $changed[$i])
1365 * Record the length of this run of changes, so that
1366 * we can later determine whether the run has grown.
1368 $runlength = $i - $start;
1371 * Move the changed region back, so long as the
1372 * previous unchanged line matches the last changed one.
1373 * This merges with previous changed regions.
1375 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1376 $changed[--$start] = 1;
1377 $changed[--$i] = false;
1378 while ($start > 0 && $changed[$start - 1])
1380 USE_ASSERTS
&& assert('$j > 0');
1381 while ($other_changed[--$j])
1383 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1387 * Set CORRESPONDING to the end of the changed run, at the last
1388 * point where it corresponds to a changed run in the other file.
1389 * CORRESPONDING == LEN means no such point has been found.
1391 $corresponding = $j < $other_len ?
$i : $len;
1394 * Move the changed region forward, so long as the
1395 * first changed line matches the following unchanged one.
1396 * This merges with following changed regions.
1397 * Do this second, so that if there are no merges,
1398 * the changed region is moved forward as far as possible.
1400 while ($i < $len && $lines[$start] == $lines[$i]) {
1401 $changed[$start++
] = false;
1403 while ($i < $len && $changed[$i])
1406 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1408 if ($j < $other_len && $other_changed[$j]) {
1409 $corresponding = $i;
1410 while ($j < $other_len && $other_changed[$j])
1414 } while ($runlength != $i - $start);
1417 * If possible, move the fully-merged run of changes
1418 * back to a corresponding run in the other file.
1420 while ($corresponding < $i) {
1421 $changed[--$start] = 1;
1423 USE_ASSERTS
&& assert('$j > 0');
1424 while ($other_changed[--$j])
1426 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1429 wfProfileOut( __METHOD__
);
1434 * Class representing a 'diff' between two sequences of strings.
1437 * @ingroup DifferenceEngine
1445 * Computes diff between sequences of strings.
1447 * @param $from_lines array An array of strings.
1448 * (Typically these are lines from a file.)
1449 * @param $to_lines array An array of strings.
1451 function Diff($from_lines, $to_lines) {
1452 $eng = new _DiffEngine
;
1453 $this->edits
= $eng->diff($from_lines, $to_lines);
1454 //$this->_check($from_lines, $to_lines);
1458 * Compute reversed Diff.
1462 * $diff = new Diff($lines1, $lines2);
1463 * $rev = $diff->reverse();
1464 * @return object A Diff object representing the inverse of the
1467 function reverse () {
1469 $rev->edits
= array();
1470 foreach ($this->edits
as $edit) {
1471 $rev->edits
[] = $edit->reverse();
1477 * Check for empty diff.
1479 * @return bool True iff two sequences were identical.
1481 function isEmpty () {
1482 foreach ($this->edits
as $edit) {
1483 if ($edit->type
!= 'copy')
1490 * Compute the length of the Longest Common Subsequence (LCS).
1492 * This is mostly for diagnostic purposed.
1494 * @return int The length of the LCS.
1498 foreach ($this->edits
as $edit) {
1499 if ($edit->type
== 'copy')
1500 $lcs +
= sizeof($edit->orig
);
1506 * Get the original set of lines.
1508 * This reconstructs the $from_lines parameter passed to the
1511 * @return array The original sequence of strings.
1516 foreach ($this->edits
as $edit) {
1518 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1524 * Get the closing set of lines.
1526 * This reconstructs the $to_lines parameter passed to the
1529 * @return array The sequence of strings.
1531 function closing() {
1534 foreach ($this->edits
as $edit) {
1536 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1542 * Check a Diff for validity.
1544 * This is here only for debugging purposes.
1546 function _check ($from_lines, $to_lines) {
1547 wfProfileIn( __METHOD__
);
1548 if (serialize($from_lines) != serialize($this->orig()))
1549 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1550 if (serialize($to_lines) != serialize($this->closing()))
1551 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1553 $rev = $this->reverse();
1554 if (serialize($to_lines) != serialize($rev->orig()))
1555 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1556 if (serialize($from_lines) != serialize($rev->closing()))
1557 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1561 foreach ($this->edits
as $edit) {
1562 if ( $prevtype == $edit->type
)
1563 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1564 $prevtype = $edit->type
;
1567 $lcs = $this->lcs();
1568 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1569 wfProfileOut( __METHOD__
);
1574 * @todo document, bad name.
1576 * @ingroup DifferenceEngine
1578 class MappedDiff
extends Diff
1583 * Computes diff between sequences of strings.
1585 * This can be used to compute things like
1586 * case-insensitve diffs, or diffs which ignore
1587 * changes in white-space.
1589 * @param $from_lines array An array of strings.
1590 * (Typically these are lines from a file.)
1592 * @param $to_lines array An array of strings.
1594 * @param $mapped_from_lines array This array should
1595 * have the same size number of elements as $from_lines.
1596 * The elements in $mapped_from_lines and
1597 * $mapped_to_lines are what is actually compared
1598 * when computing the diff.
1600 * @param $mapped_to_lines array This array should
1601 * have the same number of elements as $to_lines.
1603 function MappedDiff($from_lines, $to_lines,
1604 $mapped_from_lines, $mapped_to_lines) {
1605 wfProfileIn( __METHOD__
);
1607 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1608 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1610 $this->Diff($mapped_from_lines, $mapped_to_lines);
1613 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1614 $orig = &$this->edits
[$i]->orig
;
1615 if (is_array($orig)) {
1616 $orig = array_slice($from_lines, $xi, sizeof($orig));
1617 $xi +
= sizeof($orig);
1620 $closing = &$this->edits
[$i]->closing
;
1621 if (is_array($closing)) {
1622 $closing = array_slice($to_lines, $yi, sizeof($closing));
1623 $yi +
= sizeof($closing);
1626 wfProfileOut( __METHOD__
);
1631 * A class to format Diffs
1633 * This class formats the diff in classic diff format.
1634 * It is intended that this class be customized via inheritance,
1635 * to obtain fancier outputs.
1638 * @ingroup DifferenceEngine
1640 class DiffFormatter
{
1642 * Number of leading 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 $leading_context_lines = 0;
1650 * Number of trailing context "lines" to preserve.
1652 * This should be left at zero for this class, but subclasses
1653 * may want to set this to other values.
1655 var $trailing_context_lines = 0;
1660 * @param $diff object A Diff object.
1661 * @return string The formatted output.
1663 function format($diff) {
1664 wfProfileIn( __METHOD__
);
1670 $nlead = $this->leading_context_lines
;
1671 $ntrail = $this->trailing_context_lines
;
1673 $this->_start_diff();
1675 foreach ($diff->edits
as $edit) {
1676 if ($edit->type
== 'copy') {
1677 if (is_array($block)) {
1678 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1683 $context = array_slice($edit->orig
, 0, $ntrail);
1684 $block[] = new _DiffOp_Copy($context);
1686 $this->_block($x0, $ntrail +
$xi - $x0,
1687 $y0, $ntrail +
$yi - $y0,
1692 $context = $edit->orig
;
1695 if (! is_array($block)) {
1696 $context = array_slice($context, sizeof($context) - $nlead);
1697 $x0 = $xi - sizeof($context);
1698 $y0 = $yi - sizeof($context);
1701 $block[] = new _DiffOp_Copy($context);
1707 $xi +
= sizeof($edit->orig
);
1709 $yi +
= sizeof($edit->closing
);
1712 if (is_array($block))
1713 $this->_block($x0, $xi - $x0,
1717 $end = $this->_end_diff();
1718 wfProfileOut( __METHOD__
);
1722 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1723 wfProfileIn( __METHOD__
);
1724 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1725 foreach ($edits as $edit) {
1726 if ($edit->type
== 'copy')
1727 $this->_context($edit->orig
);
1728 elseif ($edit->type
== 'add')
1729 $this->_added($edit->closing
);
1730 elseif ($edit->type
== 'delete')
1731 $this->_deleted($edit->orig
);
1732 elseif ($edit->type
== 'change')
1733 $this->_changed($edit->orig
, $edit->closing
);
1735 trigger_error('Unknown edit type', E_USER_ERROR
);
1737 $this->_end_block();
1738 wfProfileOut( __METHOD__
);
1741 function _start_diff() {
1745 function _end_diff() {
1746 $val = ob_get_contents();
1751 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1753 $xbeg .= "," . ($xbeg +
$xlen - 1);
1755 $ybeg .= "," . ($ybeg +
$ylen - 1);
1757 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1760 function _start_block($header) {
1761 echo $header . "\n";
1764 function _end_block() {
1767 function _lines($lines, $prefix = ' ') {
1768 foreach ($lines as $line)
1769 echo "$prefix $line\n";
1772 function _context($lines) {
1773 $this->_lines($lines);
1776 function _added($lines) {
1777 $this->_lines($lines, '>');
1779 function _deleted($lines) {
1780 $this->_lines($lines, '<');
1783 function _changed($orig, $closing) {
1784 $this->_deleted($orig);
1786 $this->_added($closing);
1791 * A formatter that outputs unified diffs
1792 * @ingroup DifferenceEngine
1795 class UnifiedDiffFormatter
extends DiffFormatter
{
1796 var $leading_context_lines = 2;
1797 var $trailing_context_lines = 2;
1799 function _added($lines) {
1800 $this->_lines($lines, '+');
1802 function _deleted($lines) {
1803 $this->_lines($lines, '-');
1805 function _changed($orig, $closing) {
1806 $this->_deleted($orig);
1807 $this->_added($closing);
1809 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1810 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1815 * A pseudo-formatter that just passes along the Diff::$edits array
1816 * @ingroup DifferenceEngine
1818 class ArrayDiffFormatter
extends DiffFormatter
{
1819 function format($diff) {
1823 foreach($diff->edits
as $edit)
1824 switch($edit->type
) {
1826 foreach($edit->closing
as $l) {
1830 'newline' => $newline++
1835 foreach($edit->orig
as $l) {
1837 'action' => 'delete',
1839 'oldline' => $oldline++
,
1844 foreach($edit->orig
as $i => $l) {
1846 'action' => 'change',
1848 'new' => @$edit->closing
[$i],
1849 'oldline' => $oldline++
,
1850 'newline' => $newline++
,
1855 $oldline +
= count($edit->orig
);
1856 $newline +
= count($edit->orig
);
1863 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1867 define('NBSP', ' '); // iso-8859-x non-breaking space.
1872 * @ingroup DifferenceEngine
1874 class _HWLDF_WordAccumulator
{
1875 function _HWLDF_WordAccumulator () {
1876 $this->_lines
= array();
1882 function _flushGroup ($new_tag) {
1883 if ($this->_group
!== '') {
1884 if ($this->_tag
== 'ins')
1885 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1886 htmlspecialchars ( $this->_group
) . '</ins>';
1887 elseif ($this->_tag
== 'del')
1888 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1889 htmlspecialchars ( $this->_group
) . '</del>';
1891 $this->_line
.= htmlspecialchars ( $this->_group
);
1894 $this->_tag
= $new_tag;
1897 function _flushLine ($new_tag) {
1898 $this->_flushGroup($new_tag);
1899 if ($this->_line
!= '')
1900 array_push ( $this->_lines
, $this->_line
);
1902 # make empty lines visible by inserting an NBSP
1903 array_push ( $this->_lines
, NBSP
);
1907 function addWords ($words, $tag = '') {
1908 if ($tag != $this->_tag
)
1909 $this->_flushGroup($tag);
1911 foreach ($words as $word) {
1912 // new-line should only come as first char of word.
1915 if ($word[0] == "\n") {
1916 $this->_flushLine($tag);
1917 $word = substr($word, 1);
1919 assert(!strstr($word, "\n"));
1920 $this->_group
.= $word;
1924 function getLines() {
1925 $this->_flushLine('~done');
1926 return $this->_lines
;
1933 * @ingroup DifferenceEngine
1935 class WordLevelDiff
extends MappedDiff
{
1936 const MAX_LINE_LENGTH
= 10000;
1938 function WordLevelDiff ($orig_lines, $closing_lines) {
1939 wfProfileIn( __METHOD__
);
1941 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1942 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1944 $this->MappedDiff($orig_words, $closing_words,
1945 $orig_stripped, $closing_stripped);
1946 wfProfileOut( __METHOD__
);
1949 function _split($lines) {
1950 wfProfileIn( __METHOD__
);
1953 $stripped = array();
1955 foreach ( $lines as $line ) {
1956 # If the line is too long, just pretend the entire line is one big word
1957 # This prevents resource exhaustion problems
1964 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1966 $stripped[] = $line;
1969 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1972 $words = array_merge( $words, $m[0] );
1973 $stripped = array_merge( $stripped, $m[1] );
1977 wfProfileOut( __METHOD__
);
1978 return array($words, $stripped);
1982 wfProfileIn( __METHOD__
);
1983 $orig = new _HWLDF_WordAccumulator
;
1985 foreach ($this->edits
as $edit) {
1986 if ($edit->type
== 'copy')
1987 $orig->addWords($edit->orig
);
1988 elseif ($edit->orig
)
1989 $orig->addWords($edit->orig
, 'del');
1991 $lines = $orig->getLines();
1992 wfProfileOut( __METHOD__
);
1996 function closing () {
1997 wfProfileIn( __METHOD__
);
1998 $closing = new _HWLDF_WordAccumulator
;
2000 foreach ($this->edits
as $edit) {
2001 if ($edit->type
== 'copy')
2002 $closing->addWords($edit->closing
);
2003 elseif ($edit->closing
)
2004 $closing->addWords($edit->closing
, 'ins');
2006 $lines = $closing->getLines();
2007 wfProfileOut( __METHOD__
);
2013 * Wikipedia Table style diff formatter.
2016 * @ingroup DifferenceEngine
2018 class TableDiffFormatter
extends DiffFormatter
{
2019 function TableDiffFormatter() {
2020 $this->leading_context_lines
= 2;
2021 $this->trailing_context_lines
= 2;
2024 public static function escapeWhiteSpace( $msg ) {
2025 $msg = preg_replace( '/^ /m', ' ', $msg );
2026 $msg = preg_replace( '/ $/m', ' ', $msg );
2027 $msg = preg_replace( '/ /', ' ', $msg );
2031 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2032 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2033 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2037 function _start_block( $header ) {
2041 function _end_block() {
2044 function _lines( $lines, $prefix=' ', $color='white' ) {
2047 # HTML-escape parameter before calling this
2048 function addedLine( $line ) {
2049 return $this->wrapLine( '+', 'diff-addedline', $line );
2052 # HTML-escape parameter before calling this
2053 function deletedLine( $line ) {
2054 return $this->wrapLine( '-', 'diff-deletedline', $line );
2057 # HTML-escape parameter before calling this
2058 function contextLine( $line ) {
2059 return $this->wrapLine( ' ', 'diff-context', $line );
2062 private function wrapLine( $marker, $class, $line ) {
2063 if( $line !== '' ) {
2064 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2065 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2067 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2070 function emptyLine() {
2071 return '<td colspan="2"> </td>';
2074 function _added( $lines ) {
2075 foreach ($lines as $line) {
2076 echo '<tr>' . $this->emptyLine() .
2077 $this->addedLine( '<ins class="diffchange">' .
2078 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2082 function _deleted($lines) {
2083 foreach ($lines as $line) {
2084 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2085 htmlspecialchars ( $line ) . '</del>' ) .
2086 $this->emptyLine() . "</tr>\n";
2090 function _context( $lines ) {
2091 foreach ($lines as $line) {
2093 $this->contextLine( htmlspecialchars ( $line ) ) .
2094 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2098 function _changed( $orig, $closing ) {
2099 wfProfileIn( __METHOD__
);
2101 $diff = new WordLevelDiff( $orig, $closing );
2102 $del = $diff->orig();
2103 $add = $diff->closing();
2105 # Notice that WordLevelDiff returns HTML-escaped output.
2106 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2108 while ( $line = array_shift( $del ) ) {
2109 $aline = array_shift( $add );
2110 echo '<tr>' . $this->deletedLine( $line ) .
2111 $this->addedLine( $aline ) . "</tr>\n";
2113 foreach ($add as $line) { # If any leftovers
2114 echo '<tr>' . $this->emptyLine() .
2115 $this->addedLine( $line ) . "</tr>\n";
2117 wfProfileOut( __METHOD__
);