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, $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 ( $key !== false && $difftext !== false ) {
550 wfIncrStats( 'diff_cache_miss' );
551 $wgMemc->set( $key, $difftext, 7*86400 );
553 wfIncrStats( 'diff_uncacheable' );
555 // Replace line numbers with the text in the user's language
556 if ( $difftext !== false ) {
557 $difftext = $this->localiseLineNumbers( $difftext );
559 wfProfileOut( __METHOD__
);
564 * Generate a diff, no caching
565 * $otext and $ntext must be already segmented
567 function generateDiffBody( $otext, $ntext ) {
568 global $wgExternalDiffEngine, $wgContLang;
570 $otext = str_replace( "\r\n", "\n", $otext );
571 $ntext = str_replace( "\r\n", "\n", $ntext );
573 if ( $wgExternalDiffEngine == 'wikidiff' ) {
574 # For historical reasons, external diff engine expects
575 # input text to be HTML-escaped already
576 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
577 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
578 if( !function_exists( 'wikidiff_do_diff' ) ) {
579 dl('php_wikidiff.so');
581 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
582 $this->debug( 'wikidiff1' );
585 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
586 # Better external diff engine, the 2 may some day be dropped
587 # This one does the escaping and segmenting itself
588 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
589 wfProfileIn( __METHOD__
. "-dl" );
590 @dl
('php_wikidiff2.so');
591 wfProfileOut( __METHOD__
. "-dl" );
593 if ( function_exists( 'wikidiff2_do_diff' ) ) {
594 wfProfileIn( 'wikidiff2_do_diff' );
595 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
596 $text .= $this->debug( 'wikidiff2' );
597 wfProfileOut( 'wikidiff2_do_diff' );
601 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
603 global $wgTmpDirectory;
604 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
605 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
607 $tempFile1 = fopen( $tempName1, "w" );
609 wfProfileOut( __METHOD__
);
612 $tempFile2 = fopen( $tempName2, "w" );
614 wfProfileOut( __METHOD__
);
617 fwrite( $tempFile1, $otext );
618 fwrite( $tempFile2, $ntext );
619 fclose( $tempFile1 );
620 fclose( $tempFile2 );
621 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
622 wfProfileIn( __METHOD__
. "-shellexec" );
623 $difftext = wfShellExec( $cmd );
624 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
625 wfProfileOut( __METHOD__
. "-shellexec" );
626 unlink( $tempName1 );
627 unlink( $tempName2 );
632 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
633 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
634 $diffs = new Diff( $ota, $nta );
635 $formatter = new TableDiffFormatter();
636 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
641 * Generate a debug comment indicating diff generating time,
642 * server node, and generator backend.
644 protected function debug( $generator="internal" ) {
645 global $wgShowHostnames, $wgNodeName;
646 $data = array( $generator );
647 if( $wgShowHostnames ) {
648 $data[] = $wgNodeName;
650 $data[] = wfTimestamp( TS_DB
);
651 return "<!-- diff generator: " .
660 * Replace line numbers with the text in the user's language
662 function localiseLineNumbers( $text ) {
663 return preg_replace_callback( '/<!--LINE (\d+)-->/',
664 array( &$this, 'localiseLineNumbersCb' ), $text );
667 function localiseLineNumbersCb( $matches ) {
669 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
674 * If there are revisions between the ones being compared, return a note saying so.
676 function getMultiNotice() {
677 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
680 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
681 // Comparing two different pages? Count would be meaningless.
685 $oldid = $this->mOldRev
->getId();
686 $newid = $this->mNewRev
->getId();
687 if ( $oldid > $newid ) {
688 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
691 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
695 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
700 * Add the header to a diff body
702 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
705 <col class='diff-marker' />
706 <col class='diff-content' />
707 <col class='diff-marker' />
708 <col class='diff-content' />
710 <td colspan='2' class='diff-otitle'>{$otitle}</td>
711 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
716 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
718 return $header . $diff . "</table>";
722 * Use specified text instead of loading from the database
724 function setText( $oldText, $newText ) {
725 $this->mOldtext
= $oldText;
726 $this->mNewtext
= $newText;
727 $this->mTextLoaded
= 2;
731 * Load revision metadata for the specified articles. If newid is 0, then compare
732 * the old article in oldid to the current article; if oldid is 0, then
733 * compare the current article to the immediately previous one (ignoring the
736 * If oldid is false, leave the corresponding revision object set
737 * to false. This is impossible via ordinary user input, and is provided for
740 function loadRevisionData() {
742 if ( $this->mRevisionsLoaded
) {
745 // Whether it succeeds or fails, we don't want to try again
746 $this->mRevisionsLoaded
= true;
749 // Load the new revision object
750 $this->mNewRev
= $this->mNewid
751 ? Revision
::newFromId( $this->mNewid
)
752 : Revision
::newFromTitle( $this->mTitle
);
753 if( !$this->mNewRev
instanceof Revision
)
756 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
757 $this->mNewid
= $this->mNewRev
->getId();
759 // Check if page is editable
760 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
762 // Set assorted variables
763 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
764 $this->mNewPage
= $this->mNewRev
->getTitle();
765 if( $this->mNewRev
->isCurrent() ) {
766 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
767 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
768 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
770 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
771 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
774 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
775 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
776 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
778 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
779 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
781 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
782 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
783 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
784 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
787 // Load the old revision object
788 $this->mOldRev
= false;
789 if( $this->mOldid
) {
790 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
791 } elseif ( $this->mOldid
=== 0 ) {
792 $rev = $this->mNewRev
->getPrevious();
794 $this->mOldid
= $rev->getId();
795 $this->mOldRev
= $rev;
797 // No previous revision; mark to show as first-version only.
798 $this->mOldid
= false;
799 $this->mOldRev
= false;
801 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
803 if( is_null( $this->mOldRev
) ) {
807 if ( $this->mOldRev
) {
808 $this->mOldPage
= $this->mOldRev
->getTitle();
810 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
811 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
812 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
813 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
815 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
816 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
817 // Add an "undo" link
818 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
819 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
820 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
823 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
824 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
825 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
826 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
834 * Load the text of the revisions, as well as revision data.
836 function loadText() {
837 if ( $this->mTextLoaded
== 2 ) {
840 // Whether it succeeds or fails, we don't want to try again
841 $this->mTextLoaded
= 2;
844 if ( !$this->loadRevisionData() ) {
847 if ( $this->mOldRev
) {
848 $this->mOldtext
= $this->mOldRev
->revText();
849 if ( $this->mOldtext
=== false ) {
853 if ( $this->mNewRev
) {
854 $this->mNewtext
= $this->mNewRev
->revText();
855 if ( $this->mNewtext
=== false ) {
863 * Load the text of the new revision, not the old one
865 function loadNewText() {
866 if ( $this->mTextLoaded
>= 1 ) {
869 $this->mTextLoaded
= 1;
871 if ( !$this->loadRevisionData() ) {
874 $this->mNewtext
= $this->mNewRev
->getText();
881 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
883 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
884 // You may copy this code freely under the conditions of the GPL.
887 define('USE_ASSERTS', function_exists('assert'));
892 * @ingroup DifferenceEngine
900 trigger_error('pure virtual', E_USER_ERROR
);
904 return $this->orig ?
sizeof($this->orig
) : 0;
907 function nclosing() {
908 return $this->closing ?
sizeof($this->closing
) : 0;
915 * @ingroup DifferenceEngine
917 class _DiffOp_Copy
extends _DiffOp
{
920 function _DiffOp_Copy ($orig, $closing = false) {
921 if (!is_array($closing))
924 $this->closing
= $closing;
928 return new _DiffOp_Copy($this->closing
, $this->orig
);
935 * @ingroup DifferenceEngine
937 class _DiffOp_Delete
extends _DiffOp
{
938 var $type = 'delete';
940 function _DiffOp_Delete ($lines) {
941 $this->orig
= $lines;
942 $this->closing
= false;
946 return new _DiffOp_Add($this->orig
);
953 * @ingroup DifferenceEngine
955 class _DiffOp_Add
extends _DiffOp
{
958 function _DiffOp_Add ($lines) {
959 $this->closing
= $lines;
964 return new _DiffOp_Delete($this->closing
);
971 * @ingroup DifferenceEngine
973 class _DiffOp_Change
extends _DiffOp
{
974 var $type = 'change';
976 function _DiffOp_Change ($orig, $closing) {
978 $this->closing
= $closing;
982 return new _DiffOp_Change($this->closing
, $this->orig
);
987 * Class used internally by Diff to actually compute the diffs.
989 * The algorithm used here is mostly lifted from the perl module
990 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
991 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
993 * More ideas are taken from:
994 * http://www.ics.uci.edu/~eppstein/161/960229.html
996 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
997 * diffutils-2.7, which can be found at:
998 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1000 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1003 * Line length limits for robustness added by Tim Starling, 2005-08-31
1004 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1006 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1008 * @ingroup DifferenceEngine
1012 const MAX_XREF_LENGTH
= 10000;
1014 function diff ($from_lines, $to_lines){
1015 wfProfileIn( __METHOD__
);
1017 // Diff and store locally
1018 $this->diff_local($from_lines, $to_lines);
1020 // Merge edits when possible
1021 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
1022 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
1024 // Compute the edit operations.
1025 $n_from = sizeof($from_lines);
1026 $n_to = sizeof($to_lines);
1030 while ($xi < $n_from ||
$yi < $n_to) {
1031 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1032 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1034 // Skip matching "snake".
1036 while ( $xi < $n_from && $yi < $n_to
1037 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1038 $copy[] = $from_lines[$xi++
];
1042 $edits[] = new _DiffOp_Copy($copy);
1044 // Find deletes & adds.
1046 while ($xi < $n_from && $this->xchanged
[$xi])
1047 $delete[] = $from_lines[$xi++
];
1050 while ($yi < $n_to && $this->ychanged
[$yi])
1051 $add[] = $to_lines[$yi++
];
1053 if ($delete && $add)
1054 $edits[] = new _DiffOp_Change($delete, $add);
1056 $edits[] = new _DiffOp_Delete($delete);
1058 $edits[] = new _DiffOp_Add($add);
1060 wfProfileOut( __METHOD__
);
1064 function diff_local ($from_lines, $to_lines) {
1065 global $wgExternalDiffEngine;
1066 wfProfileIn( __METHOD__
);
1068 if($wgExternalDiffEngine == 'wikidiff3'){
1070 $wikidiff3 = new WikiDiff3();
1071 $wikidiff3->diff($from_lines, $to_lines);
1072 $this->xchanged
= $wikidiff3->removed
;
1073 $this->ychanged
= $wikidiff3->added
;
1077 $n_from = sizeof($from_lines);
1078 $n_to = sizeof($to_lines);
1079 $this->xchanged
= $this->ychanged
= array();
1080 $this->xv
= $this->yv
= array();
1081 $this->xind
= $this->yind
= array();
1083 unset($this->in_seq
);
1086 // Skip leading common lines.
1087 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1088 if ($from_lines[$skip] !== $to_lines[$skip])
1090 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1092 // Skip trailing common lines.
1093 $xi = $n_from; $yi = $n_to;
1094 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1095 if ($from_lines[$xi] !== $to_lines[$yi])
1097 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1100 // Ignore lines which do not exist in both files.
1101 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1102 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1105 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1106 $line = $to_lines[$yi];
1107 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1109 $yhash[$this->_line_hash($line)] = 1;
1110 $this->yv
[] = $line;
1111 $this->yind
[] = $yi;
1113 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1114 $line = $from_lines[$xi];
1115 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1117 $this->xv
[] = $line;
1118 $this->xind
[] = $xi;
1122 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1124 wfProfileOut( __METHOD__
);
1128 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1130 function _line_hash( $line ) {
1131 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1132 return md5( $line );
1138 /* Divide the Largest Common Subsequence (LCS) of the sequences
1139 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1142 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1143 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1144 * sub sequences. The first sub-sequence is contained in [X0, X1),
1145 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1146 * that (X0, Y0) == (XOFF, YOFF) and
1147 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1149 * This function assumes that the first lines of the specified portions
1150 * of the two files do not match, and likewise that the last lines do not
1151 * match. The caller must trim matching lines from the beginning and end
1152 * of the portions it is going to specify.
1154 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1157 if ($xlim - $xoff > $ylim - $yoff) {
1158 // Things seems faster (I'm not sure I understand why)
1159 // when the shortest sequence in X.
1161 list ($xoff, $xlim, $yoff, $ylim)
1162 = array( $yoff, $ylim, $xoff, $xlim);
1166 for ($i = $ylim - 1; $i >= $yoff; $i--)
1167 $ymatches[$this->xv
[$i]][] = $i;
1169 for ($i = $ylim - 1; $i >= $yoff; $i--)
1170 $ymatches[$this->yv
[$i]][] = $i;
1173 $this->seq
[0]= $yoff - 1;
1174 $this->in_seq
= array();
1175 $ymids[0] = array();
1177 $numer = $xlim - $xoff +
$nchunks - 1;
1179 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1181 for ($i = 0; $i <= $this->lcs
; $i++
)
1182 $ymids[$i][$chunk-1] = $this->seq
[$i];
1184 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1185 for ( ; $x < $x1; $x++
) {
1186 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1187 if (empty($ymatches[$line]))
1189 $matches = $ymatches[$line];
1191 while (list ($junk, $y) = each($matches))
1192 if (empty($this->in_seq
[$y])) {
1193 $k = $this->_lcs_pos($y);
1194 USE_ASSERTS
&& assert($k > 0);
1195 $ymids[$k] = $ymids[$k-1];
1198 while (list ( /* $junk */, $y) = each($matches)) {
1199 if ($y > $this->seq
[$k-1]) {
1200 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1201 // Optimization: this is a common case:
1202 // next match is just replacing previous match.
1203 $this->in_seq
[$this->seq
[$k]] = false;
1204 $this->seq
[$k] = $y;
1205 $this->in_seq
[$y] = 1;
1206 } else if (empty($this->in_seq
[$y])) {
1207 $k = $this->_lcs_pos($y);
1208 USE_ASSERTS
&& assert($k > 0);
1209 $ymids[$k] = $ymids[$k-1];
1215 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1216 $ymid = $ymids[$this->lcs
];
1217 for ($n = 0; $n < $nchunks - 1; $n++
) {
1218 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1219 $y1 = $ymid[$n] +
1;
1220 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1222 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1224 return array($this->lcs
, $seps);
1227 function _lcs_pos ($ypos) {
1229 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1230 $this->seq
[++
$this->lcs
] = $ypos;
1231 $this->in_seq
[$ypos] = 1;
1236 while ($beg < $end) {
1237 $mid = (int)(($beg +
$end) / 2);
1238 if ( $ypos > $this->seq
[$mid] )
1244 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1246 $this->in_seq
[$this->seq
[$end]] = false;
1247 $this->seq
[$end] = $ypos;
1248 $this->in_seq
[$ypos] = 1;
1252 /* Find LCS of two sequences.
1254 * The results are recorded in the vectors $this->{x,y}changed[], by
1255 * storing a 1 in the element for each line that is an insertion
1256 * or deletion (ie. is not in the LCS).
1258 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1260 * Note that XLIM, YLIM are exclusive bounds.
1261 * All line numbers are origin-0 and discarded lines are not counted.
1263 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1264 // Slide down the bottom initial diagonal.
1265 while ($xoff < $xlim && $yoff < $ylim
1266 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1271 // Slide up the top initial diagonal.
1272 while ($xlim > $xoff && $ylim > $yoff
1273 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1278 if ($xoff == $xlim ||
$yoff == $ylim)
1281 // This is ad hoc but seems to work well.
1282 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1283 //$nchunks = max(2,min(8,(int)$nchunks));
1284 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1286 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1290 // X and Y sequences have no common subsequence:
1291 // mark all changed.
1292 while ($yoff < $ylim)
1293 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1294 while ($xoff < $xlim)
1295 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1297 // Use the partitions to split this problem into subproblems.
1300 while ($pt2 = next($seps)) {
1301 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1307 /* Adjust inserts/deletes of identical lines to join changes
1308 * as much as possible.
1310 * We do something when a run of changed lines include a
1311 * line at one end and has an excluded, identical line at the other.
1312 * We are free to choose which identical line is included.
1313 * `compareseq' usually chooses the one at the beginning,
1314 * but usually it is cleaner to consider the following identical line
1315 * to be the "change".
1317 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1319 function _shift_boundaries ($lines, &$changed, $other_changed) {
1320 wfProfileIn( __METHOD__
);
1324 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1325 $len = sizeof($lines);
1326 $other_len = sizeof($other_changed);
1330 * Scan forwards to find beginning of another run of changes.
1331 * Also keep track of the corresponding point in the other file.
1333 * Throughout this code, $i and $j are adjusted together so that
1334 * the first $i elements of $changed and the first $j elements
1335 * of $other_changed both contain the same number of zeros
1336 * (unchanged lines).
1337 * Furthermore, $j is always kept so that $j == $other_len or
1338 * $other_changed[$j] == false.
1340 while ($j < $other_len && $other_changed[$j])
1343 while ($i < $len && ! $changed[$i]) {
1344 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1346 while ($j < $other_len && $other_changed[$j])
1355 // Find the end of this run of changes.
1356 while (++
$i < $len && $changed[$i])
1361 * Record the length of this run of changes, so that
1362 * we can later determine whether the run has grown.
1364 $runlength = $i - $start;
1367 * Move the changed region back, so long as the
1368 * previous unchanged line matches the last changed one.
1369 * This merges with previous changed regions.
1371 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1372 $changed[--$start] = 1;
1373 $changed[--$i] = false;
1374 while ($start > 0 && $changed[$start - 1])
1376 USE_ASSERTS
&& assert('$j > 0');
1377 while ($other_changed[--$j])
1379 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1383 * Set CORRESPONDING to the end of the changed run, at the last
1384 * point where it corresponds to a changed run in the other file.
1385 * CORRESPONDING == LEN means no such point has been found.
1387 $corresponding = $j < $other_len ?
$i : $len;
1390 * Move the changed region forward, so long as the
1391 * first changed line matches the following unchanged one.
1392 * This merges with following changed regions.
1393 * Do this second, so that if there are no merges,
1394 * the changed region is moved forward as far as possible.
1396 while ($i < $len && $lines[$start] == $lines[$i]) {
1397 $changed[$start++
] = false;
1399 while ($i < $len && $changed[$i])
1402 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1404 if ($j < $other_len && $other_changed[$j]) {
1405 $corresponding = $i;
1406 while ($j < $other_len && $other_changed[$j])
1410 } while ($runlength != $i - $start);
1413 * If possible, move the fully-merged run of changes
1414 * back to a corresponding run in the other file.
1416 while ($corresponding < $i) {
1417 $changed[--$start] = 1;
1419 USE_ASSERTS
&& assert('$j > 0');
1420 while ($other_changed[--$j])
1422 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1425 wfProfileOut( __METHOD__
);
1430 * Class representing a 'diff' between two sequences of strings.
1433 * @ingroup DifferenceEngine
1441 * Computes diff between sequences of strings.
1443 * @param $from_lines array An array of strings.
1444 * (Typically these are lines from a file.)
1445 * @param $to_lines array An array of strings.
1447 function Diff($from_lines, $to_lines) {
1448 $eng = new _DiffEngine
;
1449 $this->edits
= $eng->diff($from_lines, $to_lines);
1450 //$this->_check($from_lines, $to_lines);
1454 * Compute reversed Diff.
1458 * $diff = new Diff($lines1, $lines2);
1459 * $rev = $diff->reverse();
1460 * @return object A Diff object representing the inverse of the
1463 function reverse () {
1465 $rev->edits
= array();
1466 foreach ($this->edits
as $edit) {
1467 $rev->edits
[] = $edit->reverse();
1473 * Check for empty diff.
1475 * @return bool True iff two sequences were identical.
1477 function isEmpty () {
1478 foreach ($this->edits
as $edit) {
1479 if ($edit->type
!= 'copy')
1486 * Compute the length of the Longest Common Subsequence (LCS).
1488 * This is mostly for diagnostic purposed.
1490 * @return int The length of the LCS.
1494 foreach ($this->edits
as $edit) {
1495 if ($edit->type
== 'copy')
1496 $lcs +
= sizeof($edit->orig
);
1502 * Get the original set of lines.
1504 * This reconstructs the $from_lines parameter passed to the
1507 * @return array The original sequence of strings.
1512 foreach ($this->edits
as $edit) {
1514 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1520 * Get the closing set of lines.
1522 * This reconstructs the $to_lines parameter passed to the
1525 * @return array The sequence of strings.
1527 function closing() {
1530 foreach ($this->edits
as $edit) {
1532 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1538 * Check a Diff for validity.
1540 * This is here only for debugging purposes.
1542 function _check ($from_lines, $to_lines) {
1543 wfProfileIn( __METHOD__
);
1544 if (serialize($from_lines) != serialize($this->orig()))
1545 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1546 if (serialize($to_lines) != serialize($this->closing()))
1547 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1549 $rev = $this->reverse();
1550 if (serialize($to_lines) != serialize($rev->orig()))
1551 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1552 if (serialize($from_lines) != serialize($rev->closing()))
1553 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1557 foreach ($this->edits
as $edit) {
1558 if ( $prevtype == $edit->type
)
1559 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1560 $prevtype = $edit->type
;
1563 $lcs = $this->lcs();
1564 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1565 wfProfileOut( __METHOD__
);
1570 * @todo document, bad name.
1572 * @ingroup DifferenceEngine
1574 class MappedDiff
extends Diff
1579 * Computes diff between sequences of strings.
1581 * This can be used to compute things like
1582 * case-insensitve diffs, or diffs which ignore
1583 * changes in white-space.
1585 * @param $from_lines array An array of strings.
1586 * (Typically these are lines from a file.)
1588 * @param $to_lines array An array of strings.
1590 * @param $mapped_from_lines array This array should
1591 * have the same size number of elements as $from_lines.
1592 * The elements in $mapped_from_lines and
1593 * $mapped_to_lines are what is actually compared
1594 * when computing the diff.
1596 * @param $mapped_to_lines array This array should
1597 * have the same number of elements as $to_lines.
1599 function MappedDiff($from_lines, $to_lines,
1600 $mapped_from_lines, $mapped_to_lines) {
1601 wfProfileIn( __METHOD__
);
1603 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1604 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1606 $this->Diff($mapped_from_lines, $mapped_to_lines);
1609 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1610 $orig = &$this->edits
[$i]->orig
;
1611 if (is_array($orig)) {
1612 $orig = array_slice($from_lines, $xi, sizeof($orig));
1613 $xi +
= sizeof($orig);
1616 $closing = &$this->edits
[$i]->closing
;
1617 if (is_array($closing)) {
1618 $closing = array_slice($to_lines, $yi, sizeof($closing));
1619 $yi +
= sizeof($closing);
1622 wfProfileOut( __METHOD__
);
1627 * A class to format Diffs
1629 * This class formats the diff in classic diff format.
1630 * It is intended that this class be customized via inheritance,
1631 * to obtain fancier outputs.
1634 * @ingroup DifferenceEngine
1636 class DiffFormatter
{
1638 * Number of leading context "lines" to preserve.
1640 * This should be left at zero for this class, but subclasses
1641 * may want to set this to other values.
1643 var $leading_context_lines = 0;
1646 * Number of trailing context "lines" to preserve.
1648 * This should be left at zero for this class, but subclasses
1649 * may want to set this to other values.
1651 var $trailing_context_lines = 0;
1656 * @param $diff object A Diff object.
1657 * @return string The formatted output.
1659 function format($diff) {
1660 wfProfileIn( __METHOD__
);
1666 $nlead = $this->leading_context_lines
;
1667 $ntrail = $this->trailing_context_lines
;
1669 $this->_start_diff();
1671 foreach ($diff->edits
as $edit) {
1672 if ($edit->type
== 'copy') {
1673 if (is_array($block)) {
1674 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1679 $context = array_slice($edit->orig
, 0, $ntrail);
1680 $block[] = new _DiffOp_Copy($context);
1682 $this->_block($x0, $ntrail +
$xi - $x0,
1683 $y0, $ntrail +
$yi - $y0,
1688 $context = $edit->orig
;
1691 if (! is_array($block)) {
1692 $context = array_slice($context, sizeof($context) - $nlead);
1693 $x0 = $xi - sizeof($context);
1694 $y0 = $yi - sizeof($context);
1697 $block[] = new _DiffOp_Copy($context);
1703 $xi +
= sizeof($edit->orig
);
1705 $yi +
= sizeof($edit->closing
);
1708 if (is_array($block))
1709 $this->_block($x0, $xi - $x0,
1713 $end = $this->_end_diff();
1714 wfProfileOut( __METHOD__
);
1718 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1719 wfProfileIn( __METHOD__
);
1720 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1721 foreach ($edits as $edit) {
1722 if ($edit->type
== 'copy')
1723 $this->_context($edit->orig
);
1724 elseif ($edit->type
== 'add')
1725 $this->_added($edit->closing
);
1726 elseif ($edit->type
== 'delete')
1727 $this->_deleted($edit->orig
);
1728 elseif ($edit->type
== 'change')
1729 $this->_changed($edit->orig
, $edit->closing
);
1731 trigger_error('Unknown edit type', E_USER_ERROR
);
1733 $this->_end_block();
1734 wfProfileOut( __METHOD__
);
1737 function _start_diff() {
1741 function _end_diff() {
1742 $val = ob_get_contents();
1747 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1749 $xbeg .= "," . ($xbeg +
$xlen - 1);
1751 $ybeg .= "," . ($ybeg +
$ylen - 1);
1753 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1756 function _start_block($header) {
1757 echo $header . "\n";
1760 function _end_block() {
1763 function _lines($lines, $prefix = ' ') {
1764 foreach ($lines as $line)
1765 echo "$prefix $line\n";
1768 function _context($lines) {
1769 $this->_lines($lines);
1772 function _added($lines) {
1773 $this->_lines($lines, '>');
1775 function _deleted($lines) {
1776 $this->_lines($lines, '<');
1779 function _changed($orig, $closing) {
1780 $this->_deleted($orig);
1782 $this->_added($closing);
1787 * A formatter that outputs unified diffs
1788 * @ingroup DifferenceEngine
1791 class UnifiedDiffFormatter
extends DiffFormatter
{
1792 var $leading_context_lines = 2;
1793 var $trailing_context_lines = 2;
1795 function _added($lines) {
1796 $this->_lines($lines, '+');
1798 function _deleted($lines) {
1799 $this->_lines($lines, '-');
1801 function _changed($orig, $closing) {
1802 $this->_deleted($orig);
1803 $this->_added($closing);
1805 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1806 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1811 * A pseudo-formatter that just passes along the Diff::$edits array
1812 * @ingroup DifferenceEngine
1814 class ArrayDiffFormatter
extends DiffFormatter
{
1815 function format($diff) {
1819 foreach($diff->edits
as $edit)
1820 switch($edit->type
) {
1822 foreach($edit->closing
as $l) {
1826 'newline' => $newline++
1831 foreach($edit->orig
as $l) {
1833 'action' => 'delete',
1835 'oldline' => $oldline++
,
1840 foreach($edit->orig
as $i => $l) {
1842 'action' => 'change',
1844 'new' => @$edit->closing
[$i],
1845 'oldline' => $oldline++
,
1846 'newline' => $newline++
,
1851 $oldline +
= count($edit->orig
);
1852 $newline +
= count($edit->orig
);
1859 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1863 define('NBSP', ' '); // iso-8859-x non-breaking space.
1868 * @ingroup DifferenceEngine
1870 class _HWLDF_WordAccumulator
{
1871 function _HWLDF_WordAccumulator () {
1872 $this->_lines
= array();
1878 function _flushGroup ($new_tag) {
1879 if ($this->_group
!== '') {
1880 if ($this->_tag
== 'ins')
1881 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1882 htmlspecialchars ( $this->_group
) . '</ins>';
1883 elseif ($this->_tag
== 'del')
1884 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1885 htmlspecialchars ( $this->_group
) . '</del>';
1887 $this->_line
.= htmlspecialchars ( $this->_group
);
1890 $this->_tag
= $new_tag;
1893 function _flushLine ($new_tag) {
1894 $this->_flushGroup($new_tag);
1895 if ($this->_line
!= '')
1896 array_push ( $this->_lines
, $this->_line
);
1898 # make empty lines visible by inserting an NBSP
1899 array_push ( $this->_lines
, NBSP
);
1903 function addWords ($words, $tag = '') {
1904 if ($tag != $this->_tag
)
1905 $this->_flushGroup($tag);
1907 foreach ($words as $word) {
1908 // new-line should only come as first char of word.
1911 if ($word[0] == "\n") {
1912 $this->_flushLine($tag);
1913 $word = substr($word, 1);
1915 assert(!strstr($word, "\n"));
1916 $this->_group
.= $word;
1920 function getLines() {
1921 $this->_flushLine('~done');
1922 return $this->_lines
;
1929 * @ingroup DifferenceEngine
1931 class WordLevelDiff
extends MappedDiff
{
1932 const MAX_LINE_LENGTH
= 10000;
1934 function WordLevelDiff ($orig_lines, $closing_lines) {
1935 wfProfileIn( __METHOD__
);
1937 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1938 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1940 $this->MappedDiff($orig_words, $closing_words,
1941 $orig_stripped, $closing_stripped);
1942 wfProfileOut( __METHOD__
);
1945 function _split($lines) {
1946 wfProfileIn( __METHOD__
);
1949 $stripped = array();
1951 foreach ( $lines as $line ) {
1952 # If the line is too long, just pretend the entire line is one big word
1953 # This prevents resource exhaustion problems
1960 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1962 $stripped[] = $line;
1965 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1968 $words = array_merge( $words, $m[0] );
1969 $stripped = array_merge( $stripped, $m[1] );
1973 wfProfileOut( __METHOD__
);
1974 return array($words, $stripped);
1978 wfProfileIn( __METHOD__
);
1979 $orig = new _HWLDF_WordAccumulator
;
1981 foreach ($this->edits
as $edit) {
1982 if ($edit->type
== 'copy')
1983 $orig->addWords($edit->orig
);
1984 elseif ($edit->orig
)
1985 $orig->addWords($edit->orig
, 'del');
1987 $lines = $orig->getLines();
1988 wfProfileOut( __METHOD__
);
1992 function closing () {
1993 wfProfileIn( __METHOD__
);
1994 $closing = new _HWLDF_WordAccumulator
;
1996 foreach ($this->edits
as $edit) {
1997 if ($edit->type
== 'copy')
1998 $closing->addWords($edit->closing
);
1999 elseif ($edit->closing
)
2000 $closing->addWords($edit->closing
, 'ins');
2002 $lines = $closing->getLines();
2003 wfProfileOut( __METHOD__
);
2009 * Wikipedia Table style diff formatter.
2012 * @ingroup DifferenceEngine
2014 class TableDiffFormatter
extends DiffFormatter
{
2015 function TableDiffFormatter() {
2016 $this->leading_context_lines
= 2;
2017 $this->trailing_context_lines
= 2;
2020 public static function escapeWhiteSpace( $msg ) {
2021 $msg = preg_replace( '/^ /m', ' ', $msg );
2022 $msg = preg_replace( '/ $/m', ' ', $msg );
2023 $msg = preg_replace( '/ /', ' ', $msg );
2027 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2028 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2029 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2033 function _start_block( $header ) {
2037 function _end_block() {
2040 function _lines( $lines, $prefix=' ', $color='white' ) {
2043 # HTML-escape parameter before calling this
2044 function addedLine( $line ) {
2045 return $this->wrapLine( '+', 'diff-addedline', $line );
2048 # HTML-escape parameter before calling this
2049 function deletedLine( $line ) {
2050 return $this->wrapLine( '-', 'diff-deletedline', $line );
2053 # HTML-escape parameter before calling this
2054 function contextLine( $line ) {
2055 return $this->wrapLine( ' ', 'diff-context', $line );
2058 private function wrapLine( $marker, $class, $line ) {
2059 if( $line !== '' ) {
2060 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2061 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2063 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2066 function emptyLine() {
2067 return '<td colspan="2"> </td>';
2070 function _added( $lines ) {
2071 foreach ($lines as $line) {
2072 echo '<tr>' . $this->emptyLine() .
2073 $this->addedLine( '<ins class="diffchange">' .
2074 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2078 function _deleted($lines) {
2079 foreach ($lines as $line) {
2080 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2081 htmlspecialchars ( $line ) . '</del>' ) .
2082 $this->emptyLine() . "</tr>\n";
2086 function _context( $lines ) {
2087 foreach ($lines as $line) {
2089 $this->contextLine( htmlspecialchars ( $line ) ) .
2090 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2094 function _changed( $orig, $closing ) {
2095 wfProfileIn( __METHOD__
);
2097 $diff = new WordLevelDiff( $orig, $closing );
2098 $del = $diff->orig();
2099 $add = $diff->closing();
2101 # Notice that WordLevelDiff returns HTML-escaped output.
2102 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2104 while ( $line = array_shift( $del ) ) {
2105 $aline = array_shift( $add );
2106 echo '<tr>' . $this->deletedLine( $line ) .
2107 $this->addedLine( $aline ) . "</tr>\n";
2109 foreach ($add as $line) { # If any leftovers
2110 echo '<tr>' . $this->emptyLine() .
2111 $this->addedLine( $line ) . "</tr>\n";
2113 wfProfileOut( __METHOD__
);