3 * @defgroup DifferenceEngine DifferenceEngine
7 * @todo indicate where diff.doc can be found.
11 * Constant to indicate diff cache compatibility.
12 * Bump this when changing the diff formatting in a way that
13 * fixes important bugs or such to force cached diff views to
16 define( 'MW_DIFF_VERSION', '1.11a' );
20 * @ingroup DifferenceEngine
22 class DifferenceEngine
{
26 var $mOldid, $mNewid, $mTitle;
27 var $mOldtitle, $mNewtitle, $mPagetitle;
28 var $mOldtext, $mNewtext;
29 var $mOldPage, $mNewPage;
30 var $mRcidMarkPatrolled;
31 var $mOldRev, $mNewRev;
32 var $mRevisionsLoaded = false; // Have the revisions been loaded
33 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
38 * @param $titleObj Title object that the diff is associated with
39 * @param $old Integer: old ID we want to show and diff with.
40 * @param $new String: either 'prev' or 'next'.
41 * @param $rcid Integer: ??? FIXME (default 0)
42 * @param $refreshCache boolean If set, refreshes the diff cache
44 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false ) {
45 $this->mTitle
= $titleObj;
46 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
48 if ( 'prev' === $new ) {
49 # Show diff between revision $old and the previous one.
50 # Get previous one from DB.
52 $this->mNewid
= intval($old);
54 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
56 } elseif ( 'next' === $new ) {
57 # Show diff between revision $old and the previous one.
58 # Get previous one from DB.
60 $this->mOldid
= intval($old);
61 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
62 if ( false === $this->mNewid
) {
63 # if no result, NewId points to the newest old revision. The only newer
64 # revision is cur, which is "0".
69 $this->mOldid
= intval($old);
70 $this->mNewid
= intval($new);
72 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
73 $this->mRefreshCache
= $refreshCache;
80 function showDiffPage( $diffOnly = false ) {
81 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
82 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 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
209 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
210 if ( $this->mNewRev
->isCurrent() ) {
211 $nextlink = ' ';
213 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
214 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
220 if ($this->mOldRev
->mMinorEdit
== 1) {
221 $oldminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
224 if ($this->mNewRev
->mMinorEdit
== 1) {
225 $newminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
228 $rdel = ''; $ldel = '';
229 if( $wgUser->isAllowed( 'deleterevision' ) ) {
230 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
231 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
232 // If revision was hidden from sysops
233 $ldel = wfMsgHtml('rev-delundel');
235 $ldel = $sk->makeKnownLinkObj( $revdel,
236 wfMsgHtml('rev-delundel'),
237 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
238 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
239 // Bolden oversighted content
240 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
241 $ldel = "<strong>$ldel</strong>";
243 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
244 // We don't currently handle well changing the top revision's settings
245 if( $this->mNewRev
->isCurrent() ) {
246 // If revision was hidden from sysops
247 $rdel = wfMsgHtml('rev-delundel');
248 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
249 // If revision was hidden from sysops
250 $rdel = wfMsgHtml('rev-delundel');
252 $rdel = $sk->makeKnownLinkObj( $revdel,
253 wfMsgHtml('rev-delundel'),
254 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
255 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
256 // Bolden oversighted content
257 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
258 $rdel = "<strong>$rdel</strong>";
260 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
263 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
264 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
265 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
266 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
267 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
268 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
269 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
270 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
272 $this->showDiff( $oldHeader, $newHeader );
275 $this->renderNewRevision();
277 wfProfileOut( __METHOD__
);
281 * Show the new revision of the page.
283 function renderNewRevision() {
285 wfProfileIn( __METHOD__
);
287 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
288 #add deleted rev tag if needed
289 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
290 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
291 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
292 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
295 if( !$this->mNewRev
->isCurrent() ) {
296 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
299 $this->loadNewText();
300 if( is_object( $this->mNewRev
) ) {
301 $wgOut->setRevisionId( $this->mNewRev
->getId() );
304 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
305 // Stolen from Article::view --AG 2007-10-11
307 // Give hooks a chance to customise the output
308 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
309 // Wrap the whole lot in a <pre> and don't parse
311 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
312 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
313 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
314 $wgOut->addHtml( "\n</pre>\n" );
317 $wgOut->addWikiTextTidy( $this->mNewtext
);
319 if( !$this->mNewRev
->isCurrent() ) {
320 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
323 wfProfileOut( __METHOD__
);
327 * Show the first revision of an article. Uses normal diff headers in
328 * contrast to normal "old revision" display style.
330 function showFirstRevision() {
331 global $wgOut, $wgUser;
332 wfProfileIn( __METHOD__
);
334 # Get article text from the DB
336 if ( ! $this->loadNewText() ) {
337 $t = $this->mTitle
->getPrefixedText();
338 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
339 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
340 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
341 wfProfileOut( __METHOD__
);
344 if ( $this->mNewRev
->isCurrent() ) {
345 $wgOut->setArticleFlag( true );
348 # Check if user is allowed to look at this page. If not, bail out.
350 if ( !( $this->mTitle
->userCanRead() ) ) {
351 $wgOut->loginToUse();
353 wfProfileOut( __METHOD__
);
357 # Prepare the header box
359 $sk = $wgUser->getSkin();
361 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
362 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
363 $sk->revUserTools( $this->mNewRev
) . "<br />" .
364 $sk->revComment( $this->mNewRev
) . "<br />" .
365 $nextlink . "</div>\n";
367 $wgOut->addHTML( $header );
369 $wgOut->setSubtitle( wfMsg( 'difference' ) );
370 $wgOut->setRobotpolicy( 'noindex,nofollow' );
372 wfProfileOut( __METHOD__
);
376 * Get the diff text, send it to $wgOut
377 * Returns false if the diff could not be generated, otherwise returns true
379 function showDiff( $otitle, $ntitle ) {
381 $diff = $this->getDiff( $otitle, $ntitle );
382 if ( $diff === false ) {
383 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
386 $this->showDiffStyle();
387 $wgOut->addHTML( $diff );
393 * Add style sheets and supporting JS for diff display.
395 function showDiffStyle() {
396 global $wgStylePath, $wgStyleVersion, $wgOut;
397 $wgOut->addStyle( 'common/diff.css' );
399 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
400 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
404 * Get complete diff table, including header
406 * @param Title $otitle Old title
407 * @param Title $ntitle New title
410 function getDiff( $otitle, $ntitle ) {
411 $body = $this->getDiffBody();
412 if ( $body === false ) {
415 $multi = $this->getMultiNotice();
416 return $this->addHeader( $body, $otitle, $ntitle, $multi );
421 * Get the diff table body, without header
425 function getDiffBody() {
427 wfProfileIn( __METHOD__
);
428 // Check if the diff should be hidden from this user
429 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
431 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
436 if ( $this->mOldid
&& $this->mNewid
) {
437 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
439 if ( !$this->mRefreshCache
) {
440 $difftext = $wgMemc->get( $key );
442 wfIncrStats( 'diff_cache_hit' );
443 $difftext = $this->localiseLineNumbers( $difftext );
444 $difftext .= "\n<!-- diff cache key $key -->\n";
445 wfProfileOut( __METHOD__
);
448 } // don't try to load but save the result
451 // Loadtext is permission safe, this just clears out the diff
452 if ( !$this->loadText() ) {
453 wfProfileOut( __METHOD__
);
457 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
459 // Save to cache for 7 days
460 if ( $key !== false && $difftext !== false ) {
461 wfIncrStats( 'diff_cache_miss' );
462 $wgMemc->set( $key, $difftext, 7*86400 );
464 wfIncrStats( 'diff_uncacheable' );
466 // Replace line numbers with the text in the user's language
467 if ( $difftext !== false ) {
468 $difftext = $this->localiseLineNumbers( $difftext );
470 wfProfileOut( __METHOD__
);
475 * Generate a diff, no caching
476 * $otext and $ntext must be already segmented
478 function generateDiffBody( $otext, $ntext ) {
479 global $wgExternalDiffEngine, $wgContLang;
481 $otext = str_replace( "\r\n", "\n", $otext );
482 $ntext = str_replace( "\r\n", "\n", $ntext );
484 if ( $wgExternalDiffEngine == 'wikidiff' ) {
485 # For historical reasons, external diff engine expects
486 # input text to be HTML-escaped already
487 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
488 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
489 if( !function_exists( 'wikidiff_do_diff' ) ) {
490 dl('php_wikidiff.so');
492 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
493 $this->debug( 'wikidiff1' );
496 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
497 # Better external diff engine, the 2 may some day be dropped
498 # This one does the escaping and segmenting itself
499 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
500 wfProfileIn( __METHOD__
. "-dl" );
501 @dl
('php_wikidiff2.so');
502 wfProfileOut( __METHOD__
. "-dl" );
504 if ( function_exists( 'wikidiff2_do_diff' ) ) {
505 wfProfileIn( 'wikidiff2_do_diff' );
506 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
507 $text .= $this->debug( 'wikidiff2' );
508 wfProfileOut( 'wikidiff2_do_diff' );
512 if ( $wgExternalDiffEngine !== false ) {
514 global $wgTmpDirectory;
515 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
516 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
518 $tempFile1 = fopen( $tempName1, "w" );
520 wfProfileOut( __METHOD__
);
523 $tempFile2 = fopen( $tempName2, "w" );
525 wfProfileOut( __METHOD__
);
528 fwrite( $tempFile1, $otext );
529 fwrite( $tempFile2, $ntext );
530 fclose( $tempFile1 );
531 fclose( $tempFile2 );
532 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
533 wfProfileIn( __METHOD__
. "-shellexec" );
534 $difftext = wfShellExec( $cmd );
535 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
536 wfProfileOut( __METHOD__
. "-shellexec" );
537 unlink( $tempName1 );
538 unlink( $tempName2 );
543 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
544 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
545 $diffs = new Diff( $ota, $nta );
546 $formatter = new TableDiffFormatter();
547 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
552 * Generate a debug comment indicating diff generating time,
553 * server node, and generator backend.
555 protected function debug( $generator="internal" ) {
556 global $wgShowHostnames, $wgNodeName;
557 $data = array( $generator );
558 if( $wgShowHostnames ) {
559 $data[] = $wgNodeName;
561 $data[] = wfTimestamp( TS_DB
);
562 return "<!-- diff generator: " .
571 * Replace line numbers with the text in the user's language
573 function localiseLineNumbers( $text ) {
574 return preg_replace_callback( '/<!--LINE (\d+)-->/',
575 array( &$this, 'localiseLineNumbersCb' ), $text );
578 function localiseLineNumbersCb( $matches ) {
580 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
585 * If there are revisions between the ones being compared, return a note saying so.
587 function getMultiNotice() {
588 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
591 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
592 // Comparing two different pages? Count would be meaningless.
596 $oldid = $this->mOldRev
->getId();
597 $newid = $this->mNewRev
->getId();
598 if ( $oldid > $newid ) {
599 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
602 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
606 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
611 * Add the header to a diff body
613 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
618 <col class='diff-marker' />
619 <col class='diff-content' />
620 <col class='diff-marker' />
621 <col class='diff-content' />
623 <td colspan='2' class='diff-otitle'>{$otitle}</td>
624 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
629 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
631 return $header . $diff . "</table>";
635 * Use specified text instead of loading from the database
637 function setText( $oldText, $newText ) {
638 $this->mOldtext
= $oldText;
639 $this->mNewtext
= $newText;
640 $this->mTextLoaded
= 2;
644 * Load revision metadata for the specified articles. If newid is 0, then compare
645 * the old article in oldid to the current article; if oldid is 0, then
646 * compare the current article to the immediately previous one (ignoring the
649 * If oldid is false, leave the corresponding revision object set
650 * to false. This is impossible via ordinary user input, and is provided for
653 function loadRevisionData() {
655 if ( $this->mRevisionsLoaded
) {
658 // Whether it succeeds or fails, we don't want to try again
659 $this->mRevisionsLoaded
= true;
662 // Load the new revision object
663 $this->mNewRev
= $this->mNewid
664 ? Revision
::newFromId( $this->mNewid
)
665 : Revision
::newFromTitle( $this->mTitle
);
666 if( !$this->mNewRev
instanceof Revision
)
669 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
670 $this->mNewid
= $this->mNewRev
->getId();
672 // Check if page is editable
673 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
675 // Set assorted variables
676 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
677 $this->mNewPage
= $this->mNewRev
->getTitle();
678 if( $this->mNewRev
->isCurrent() ) {
679 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
680 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
681 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
683 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
684 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
687 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
688 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
689 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
691 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
692 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
694 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
695 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
696 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
697 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
700 // Load the old revision object
701 $this->mOldRev
= false;
702 if( $this->mOldid
) {
703 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
704 } elseif ( $this->mOldid
=== 0 ) {
705 $rev = $this->mNewRev
->getPrevious();
707 $this->mOldid
= $rev->getId();
708 $this->mOldRev
= $rev;
710 // No previous revision; mark to show as first-version only.
711 $this->mOldid
= false;
712 $this->mOldRev
= false;
714 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
716 if( is_null( $this->mOldRev
) ) {
720 if ( $this->mOldRev
) {
721 $this->mOldPage
= $this->mOldRev
->getTitle();
723 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
724 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
725 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
726 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
728 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
729 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
730 // Add an "undo" link
731 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
732 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
733 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
736 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
737 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
738 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
739 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
747 * Load the text of the revisions, as well as revision data.
749 function loadText() {
750 if ( $this->mTextLoaded
== 2 ) {
753 // Whether it succeeds or fails, we don't want to try again
754 $this->mTextLoaded
= 2;
757 if ( !$this->loadRevisionData() ) {
760 if ( $this->mOldRev
) {
761 $this->mOldtext
= $this->mOldRev
->revText();
762 if ( $this->mOldtext
=== false ) {
766 if ( $this->mNewRev
) {
767 $this->mNewtext
= $this->mNewRev
->revText();
768 if ( $this->mNewtext
=== false ) {
776 * Load the text of the new revision, not the old one
778 function loadNewText() {
779 if ( $this->mTextLoaded
>= 1 ) {
782 $this->mTextLoaded
= 1;
784 if ( !$this->loadRevisionData() ) {
787 $this->mNewtext
= $this->mNewRev
->getText();
794 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
796 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
797 // You may copy this code freely under the conditions of the GPL.
800 define('USE_ASSERTS', function_exists('assert'));
805 * @ingroup DifferenceEngine
813 trigger_error('pure virtual', E_USER_ERROR
);
817 return $this->orig ?
sizeof($this->orig
) : 0;
820 function nclosing() {
821 return $this->closing ?
sizeof($this->closing
) : 0;
828 * @ingroup DifferenceEngine
830 class _DiffOp_Copy
extends _DiffOp
{
833 function _DiffOp_Copy ($orig, $closing = false) {
834 if (!is_array($closing))
837 $this->closing
= $closing;
841 return new _DiffOp_Copy($this->closing
, $this->orig
);
848 * @ingroup DifferenceEngine
850 class _DiffOp_Delete
extends _DiffOp
{
851 var $type = 'delete';
853 function _DiffOp_Delete ($lines) {
854 $this->orig
= $lines;
855 $this->closing
= false;
859 return new _DiffOp_Add($this->orig
);
866 * @ingroup DifferenceEngine
868 class _DiffOp_Add
extends _DiffOp
{
871 function _DiffOp_Add ($lines) {
872 $this->closing
= $lines;
877 return new _DiffOp_Delete($this->closing
);
884 * @ingroup DifferenceEngine
886 class _DiffOp_Change
extends _DiffOp
{
887 var $type = 'change';
889 function _DiffOp_Change ($orig, $closing) {
891 $this->closing
= $closing;
895 return new _DiffOp_Change($this->closing
, $this->orig
);
901 * Class used internally by Diff to actually compute the diffs.
903 * The algorithm used here is mostly lifted from the perl module
904 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
905 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
907 * More ideas are taken from:
908 * http://www.ics.uci.edu/~eppstein/161/960229.html
910 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
911 * diffutils-2.7, which can be found at:
912 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
914 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
917 * Line length limits for robustness added by Tim Starling, 2005-08-31
919 * @author Geoffrey T. Dairiki, Tim Starling
921 * @ingroup DifferenceEngine
924 const MAX_XREF_LENGTH
= 10000;
926 function diff ($from_lines, $to_lines) {
927 wfProfileIn( __METHOD__
);
929 $n_from = sizeof($from_lines);
930 $n_to = sizeof($to_lines);
932 $this->xchanged
= $this->ychanged
= array();
933 $this->xv
= $this->yv
= array();
934 $this->xind
= $this->yind
= array();
936 unset($this->in_seq
);
939 // Skip leading common lines.
940 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
941 if ($from_lines[$skip] !== $to_lines[$skip])
943 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
945 // Skip trailing common lines.
946 $xi = $n_from; $yi = $n_to;
947 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
948 if ($from_lines[$xi] !== $to_lines[$yi])
950 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
953 // Ignore lines which do not exist in both files.
954 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
955 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
958 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
959 $line = $to_lines[$yi];
960 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
962 $yhash[$this->_line_hash($line)] = 1;
966 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
967 $line = $from_lines[$xi];
968 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
975 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
977 // Merge edits when possible
978 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
979 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
981 // Compute the edit operations.
984 while ($xi < $n_from ||
$yi < $n_to) {
985 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
986 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
988 // Skip matching "snake".
990 while ( $xi < $n_from && $yi < $n_to
991 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
992 $copy[] = $from_lines[$xi++
];
996 $edits[] = new _DiffOp_Copy($copy);
998 // Find deletes & adds.
1000 while ($xi < $n_from && $this->xchanged
[$xi])
1001 $delete[] = $from_lines[$xi++
];
1004 while ($yi < $n_to && $this->ychanged
[$yi])
1005 $add[] = $to_lines[$yi++
];
1007 if ($delete && $add)
1008 $edits[] = new _DiffOp_Change($delete, $add);
1010 $edits[] = new _DiffOp_Delete($delete);
1012 $edits[] = new _DiffOp_Add($add);
1014 wfProfileOut( __METHOD__
);
1019 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1021 function _line_hash( $line ) {
1022 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1023 return md5( $line );
1030 /* Divide the Largest Common Subsequence (LCS) of the sequences
1031 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1034 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1035 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1036 * sub sequences. The first sub-sequence is contained in [X0, X1),
1037 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1038 * that (X0, Y0) == (XOFF, YOFF) and
1039 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1041 * This function assumes that the first lines of the specified portions
1042 * of the two files do not match, and likewise that the last lines do not
1043 * match. The caller must trim matching lines from the beginning and end
1044 * of the portions it is going to specify.
1046 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1047 wfProfileIn( __METHOD__
);
1050 if ($xlim - $xoff > $ylim - $yoff) {
1051 // Things seems faster (I'm not sure I understand why)
1052 // when the shortest sequence in X.
1054 list ($xoff, $xlim, $yoff, $ylim)
1055 = array( $yoff, $ylim, $xoff, $xlim);
1059 for ($i = $ylim - 1; $i >= $yoff; $i--)
1060 $ymatches[$this->xv
[$i]][] = $i;
1062 for ($i = $ylim - 1; $i >= $yoff; $i--)
1063 $ymatches[$this->yv
[$i]][] = $i;
1066 $this->seq
[0]= $yoff - 1;
1067 $this->in_seq
= array();
1068 $ymids[0] = array();
1070 $numer = $xlim - $xoff +
$nchunks - 1;
1072 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1073 wfProfileIn( __METHOD__
. "-chunk" );
1075 for ($i = 0; $i <= $this->lcs
; $i++
)
1076 $ymids[$i][$chunk-1] = $this->seq
[$i];
1078 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1079 for ( ; $x < $x1; $x++
) {
1080 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1081 if (empty($ymatches[$line]))
1083 $matches = $ymatches[$line];
1085 while (list ($junk, $y) = each($matches))
1086 if (empty($this->in_seq
[$y])) {
1087 $k = $this->_lcs_pos($y);
1088 USE_ASSERTS
&& assert($k > 0);
1089 $ymids[$k] = $ymids[$k-1];
1092 while (list ( /* $junk */, $y) = each($matches)) {
1093 if ($y > $this->seq
[$k-1]) {
1094 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1095 // Optimization: this is a common case:
1096 // next match is just replacing previous match.
1097 $this->in_seq
[$this->seq
[$k]] = false;
1098 $this->seq
[$k] = $y;
1099 $this->in_seq
[$y] = 1;
1100 } else if (empty($this->in_seq
[$y])) {
1101 $k = $this->_lcs_pos($y);
1102 USE_ASSERTS
&& assert($k > 0);
1103 $ymids[$k] = $ymids[$k-1];
1107 wfProfileOut( __METHOD__
. "-chunk" );
1110 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1111 $ymid = $ymids[$this->lcs
];
1112 for ($n = 0; $n < $nchunks - 1; $n++
) {
1113 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1114 $y1 = $ymid[$n] +
1;
1115 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1117 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1119 wfProfileOut( __METHOD__
);
1120 return array($this->lcs
, $seps);
1123 function _lcs_pos ($ypos) {
1124 wfProfileIn( __METHOD__
);
1127 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1128 $this->seq
[++
$this->lcs
] = $ypos;
1129 $this->in_seq
[$ypos] = 1;
1130 wfProfileOut( __METHOD__
);
1135 while ($beg < $end) {
1136 $mid = (int)(($beg +
$end) / 2);
1137 if ( $ypos > $this->seq
[$mid] )
1143 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1145 $this->in_seq
[$this->seq
[$end]] = false;
1146 $this->seq
[$end] = $ypos;
1147 $this->in_seq
[$ypos] = 1;
1148 wfProfileOut( __METHOD__
);
1152 /* Find LCS of two sequences.
1154 * The results are recorded in the vectors $this->{x,y}changed[], by
1155 * storing a 1 in the element for each line that is an insertion
1156 * or deletion (ie. is not in the LCS).
1158 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1160 * Note that XLIM, YLIM are exclusive bounds.
1161 * All line numbers are origin-0 and discarded lines are not counted.
1163 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1164 wfProfileIn( __METHOD__
);
1166 // Slide down the bottom initial diagonal.
1167 while ($xoff < $xlim && $yoff < $ylim
1168 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1173 // Slide up the top initial diagonal.
1174 while ($xlim > $xoff && $ylim > $yoff
1175 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1180 if ($xoff == $xlim ||
$yoff == $ylim)
1183 // This is ad hoc but seems to work well.
1184 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1185 //$nchunks = max(2,min(8,(int)$nchunks));
1186 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1188 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1192 // X and Y sequences have no common subsequence:
1193 // mark all changed.
1194 while ($yoff < $ylim)
1195 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1196 while ($xoff < $xlim)
1197 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1199 // Use the partitions to split this problem into subproblems.
1202 while ($pt2 = next($seps)) {
1203 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1207 wfProfileOut( __METHOD__
);
1210 /* Adjust inserts/deletes of identical lines to join changes
1211 * as much as possible.
1213 * We do something when a run of changed lines include a
1214 * line at one end and has an excluded, identical line at the other.
1215 * We are free to choose which identical line is included.
1216 * `compareseq' usually chooses the one at the beginning,
1217 * but usually it is cleaner to consider the following identical line
1218 * to be the "change".
1220 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1222 function _shift_boundaries ($lines, &$changed, $other_changed) {
1223 wfProfileIn( __METHOD__
);
1227 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1228 $len = sizeof($lines);
1229 $other_len = sizeof($other_changed);
1233 * Scan forwards to find beginning of another run of changes.
1234 * Also keep track of the corresponding point in the other file.
1236 * Throughout this code, $i and $j are adjusted together so that
1237 * the first $i elements of $changed and the first $j elements
1238 * of $other_changed both contain the same number of zeros
1239 * (unchanged lines).
1240 * Furthermore, $j is always kept so that $j == $other_len or
1241 * $other_changed[$j] == false.
1243 while ($j < $other_len && $other_changed[$j])
1246 while ($i < $len && ! $changed[$i]) {
1247 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1249 while ($j < $other_len && $other_changed[$j])
1258 // Find the end of this run of changes.
1259 while (++
$i < $len && $changed[$i])
1264 * Record the length of this run of changes, so that
1265 * we can later determine whether the run has grown.
1267 $runlength = $i - $start;
1270 * Move the changed region back, so long as the
1271 * previous unchanged line matches the last changed one.
1272 * This merges with previous changed regions.
1274 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1275 $changed[--$start] = 1;
1276 $changed[--$i] = false;
1277 while ($start > 0 && $changed[$start - 1])
1279 USE_ASSERTS
&& assert('$j > 0');
1280 while ($other_changed[--$j])
1282 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1286 * Set CORRESPONDING to the end of the changed run, at the last
1287 * point where it corresponds to a changed run in the other file.
1288 * CORRESPONDING == LEN means no such point has been found.
1290 $corresponding = $j < $other_len ?
$i : $len;
1293 * Move the changed region forward, so long as the
1294 * first changed line matches the following unchanged one.
1295 * This merges with following changed regions.
1296 * Do this second, so that if there are no merges,
1297 * the changed region is moved forward as far as possible.
1299 while ($i < $len && $lines[$start] == $lines[$i]) {
1300 $changed[$start++
] = false;
1302 while ($i < $len && $changed[$i])
1305 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1307 if ($j < $other_len && $other_changed[$j]) {
1308 $corresponding = $i;
1309 while ($j < $other_len && $other_changed[$j])
1313 } while ($runlength != $i - $start);
1316 * If possible, move the fully-merged run of changes
1317 * back to a corresponding run in the other file.
1319 while ($corresponding < $i) {
1320 $changed[--$start] = 1;
1322 USE_ASSERTS
&& assert('$j > 0');
1323 while ($other_changed[--$j])
1325 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1328 wfProfileOut( __METHOD__
);
1333 * Class representing a 'diff' between two sequences of strings.
1336 * @ingroup DifferenceEngine
1344 * Computes diff between sequences of strings.
1346 * @param $from_lines array An array of strings.
1347 * (Typically these are lines from a file.)
1348 * @param $to_lines array An array of strings.
1350 function Diff($from_lines, $to_lines) {
1351 $eng = new _DiffEngine
;
1352 $this->edits
= $eng->diff($from_lines, $to_lines);
1353 //$this->_check($from_lines, $to_lines);
1357 * Compute reversed Diff.
1361 * $diff = new Diff($lines1, $lines2);
1362 * $rev = $diff->reverse();
1363 * @return object A Diff object representing the inverse of the
1366 function reverse () {
1368 $rev->edits
= array();
1369 foreach ($this->edits
as $edit) {
1370 $rev->edits
[] = $edit->reverse();
1376 * Check for empty diff.
1378 * @return bool True iff two sequences were identical.
1380 function isEmpty () {
1381 foreach ($this->edits
as $edit) {
1382 if ($edit->type
!= 'copy')
1389 * Compute the length of the Longest Common Subsequence (LCS).
1391 * This is mostly for diagnostic purposed.
1393 * @return int The length of the LCS.
1397 foreach ($this->edits
as $edit) {
1398 if ($edit->type
== 'copy')
1399 $lcs +
= sizeof($edit->orig
);
1405 * Get the original set of lines.
1407 * This reconstructs the $from_lines parameter passed to the
1410 * @return array The original sequence of strings.
1415 foreach ($this->edits
as $edit) {
1417 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1423 * Get the closing set of lines.
1425 * This reconstructs the $to_lines parameter passed to the
1428 * @return array The sequence of strings.
1430 function closing() {
1433 foreach ($this->edits
as $edit) {
1435 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1441 * Check a Diff for validity.
1443 * This is here only for debugging purposes.
1445 function _check ($from_lines, $to_lines) {
1446 wfProfileIn( __METHOD__
);
1447 if (serialize($from_lines) != serialize($this->orig()))
1448 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1449 if (serialize($to_lines) != serialize($this->closing()))
1450 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1452 $rev = $this->reverse();
1453 if (serialize($to_lines) != serialize($rev->orig()))
1454 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1455 if (serialize($from_lines) != serialize($rev->closing()))
1456 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1460 foreach ($this->edits
as $edit) {
1461 if ( $prevtype == $edit->type
)
1462 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1463 $prevtype = $edit->type
;
1466 $lcs = $this->lcs();
1467 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1468 wfProfileOut( __METHOD__
);
1473 * @todo document, bad name.
1475 * @ingroup DifferenceEngine
1477 class MappedDiff
extends Diff
1482 * Computes diff between sequences of strings.
1484 * This can be used to compute things like
1485 * case-insensitve diffs, or diffs which ignore
1486 * changes in white-space.
1488 * @param $from_lines array An array of strings.
1489 * (Typically these are lines from a file.)
1491 * @param $to_lines array An array of strings.
1493 * @param $mapped_from_lines array This array should
1494 * have the same size number of elements as $from_lines.
1495 * The elements in $mapped_from_lines and
1496 * $mapped_to_lines are what is actually compared
1497 * when computing the diff.
1499 * @param $mapped_to_lines array This array should
1500 * have the same number of elements as $to_lines.
1502 function MappedDiff($from_lines, $to_lines,
1503 $mapped_from_lines, $mapped_to_lines) {
1504 wfProfileIn( __METHOD__
);
1506 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1507 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1509 $this->Diff($mapped_from_lines, $mapped_to_lines);
1512 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1513 $orig = &$this->edits
[$i]->orig
;
1514 if (is_array($orig)) {
1515 $orig = array_slice($from_lines, $xi, sizeof($orig));
1516 $xi +
= sizeof($orig);
1519 $closing = &$this->edits
[$i]->closing
;
1520 if (is_array($closing)) {
1521 $closing = array_slice($to_lines, $yi, sizeof($closing));
1522 $yi +
= sizeof($closing);
1525 wfProfileOut( __METHOD__
);
1530 * A class to format Diffs
1532 * This class formats the diff in classic diff format.
1533 * It is intended that this class be customized via inheritance,
1534 * to obtain fancier outputs.
1537 * @ingroup DifferenceEngine
1539 class DiffFormatter
{
1541 * Number of leading context "lines" to preserve.
1543 * This should be left at zero for this class, but subclasses
1544 * may want to set this to other values.
1546 var $leading_context_lines = 0;
1549 * Number of trailing context "lines" to preserve.
1551 * This should be left at zero for this class, but subclasses
1552 * may want to set this to other values.
1554 var $trailing_context_lines = 0;
1559 * @param $diff object A Diff object.
1560 * @return string The formatted output.
1562 function format($diff) {
1563 wfProfileIn( __METHOD__
);
1569 $nlead = $this->leading_context_lines
;
1570 $ntrail = $this->trailing_context_lines
;
1572 $this->_start_diff();
1574 foreach ($diff->edits
as $edit) {
1575 if ($edit->type
== 'copy') {
1576 if (is_array($block)) {
1577 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1582 $context = array_slice($edit->orig
, 0, $ntrail);
1583 $block[] = new _DiffOp_Copy($context);
1585 $this->_block($x0, $ntrail +
$xi - $x0,
1586 $y0, $ntrail +
$yi - $y0,
1591 $context = $edit->orig
;
1594 if (! is_array($block)) {
1595 $context = array_slice($context, sizeof($context) - $nlead);
1596 $x0 = $xi - sizeof($context);
1597 $y0 = $yi - sizeof($context);
1600 $block[] = new _DiffOp_Copy($context);
1606 $xi +
= sizeof($edit->orig
);
1608 $yi +
= sizeof($edit->closing
);
1611 if (is_array($block))
1612 $this->_block($x0, $xi - $x0,
1616 $end = $this->_end_diff();
1617 wfProfileOut( __METHOD__
);
1621 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1622 wfProfileIn( __METHOD__
);
1623 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1624 foreach ($edits as $edit) {
1625 if ($edit->type
== 'copy')
1626 $this->_context($edit->orig
);
1627 elseif ($edit->type
== 'add')
1628 $this->_added($edit->closing
);
1629 elseif ($edit->type
== 'delete')
1630 $this->_deleted($edit->orig
);
1631 elseif ($edit->type
== 'change')
1632 $this->_changed($edit->orig
, $edit->closing
);
1634 trigger_error('Unknown edit type', E_USER_ERROR
);
1636 $this->_end_block();
1637 wfProfileOut( __METHOD__
);
1640 function _start_diff() {
1644 function _end_diff() {
1645 $val = ob_get_contents();
1650 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1652 $xbeg .= "," . ($xbeg +
$xlen - 1);
1654 $ybeg .= "," . ($ybeg +
$ylen - 1);
1656 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1659 function _start_block($header) {
1660 echo $header . "\n";
1663 function _end_block() {
1666 function _lines($lines, $prefix = ' ') {
1667 foreach ($lines as $line)
1668 echo "$prefix $line\n";
1671 function _context($lines) {
1672 $this->_lines($lines);
1675 function _added($lines) {
1676 $this->_lines($lines, '>');
1678 function _deleted($lines) {
1679 $this->_lines($lines, '<');
1682 function _changed($orig, $closing) {
1683 $this->_deleted($orig);
1685 $this->_added($closing);
1690 * A formatter that outputs unified diffs
1691 * @ingroup DifferenceEngine
1694 class UnifiedDiffFormatter
extends DiffFormatter
{
1695 var $leading_context_lines = 2;
1696 var $trailing_context_lines = 2;
1698 function _added($lines) {
1699 $this->_lines($lines, '+');
1701 function _deleted($lines) {
1702 $this->_lines($lines, '-');
1704 function _changed($orig, $closing) {
1705 $this->_deleted($orig);
1706 $this->_added($closing);
1708 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1709 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1714 * A pseudo-formatter that just passes along the Diff::$edits array
1715 * @ingroup DifferenceEngine
1717 class ArrayDiffFormatter
extends DiffFormatter
{
1718 function format($diff) {
1722 foreach($diff->edits
as $edit)
1723 switch($edit->type
) {
1725 foreach($edit->closing
as $l) {
1729 'newline' => $newline++
1734 foreach($edit->orig
as $l) {
1736 'action' => 'delete',
1738 'oldline' => $oldline++
,
1743 foreach($edit->orig
as $i => $l) {
1745 'action' => 'change',
1747 'new' => @$edit->closing
[$i],
1748 'oldline' => $oldline++
,
1749 'newline' => $newline++
,
1754 $oldline +
= count($edit->orig
);
1755 $newline +
= count($edit->orig
);
1762 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1766 define('NBSP', ' '); // iso-8859-x non-breaking space.
1771 * @ingroup DifferenceEngine
1773 class _HWLDF_WordAccumulator
{
1774 function _HWLDF_WordAccumulator () {
1775 $this->_lines
= array();
1781 function _flushGroup ($new_tag) {
1782 if ($this->_group
!== '') {
1783 if ($this->_tag
== 'ins')
1784 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1785 htmlspecialchars ( $this->_group
) . '</ins>';
1786 elseif ($this->_tag
== 'del')
1787 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1788 htmlspecialchars ( $this->_group
) . '</del>';
1790 $this->_line
.= htmlspecialchars ( $this->_group
);
1793 $this->_tag
= $new_tag;
1796 function _flushLine ($new_tag) {
1797 $this->_flushGroup($new_tag);
1798 if ($this->_line
!= '')
1799 array_push ( $this->_lines
, $this->_line
);
1801 # make empty lines visible by inserting an NBSP
1802 array_push ( $this->_lines
, NBSP
);
1806 function addWords ($words, $tag = '') {
1807 if ($tag != $this->_tag
)
1808 $this->_flushGroup($tag);
1810 foreach ($words as $word) {
1811 // new-line should only come as first char of word.
1814 if ($word[0] == "\n") {
1815 $this->_flushLine($tag);
1816 $word = substr($word, 1);
1818 assert(!strstr($word, "\n"));
1819 $this->_group
.= $word;
1823 function getLines() {
1824 $this->_flushLine('~done');
1825 return $this->_lines
;
1832 * @ingroup DifferenceEngine
1834 class WordLevelDiff
extends MappedDiff
{
1835 const MAX_LINE_LENGTH
= 10000;
1837 function WordLevelDiff ($orig_lines, $closing_lines) {
1838 wfProfileIn( __METHOD__
);
1840 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1841 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1843 $this->MappedDiff($orig_words, $closing_words,
1844 $orig_stripped, $closing_stripped);
1845 wfProfileOut( __METHOD__
);
1848 function _split($lines) {
1849 wfProfileIn( __METHOD__
);
1852 $stripped = array();
1854 foreach ( $lines as $line ) {
1855 # If the line is too long, just pretend the entire line is one big word
1856 # This prevents resource exhaustion problems
1863 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1865 $stripped[] = $line;
1868 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1871 $words = array_merge( $words, $m[0] );
1872 $stripped = array_merge( $stripped, $m[1] );
1876 wfProfileOut( __METHOD__
);
1877 return array($words, $stripped);
1881 wfProfileIn( __METHOD__
);
1882 $orig = new _HWLDF_WordAccumulator
;
1884 foreach ($this->edits
as $edit) {
1885 if ($edit->type
== 'copy')
1886 $orig->addWords($edit->orig
);
1887 elseif ($edit->orig
)
1888 $orig->addWords($edit->orig
, 'del');
1890 $lines = $orig->getLines();
1891 wfProfileOut( __METHOD__
);
1895 function closing () {
1896 wfProfileIn( __METHOD__
);
1897 $closing = new _HWLDF_WordAccumulator
;
1899 foreach ($this->edits
as $edit) {
1900 if ($edit->type
== 'copy')
1901 $closing->addWords($edit->closing
);
1902 elseif ($edit->closing
)
1903 $closing->addWords($edit->closing
, 'ins');
1905 $lines = $closing->getLines();
1906 wfProfileOut( __METHOD__
);
1912 * Wikipedia Table style diff formatter.
1915 * @ingroup DifferenceEngine
1917 class TableDiffFormatter
extends DiffFormatter
{
1918 function TableDiffFormatter() {
1919 $this->leading_context_lines
= 2;
1920 $this->trailing_context_lines
= 2;
1923 public static function escapeWhiteSpace( $msg ) {
1924 $msg = preg_replace( '/^ /m', ' ', $msg );
1925 $msg = preg_replace( '/ $/m', ' ', $msg );
1926 $msg = preg_replace( '/ /', ' ', $msg );
1930 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1931 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1932 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1936 function _start_block( $header ) {
1940 function _end_block() {
1943 function _lines( $lines, $prefix=' ', $color='white' ) {
1946 # HTML-escape parameter before calling this
1947 function addedLine( $line ) {
1948 return $this->wrapLine( '+', 'diff-addedline', $line );
1951 # HTML-escape parameter before calling this
1952 function deletedLine( $line ) {
1953 return $this->wrapLine( '-', 'diff-deletedline', $line );
1956 # HTML-escape parameter before calling this
1957 function contextLine( $line ) {
1958 return $this->wrapLine( ' ', 'diff-context', $line );
1961 private function wrapLine( $marker, $class, $line ) {
1962 if( $line !== '' ) {
1963 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1964 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1966 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1969 function emptyLine() {
1970 return '<td colspan="2"> </td>';
1973 function _added( $lines ) {
1974 foreach ($lines as $line) {
1975 echo '<tr>' . $this->emptyLine() .
1976 $this->addedLine( '<ins class="diffchange">' .
1977 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1981 function _deleted($lines) {
1982 foreach ($lines as $line) {
1983 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1984 htmlspecialchars ( $line ) . '</del>' ) .
1985 $this->emptyLine() . "</tr>\n";
1989 function _context( $lines ) {
1990 foreach ($lines as $line) {
1992 $this->contextLine( htmlspecialchars ( $line ) ) .
1993 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1997 function _changed( $orig, $closing ) {
1998 wfProfileIn( __METHOD__
);
2000 $diff = new WordLevelDiff( $orig, $closing );
2001 $del = $diff->orig();
2002 $add = $diff->closing();
2004 # Notice that WordLevelDiff returns HTML-escaped output.
2005 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2007 while ( $line = array_shift( $del ) ) {
2008 $aline = array_shift( $add );
2009 echo '<tr>' . $this->deletedLine( $line ) .
2010 $this->addedLine( $aline ) . "</tr>\n";
2012 foreach ($add as $line) { # If any leftovers
2013 echo '<tr>' . $this->emptyLine() .
2014 $this->addedLine( $line ) . "</tr>\n";
2016 wfProfileOut( __METHOD__
);