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?
34 * @param $titleObj Title object that the diff is associated with
35 * @param $old Integer: old ID we want to show and diff with.
36 * @param $new String: either 'prev' or 'next'.
37 * @param $rcid Integer: ??? FIXME (default 0)
38 * @param $refreshCache boolean If set, refreshes the diff cache
40 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false ) {
41 $this->mTitle
= $titleObj;
42 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
44 if ( 'prev' === $new ) {
45 # Show diff between revision $old and the previous one.
46 # Get previous one from DB.
48 $this->mNewid
= intval($old);
50 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
52 } elseif ( 'next' === $new ) {
53 # Show diff between revision $old and the previous one.
54 # Get previous one from DB.
56 $this->mOldid
= intval($old);
57 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
58 if ( false === $this->mNewid
) {
59 # if no result, NewId points to the newest old revision. The only newer
60 # revision is cur, which is "0".
65 $this->mOldid
= intval($old);
66 $this->mNewid
= intval($new);
68 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
69 $this->mRefreshCache
= $refreshCache;
76 function showDiffPage( $diffOnly = false ) {
77 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
78 wfProfileIn( __METHOD__
);
80 # If external diffs are enabled both globally and for the user,
81 # we'll use the application/x-external-editor interface to call
82 # an external diff tool like kompare, kdiff3, etc.
83 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
84 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
86 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
87 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
88 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
89 $special=$wgLang->getNsText(NS_SPECIAL
);
94 Script={$wgServer}{$wgScript}
95 Special namespace={$special}
109 $wgOut->setArticleFlag( false );
110 if ( ! $this->loadRevisionData() ) {
111 $t = $this->mTitle
->getPrefixedText();
112 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
113 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
114 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
115 wfProfileOut( __METHOD__
);
119 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
121 if ( $this->mNewRev
->isCurrent() ) {
122 $wgOut->setArticleFlag( true );
125 # mOldid is false if the difference engine is called with a "vague" query for
126 # a diff between a version V and its previous version V' AND the version V
127 # is the first version of that article. In that case, V' does not exist.
128 if ( $this->mOldid
=== false ) {
129 $this->showFirstRevision();
130 $this->renderNewRevision(); // should we respect $diffOnly here or not?
131 wfProfileOut( __METHOD__
);
135 $wgOut->suppressQuickbar();
137 $oldTitle = $this->mOldPage
->getPrefixedText();
138 $newTitle = $this->mNewPage
->getPrefixedText();
139 if( $oldTitle == $newTitle ) {
140 $wgOut->setPageTitle( $newTitle );
142 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
144 $wgOut->setSubtitle( wfMsg( 'difference' ) );
145 $wgOut->setRobotPolicy( 'noindex,nofollow' );
147 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
148 $wgOut->loginToUse();
150 wfProfileOut( __METHOD__
);
154 $sk = $wgUser->getSkin();
156 // Check if page is editable
157 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
158 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
159 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
164 // Prepare a change patrol link, if applicable
165 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
166 // If we've been given an explicit change identifier, use it; saves time
167 if( $this->mRcidMarkPatrolled
) {
168 $rcid = $this->mRcidMarkPatrolled
;
170 // Look for an unpatrolled change corresponding to this diff
171 $db = wfGetDB( DB_SLAVE
);
172 $change = RecentChange
::newFromConds(
174 // Add redundant user,timestamp condition so we can use the existing index
175 'rc_user_text' => $this->mNewRev
->getRawUserText(),
176 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
177 'rc_this_oldid' => $this->mNewid
,
178 'rc_last_oldid' => $this->mOldid
,
183 if( $change instanceof RecentChange
) {
184 $rcid = $change->mAttribs
['rc_id'];
192 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
194 wfMsgHtml( 'markaspatrolleddiff' ),
195 "action=markpatrolled&rcid={$rcid}"
204 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
205 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
206 if ( $this->mNewRev
->isCurrent() ) {
207 $nextlink = ' ';
209 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
210 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
216 if ($this->mOldRev
->mMinorEdit
== 1) {
217 $oldminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
220 if ($this->mNewRev
->mMinorEdit
== 1) {
221 $newminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
224 $rdel = ''; $ldel = '';
225 if( $wgUser->isAllowed( 'deleterevision' ) ) {
226 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
227 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
228 // If revision was hidden from sysops
229 $ldel = wfMsgHtml('rev-delundel');
231 $ldel = $sk->makeKnownLinkObj( $revdel,
232 wfMsgHtml('rev-delundel'),
233 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
234 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
235 // Bolden oversighted content
236 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
237 $ldel = "<strong>$ldel</strong>";
239 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
240 // We don't currently handle well changing the top revision's settings
241 if( $this->mNewRev
->isCurrent() ) {
242 // If revision was hidden from sysops
243 $rdel = wfMsgHtml('rev-delundel');
244 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
245 // If revision was hidden from sysops
246 $rdel = wfMsgHtml('rev-delundel');
248 $rdel = $sk->makeKnownLinkObj( $revdel,
249 wfMsgHtml('rev-delundel'),
250 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
251 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
252 // Bolden oversighted content
253 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
254 $rdel = "<strong>$rdel</strong>";
256 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
259 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
260 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
261 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
262 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
263 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
264 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
265 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
266 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
268 $this->showDiff( $oldHeader, $newHeader );
271 $this->renderNewRevision();
273 wfProfileOut( __METHOD__
);
277 * Show the new revision of the page.
279 function renderNewRevision() {
281 wfProfileIn( __METHOD__
);
283 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
284 #add deleted rev tag if needed
285 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
286 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
287 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
288 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
291 if( !$this->mNewRev
->isCurrent() ) {
292 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
295 $this->loadNewText();
296 if( is_object( $this->mNewRev
) ) {
297 $wgOut->setRevisionId( $this->mNewRev
->getId() );
300 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
301 // Stolen from Article::view --AG 2007-10-11
303 // Give hooks a chance to customise the output
304 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
305 // Wrap the whole lot in a <pre> and don't parse
307 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
308 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
309 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
310 $wgOut->addHtml( "\n</pre>\n" );
313 $wgOut->addWikiTextTidy( $this->mNewtext
);
315 if( !$this->mNewRev
->isCurrent() ) {
316 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
319 wfProfileOut( __METHOD__
);
323 * Show the first revision of an article. Uses normal diff headers in
324 * contrast to normal "old revision" display style.
326 function showFirstRevision() {
327 global $wgOut, $wgUser;
328 wfProfileIn( __METHOD__
);
330 # Get article text from the DB
332 if ( ! $this->loadNewText() ) {
333 $t = $this->mTitle
->getPrefixedText();
334 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
335 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
336 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
337 wfProfileOut( __METHOD__
);
340 if ( $this->mNewRev
->isCurrent() ) {
341 $wgOut->setArticleFlag( true );
344 # Check if user is allowed to look at this page. If not, bail out.
346 if ( !( $this->mTitle
->userCanRead() ) ) {
347 $wgOut->loginToUse();
349 wfProfileOut( __METHOD__
);
353 # Prepare the header box
355 $sk = $wgUser->getSkin();
357 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
358 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
359 $sk->revUserTools( $this->mNewRev
) . "<br />" .
360 $sk->revComment( $this->mNewRev
) . "<br />" .
361 $nextlink . "</div>\n";
363 $wgOut->addHTML( $header );
365 $wgOut->setSubtitle( wfMsg( 'difference' ) );
366 $wgOut->setRobotPolicy( 'noindex,nofollow' );
368 wfProfileOut( __METHOD__
);
372 * Get the diff text, send it to $wgOut
373 * Returns false if the diff could not be generated, otherwise returns true
375 function showDiff( $otitle, $ntitle ) {
377 $diff = $this->getDiff( $otitle, $ntitle );
378 if ( $diff === false ) {
379 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
382 $this->showDiffStyle();
383 $wgOut->addHTML( $diff );
389 * Add style sheets and supporting JS for diff display.
391 function showDiffStyle() {
392 global $wgStylePath, $wgStyleVersion, $wgOut;
393 $wgOut->addStyle( 'common/diff.css' );
395 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
396 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
400 * Get complete diff table, including header
402 * @param Title $otitle Old title
403 * @param Title $ntitle New title
406 function getDiff( $otitle, $ntitle ) {
407 $body = $this->getDiffBody();
408 if ( $body === false ) {
411 $multi = $this->getMultiNotice();
412 return $this->addHeader( $body, $otitle, $ntitle, $multi );
417 * Get the diff table body, without header
421 function getDiffBody() {
423 wfProfileIn( __METHOD__
);
424 // Check if the diff should be hidden from this user
425 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
427 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
432 if ( $this->mOldid
&& $this->mNewid
) {
433 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
435 if ( !$this->mRefreshCache
) {
436 $difftext = $wgMemc->get( $key );
438 wfIncrStats( 'diff_cache_hit' );
439 $difftext = $this->localiseLineNumbers( $difftext );
440 $difftext .= "\n<!-- diff cache key $key -->\n";
441 wfProfileOut( __METHOD__
);
444 } // don't try to load but save the result
447 // Loadtext is permission safe, this just clears out the diff
448 if ( !$this->loadText() ) {
449 wfProfileOut( __METHOD__
);
453 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
455 // Save to cache for 7 days
456 if ( $key !== false && $difftext !== false ) {
457 wfIncrStats( 'diff_cache_miss' );
458 $wgMemc->set( $key, $difftext, 7*86400 );
460 wfIncrStats( 'diff_uncacheable' );
462 // Replace line numbers with the text in the user's language
463 if ( $difftext !== false ) {
464 $difftext = $this->localiseLineNumbers( $difftext );
466 wfProfileOut( __METHOD__
);
471 * Generate a diff, no caching
472 * $otext and $ntext must be already segmented
474 function generateDiffBody( $otext, $ntext ) {
475 global $wgExternalDiffEngine, $wgContLang;
477 $otext = str_replace( "\r\n", "\n", $otext );
478 $ntext = str_replace( "\r\n", "\n", $ntext );
480 if ( $wgExternalDiffEngine == 'wikidiff' ) {
481 # For historical reasons, external diff engine expects
482 # input text to be HTML-escaped already
483 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
484 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
485 if( !function_exists( 'wikidiff_do_diff' ) ) {
486 dl('php_wikidiff.so');
488 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
489 $this->debug( 'wikidiff1' );
492 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
493 # Better external diff engine, the 2 may some day be dropped
494 # This one does the escaping and segmenting itself
495 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
496 wfProfileIn( __METHOD__
. "-dl" );
497 @dl
('php_wikidiff2.so');
498 wfProfileOut( __METHOD__
. "-dl" );
500 if ( function_exists( 'wikidiff2_do_diff' ) ) {
501 wfProfileIn( 'wikidiff2_do_diff' );
502 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
503 $text .= $this->debug( 'wikidiff2' );
504 wfProfileOut( 'wikidiff2_do_diff' );
508 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
510 global $wgTmpDirectory;
511 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
512 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
514 $tempFile1 = fopen( $tempName1, "w" );
516 wfProfileOut( __METHOD__
);
519 $tempFile2 = fopen( $tempName2, "w" );
521 wfProfileOut( __METHOD__
);
524 fwrite( $tempFile1, $otext );
525 fwrite( $tempFile2, $ntext );
526 fclose( $tempFile1 );
527 fclose( $tempFile2 );
528 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
529 wfProfileIn( __METHOD__
. "-shellexec" );
530 $difftext = wfShellExec( $cmd );
531 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
532 wfProfileOut( __METHOD__
. "-shellexec" );
533 unlink( $tempName1 );
534 unlink( $tempName2 );
539 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
540 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
541 $diffs = new Diff( $ota, $nta );
542 $formatter = new TableDiffFormatter();
543 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
548 * Generate a debug comment indicating diff generating time,
549 * server node, and generator backend.
551 protected function debug( $generator="internal" ) {
552 global $wgShowHostnames, $wgNodeName;
553 $data = array( $generator );
554 if( $wgShowHostnames ) {
555 $data[] = $wgNodeName;
557 $data[] = wfTimestamp( TS_DB
);
558 return "<!-- diff generator: " .
567 * Replace line numbers with the text in the user's language
569 function localiseLineNumbers( $text ) {
570 return preg_replace_callback( '/<!--LINE (\d+)-->/',
571 array( &$this, 'localiseLineNumbersCb' ), $text );
574 function localiseLineNumbersCb( $matches ) {
576 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
581 * If there are revisions between the ones being compared, return a note saying so.
583 function getMultiNotice() {
584 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
587 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
588 // Comparing two different pages? Count would be meaningless.
592 $oldid = $this->mOldRev
->getId();
593 $newid = $this->mNewRev
->getId();
594 if ( $oldid > $newid ) {
595 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
598 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
602 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
607 * Add the header to a diff body
609 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
614 <col class='diff-marker' />
615 <col class='diff-content' />
616 <col class='diff-marker' />
617 <col class='diff-content' />
619 <td colspan='2' class='diff-otitle'>{$otitle}</td>
620 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
625 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
627 return $header . $diff . "</table>";
631 * Use specified text instead of loading from the database
633 function setText( $oldText, $newText ) {
634 $this->mOldtext
= $oldText;
635 $this->mNewtext
= $newText;
636 $this->mTextLoaded
= 2;
640 * Load revision metadata for the specified articles. If newid is 0, then compare
641 * the old article in oldid to the current article; if oldid is 0, then
642 * compare the current article to the immediately previous one (ignoring the
645 * If oldid is false, leave the corresponding revision object set
646 * to false. This is impossible via ordinary user input, and is provided for
649 function loadRevisionData() {
651 if ( $this->mRevisionsLoaded
) {
654 // Whether it succeeds or fails, we don't want to try again
655 $this->mRevisionsLoaded
= true;
658 // Load the new revision object
659 $this->mNewRev
= $this->mNewid
660 ? Revision
::newFromId( $this->mNewid
)
661 : Revision
::newFromTitle( $this->mTitle
);
662 if( !$this->mNewRev
instanceof Revision
)
665 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
666 $this->mNewid
= $this->mNewRev
->getId();
668 // Check if page is editable
669 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
671 // Set assorted variables
672 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
673 $this->mNewPage
= $this->mNewRev
->getTitle();
674 if( $this->mNewRev
->isCurrent() ) {
675 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
676 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
677 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
679 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
680 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
683 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
684 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
685 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
687 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
688 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
690 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
691 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
692 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
693 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
696 // Load the old revision object
697 $this->mOldRev
= false;
698 if( $this->mOldid
) {
699 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
700 } elseif ( $this->mOldid
=== 0 ) {
701 $rev = $this->mNewRev
->getPrevious();
703 $this->mOldid
= $rev->getId();
704 $this->mOldRev
= $rev;
706 // No previous revision; mark to show as first-version only.
707 $this->mOldid
= false;
708 $this->mOldRev
= false;
710 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
712 if( is_null( $this->mOldRev
) ) {
716 if ( $this->mOldRev
) {
717 $this->mOldPage
= $this->mOldRev
->getTitle();
719 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
720 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
721 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
722 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
724 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
725 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
726 // Add an "undo" link
727 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
728 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
729 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
732 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
733 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
734 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
735 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
743 * Load the text of the revisions, as well as revision data.
745 function loadText() {
746 if ( $this->mTextLoaded
== 2 ) {
749 // Whether it succeeds or fails, we don't want to try again
750 $this->mTextLoaded
= 2;
753 if ( !$this->loadRevisionData() ) {
756 if ( $this->mOldRev
) {
757 $this->mOldtext
= $this->mOldRev
->revText();
758 if ( $this->mOldtext
=== false ) {
762 if ( $this->mNewRev
) {
763 $this->mNewtext
= $this->mNewRev
->revText();
764 if ( $this->mNewtext
=== false ) {
772 * Load the text of the new revision, not the old one
774 function loadNewText() {
775 if ( $this->mTextLoaded
>= 1 ) {
778 $this->mTextLoaded
= 1;
780 if ( !$this->loadRevisionData() ) {
783 $this->mNewtext
= $this->mNewRev
->getText();
790 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
792 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
793 // You may copy this code freely under the conditions of the GPL.
796 define('USE_ASSERTS', function_exists('assert'));
801 * @ingroup DifferenceEngine
809 trigger_error('pure virtual', E_USER_ERROR
);
813 return $this->orig ?
sizeof($this->orig
) : 0;
816 function nclosing() {
817 return $this->closing ?
sizeof($this->closing
) : 0;
824 * @ingroup DifferenceEngine
826 class _DiffOp_Copy
extends _DiffOp
{
829 function _DiffOp_Copy ($orig, $closing = false) {
830 if (!is_array($closing))
833 $this->closing
= $closing;
837 return new _DiffOp_Copy($this->closing
, $this->orig
);
844 * @ingroup DifferenceEngine
846 class _DiffOp_Delete
extends _DiffOp
{
847 var $type = 'delete';
849 function _DiffOp_Delete ($lines) {
850 $this->orig
= $lines;
851 $this->closing
= false;
855 return new _DiffOp_Add($this->orig
);
862 * @ingroup DifferenceEngine
864 class _DiffOp_Add
extends _DiffOp
{
867 function _DiffOp_Add ($lines) {
868 $this->closing
= $lines;
873 return new _DiffOp_Delete($this->closing
);
880 * @ingroup DifferenceEngine
882 class _DiffOp_Change
extends _DiffOp
{
883 var $type = 'change';
885 function _DiffOp_Change ($orig, $closing) {
887 $this->closing
= $closing;
891 return new _DiffOp_Change($this->closing
, $this->orig
);
896 * Class used internally by Diff to actually compute the diffs.
898 * The algorithm used here is mostly lifted from the perl module
899 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
900 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
902 * More ideas are taken from:
903 * http://www.ics.uci.edu/~eppstein/161/960229.html
905 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
906 * diffutils-2.7, which can be found at:
907 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
909 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
912 * Line length limits for robustness added by Tim Starling, 2005-08-31
913 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
915 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
917 * @ingroup DifferenceEngine
921 const MAX_XREF_LENGTH
= 10000;
923 function diff ($from_lines, $to_lines) {
924 wfProfileIn( __METHOD__
);
926 global $wgExternalDiffEngine;
928 $n_from = sizeof($from_lines);
929 $n_to = sizeof($to_lines);
931 if($wgExternalDiffEngine == 'wikidiff3'){
934 require_once( "$IP/includes/Diff.php" );
935 list($this->xchanged
, $this->ychanged
) = wikidiff3_diff($from_lines, $to_lines, TRUE, 100000);
938 wfProfileIn( __METHOD__
." - basicdiff");
939 $this->xchanged
= $this->ychanged
= array();
940 $this->xv
= $this->yv
= array();
941 $this->xind
= $this->yind
= array();
943 unset($this->in_seq
);
946 // Skip leading common lines.
947 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
948 if ($from_lines[$skip] !== $to_lines[$skip])
950 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
952 // Skip trailing common lines.
953 $xi = $n_from; $yi = $n_to;
954 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
955 if ($from_lines[$xi] !== $to_lines[$yi])
957 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
960 // Ignore lines which do not exist in both files.
961 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
962 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
965 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
966 $line = $to_lines[$yi];
967 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
969 $yhash[$this->_line_hash($line)] = 1;
973 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
974 $line = $from_lines[$xi];
975 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
982 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
983 wfProfileOut( __METHOD__
." - basicdiff");
986 // Merge edits when possible
987 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
988 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
990 // Compute the edit operations.
993 while ($xi < $n_from ||
$yi < $n_to) {
994 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
995 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
997 // Skip matching "snake".
999 while ( $xi < $n_from && $yi < $n_to
1000 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1001 $copy[] = $from_lines[$xi++
];
1005 $edits[] = new _DiffOp_Copy($copy);
1007 // Find deletes & adds.
1009 while ($xi < $n_from && $this->xchanged
[$xi])
1010 $delete[] = $from_lines[$xi++
];
1013 while ($yi < $n_to && $this->ychanged
[$yi])
1014 $add[] = $to_lines[$yi++
];
1016 if ($delete && $add)
1017 $edits[] = new _DiffOp_Change($delete, $add);
1019 $edits[] = new _DiffOp_Delete($delete);
1021 $edits[] = new _DiffOp_Add($add);
1023 wfProfileOut( __METHOD__
);
1028 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1030 function _line_hash( $line ) {
1031 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1032 return md5( $line );
1038 /* Divide the Largest Common Subsequence (LCS) of the sequences
1039 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1042 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1043 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1044 * sub sequences. The first sub-sequence is contained in [X0, X1),
1045 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1046 * that (X0, Y0) == (XOFF, YOFF) and
1047 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1049 * This function assumes that the first lines of the specified portions
1050 * of the two files do not match, and likewise that the last lines do not
1051 * match. The caller must trim matching lines from the beginning and end
1052 * of the portions it is going to specify.
1054 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1057 if ($xlim - $xoff > $ylim - $yoff) {
1058 // Things seems faster (I'm not sure I understand why)
1059 // when the shortest sequence in X.
1061 list ($xoff, $xlim, $yoff, $ylim)
1062 = array( $yoff, $ylim, $xoff, $xlim);
1066 for ($i = $ylim - 1; $i >= $yoff; $i--)
1067 $ymatches[$this->xv
[$i]][] = $i;
1069 for ($i = $ylim - 1; $i >= $yoff; $i--)
1070 $ymatches[$this->yv
[$i]][] = $i;
1073 $this->seq
[0]= $yoff - 1;
1074 $this->in_seq
= array();
1075 $ymids[0] = array();
1077 $numer = $xlim - $xoff +
$nchunks - 1;
1079 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1080 wfProfileIn( __METHOD__
. "-chunk" );
1082 for ($i = 0; $i <= $this->lcs
; $i++
)
1083 $ymids[$i][$chunk-1] = $this->seq
[$i];
1085 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1086 for ( ; $x < $x1; $x++
) {
1087 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1088 if (empty($ymatches[$line]))
1090 $matches = $ymatches[$line];
1092 while (list ($junk, $y) = each($matches))
1093 if (empty($this->in_seq
[$y])) {
1094 $k = $this->_lcs_pos($y);
1095 USE_ASSERTS
&& assert($k > 0);
1096 $ymids[$k] = $ymids[$k-1];
1099 while (list ( /* $junk */, $y) = each($matches)) {
1100 if ($y > $this->seq
[$k-1]) {
1101 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1102 // Optimization: this is a common case:
1103 // next match is just replacing previous match.
1104 $this->in_seq
[$this->seq
[$k]] = false;
1105 $this->seq
[$k] = $y;
1106 $this->in_seq
[$y] = 1;
1107 } else if (empty($this->in_seq
[$y])) {
1108 $k = $this->_lcs_pos($y);
1109 USE_ASSERTS
&& assert($k > 0);
1110 $ymids[$k] = $ymids[$k-1];
1116 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1117 $ymid = $ymids[$this->lcs
];
1118 for ($n = 0; $n < $nchunks - 1; $n++
) {
1119 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1120 $y1 = $ymid[$n] +
1;
1121 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1123 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1125 return array($this->lcs
, $seps);
1128 function _lcs_pos ($ypos) {
1130 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1131 $this->seq
[++
$this->lcs
] = $ypos;
1132 $this->in_seq
[$ypos] = 1;
1133 wfProfileOut( __METHOD__
);
1138 while ($beg < $end) {
1139 $mid = (int)(($beg +
$end) / 2);
1140 if ( $ypos > $this->seq
[$mid] )
1146 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1148 $this->in_seq
[$this->seq
[$end]] = false;
1149 $this->seq
[$end] = $ypos;
1150 $this->in_seq
[$ypos] = 1;
1154 /* Find LCS of two sequences.
1156 * The results are recorded in the vectors $this->{x,y}changed[], by
1157 * storing a 1 in the element for each line that is an insertion
1158 * or deletion (ie. is not in the LCS).
1160 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1162 * Note that XLIM, YLIM are exclusive bounds.
1163 * All line numbers are origin-0 and discarded lines are not counted.
1165 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
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]);
1209 /* Adjust inserts/deletes of identical lines to join changes
1210 * as much as possible.
1212 * We do something when a run of changed lines include a
1213 * line at one end and has an excluded, identical line at the other.
1214 * We are free to choose which identical line is included.
1215 * `compareseq' usually chooses the one at the beginning,
1216 * but usually it is cleaner to consider the following identical line
1217 * to be the "change".
1219 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1221 function _shift_boundaries ($lines, &$changed, $other_changed) {
1222 wfProfileIn( __METHOD__
);
1226 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1227 $len = sizeof($lines);
1228 $other_len = sizeof($other_changed);
1232 * Scan forwards to find beginning of another run of changes.
1233 * Also keep track of the corresponding point in the other file.
1235 * Throughout this code, $i and $j are adjusted together so that
1236 * the first $i elements of $changed and the first $j elements
1237 * of $other_changed both contain the same number of zeros
1238 * (unchanged lines).
1239 * Furthermore, $j is always kept so that $j == $other_len or
1240 * $other_changed[$j] == false.
1242 while ($j < $other_len && $other_changed[$j])
1245 while ($i < $len && ! $changed[$i]) {
1246 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1248 while ($j < $other_len && $other_changed[$j])
1257 // Find the end of this run of changes.
1258 while (++
$i < $len && $changed[$i])
1263 * Record the length of this run of changes, so that
1264 * we can later determine whether the run has grown.
1266 $runlength = $i - $start;
1269 * Move the changed region back, so long as the
1270 * previous unchanged line matches the last changed one.
1271 * This merges with previous changed regions.
1273 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1274 $changed[--$start] = 1;
1275 $changed[--$i] = false;
1276 while ($start > 0 && $changed[$start - 1])
1278 USE_ASSERTS
&& assert('$j > 0');
1279 while ($other_changed[--$j])
1281 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1285 * Set CORRESPONDING to the end of the changed run, at the last
1286 * point where it corresponds to a changed run in the other file.
1287 * CORRESPONDING == LEN means no such point has been found.
1289 $corresponding = $j < $other_len ?
$i : $len;
1292 * Move the changed region forward, so long as the
1293 * first changed line matches the following unchanged one.
1294 * This merges with following changed regions.
1295 * Do this second, so that if there are no merges,
1296 * the changed region is moved forward as far as possible.
1298 while ($i < $len && $lines[$start] == $lines[$i]) {
1299 $changed[$start++
] = false;
1301 while ($i < $len && $changed[$i])
1304 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1306 if ($j < $other_len && $other_changed[$j]) {
1307 $corresponding = $i;
1308 while ($j < $other_len && $other_changed[$j])
1312 } while ($runlength != $i - $start);
1315 * If possible, move the fully-merged run of changes
1316 * back to a corresponding run in the other file.
1318 while ($corresponding < $i) {
1319 $changed[--$start] = 1;
1321 USE_ASSERTS
&& assert('$j > 0');
1322 while ($other_changed[--$j])
1324 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1327 wfProfileOut( __METHOD__
);
1332 * Class representing a 'diff' between two sequences of strings.
1335 * @ingroup DifferenceEngine
1343 * Computes diff between sequences of strings.
1345 * @param $from_lines array An array of strings.
1346 * (Typically these are lines from a file.)
1347 * @param $to_lines array An array of strings.
1349 function Diff($from_lines, $to_lines) {
1350 $eng = new _DiffEngine
;
1351 $this->edits
= $eng->diff($from_lines, $to_lines);
1352 //$this->_check($from_lines, $to_lines);
1356 * Compute reversed Diff.
1360 * $diff = new Diff($lines1, $lines2);
1361 * $rev = $diff->reverse();
1362 * @return object A Diff object representing the inverse of the
1365 function reverse () {
1367 $rev->edits
= array();
1368 foreach ($this->edits
as $edit) {
1369 $rev->edits
[] = $edit->reverse();
1375 * Check for empty diff.
1377 * @return bool True iff two sequences were identical.
1379 function isEmpty () {
1380 foreach ($this->edits
as $edit) {
1381 if ($edit->type
!= 'copy')
1388 * Compute the length of the Longest Common Subsequence (LCS).
1390 * This is mostly for diagnostic purposed.
1392 * @return int The length of the LCS.
1396 foreach ($this->edits
as $edit) {
1397 if ($edit->type
== 'copy')
1398 $lcs +
= sizeof($edit->orig
);
1404 * Get the original set of lines.
1406 * This reconstructs the $from_lines parameter passed to the
1409 * @return array The original sequence of strings.
1414 foreach ($this->edits
as $edit) {
1416 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1422 * Get the closing set of lines.
1424 * This reconstructs the $to_lines parameter passed to the
1427 * @return array The sequence of strings.
1429 function closing() {
1432 foreach ($this->edits
as $edit) {
1434 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1440 * Check a Diff for validity.
1442 * This is here only for debugging purposes.
1444 function _check ($from_lines, $to_lines) {
1445 wfProfileIn( __METHOD__
);
1446 if (serialize($from_lines) != serialize($this->orig()))
1447 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1448 if (serialize($to_lines) != serialize($this->closing()))
1449 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1451 $rev = $this->reverse();
1452 if (serialize($to_lines) != serialize($rev->orig()))
1453 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1454 if (serialize($from_lines) != serialize($rev->closing()))
1455 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1459 foreach ($this->edits
as $edit) {
1460 if ( $prevtype == $edit->type
)
1461 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1462 $prevtype = $edit->type
;
1465 $lcs = $this->lcs();
1466 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1467 wfProfileOut( __METHOD__
);
1472 * @todo document, bad name.
1474 * @ingroup DifferenceEngine
1476 class MappedDiff
extends Diff
1481 * Computes diff between sequences of strings.
1483 * This can be used to compute things like
1484 * case-insensitve diffs, or diffs which ignore
1485 * changes in white-space.
1487 * @param $from_lines array An array of strings.
1488 * (Typically these are lines from a file.)
1490 * @param $to_lines array An array of strings.
1492 * @param $mapped_from_lines array This array should
1493 * have the same size number of elements as $from_lines.
1494 * The elements in $mapped_from_lines and
1495 * $mapped_to_lines are what is actually compared
1496 * when computing the diff.
1498 * @param $mapped_to_lines array This array should
1499 * have the same number of elements as $to_lines.
1501 function MappedDiff($from_lines, $to_lines,
1502 $mapped_from_lines, $mapped_to_lines) {
1503 wfProfileIn( __METHOD__
);
1505 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1506 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1508 $this->Diff($mapped_from_lines, $mapped_to_lines);
1511 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1512 $orig = &$this->edits
[$i]->orig
;
1513 if (is_array($orig)) {
1514 $orig = array_slice($from_lines, $xi, sizeof($orig));
1515 $xi +
= sizeof($orig);
1518 $closing = &$this->edits
[$i]->closing
;
1519 if (is_array($closing)) {
1520 $closing = array_slice($to_lines, $yi, sizeof($closing));
1521 $yi +
= sizeof($closing);
1524 wfProfileOut( __METHOD__
);
1529 * A class to format Diffs
1531 * This class formats the diff in classic diff format.
1532 * It is intended that this class be customized via inheritance,
1533 * to obtain fancier outputs.
1536 * @ingroup DifferenceEngine
1538 class DiffFormatter
{
1540 * Number of leading context "lines" to preserve.
1542 * This should be left at zero for this class, but subclasses
1543 * may want to set this to other values.
1545 var $leading_context_lines = 0;
1548 * Number of trailing context "lines" to preserve.
1550 * This should be left at zero for this class, but subclasses
1551 * may want to set this to other values.
1553 var $trailing_context_lines = 0;
1558 * @param $diff object A Diff object.
1559 * @return string The formatted output.
1561 function format($diff) {
1562 wfProfileIn( __METHOD__
);
1568 $nlead = $this->leading_context_lines
;
1569 $ntrail = $this->trailing_context_lines
;
1571 $this->_start_diff();
1573 foreach ($diff->edits
as $edit) {
1574 if ($edit->type
== 'copy') {
1575 if (is_array($block)) {
1576 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1581 $context = array_slice($edit->orig
, 0, $ntrail);
1582 $block[] = new _DiffOp_Copy($context);
1584 $this->_block($x0, $ntrail +
$xi - $x0,
1585 $y0, $ntrail +
$yi - $y0,
1590 $context = $edit->orig
;
1593 if (! is_array($block)) {
1594 $context = array_slice($context, sizeof($context) - $nlead);
1595 $x0 = $xi - sizeof($context);
1596 $y0 = $yi - sizeof($context);
1599 $block[] = new _DiffOp_Copy($context);
1605 $xi +
= sizeof($edit->orig
);
1607 $yi +
= sizeof($edit->closing
);
1610 if (is_array($block))
1611 $this->_block($x0, $xi - $x0,
1615 $end = $this->_end_diff();
1616 wfProfileOut( __METHOD__
);
1620 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1621 wfProfileIn( __METHOD__
);
1622 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1623 foreach ($edits as $edit) {
1624 if ($edit->type
== 'copy')
1625 $this->_context($edit->orig
);
1626 elseif ($edit->type
== 'add')
1627 $this->_added($edit->closing
);
1628 elseif ($edit->type
== 'delete')
1629 $this->_deleted($edit->orig
);
1630 elseif ($edit->type
== 'change')
1631 $this->_changed($edit->orig
, $edit->closing
);
1633 trigger_error('Unknown edit type', E_USER_ERROR
);
1635 $this->_end_block();
1636 wfProfileOut( __METHOD__
);
1639 function _start_diff() {
1643 function _end_diff() {
1644 $val = ob_get_contents();
1649 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1651 $xbeg .= "," . ($xbeg +
$xlen - 1);
1653 $ybeg .= "," . ($ybeg +
$ylen - 1);
1655 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1658 function _start_block($header) {
1659 echo $header . "\n";
1662 function _end_block() {
1665 function _lines($lines, $prefix = ' ') {
1666 foreach ($lines as $line)
1667 echo "$prefix $line\n";
1670 function _context($lines) {
1671 $this->_lines($lines);
1674 function _added($lines) {
1675 $this->_lines($lines, '>');
1677 function _deleted($lines) {
1678 $this->_lines($lines, '<');
1681 function _changed($orig, $closing) {
1682 $this->_deleted($orig);
1684 $this->_added($closing);
1689 * A formatter that outputs unified diffs
1690 * @ingroup DifferenceEngine
1693 class UnifiedDiffFormatter
extends DiffFormatter
{
1694 var $leading_context_lines = 2;
1695 var $trailing_context_lines = 2;
1697 function _added($lines) {
1698 $this->_lines($lines, '+');
1700 function _deleted($lines) {
1701 $this->_lines($lines, '-');
1703 function _changed($orig, $closing) {
1704 $this->_deleted($orig);
1705 $this->_added($closing);
1707 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1708 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1713 * A pseudo-formatter that just passes along the Diff::$edits array
1714 * @ingroup DifferenceEngine
1716 class ArrayDiffFormatter
extends DiffFormatter
{
1717 function format($diff) {
1721 foreach($diff->edits
as $edit)
1722 switch($edit->type
) {
1724 foreach($edit->closing
as $l) {
1728 'newline' => $newline++
1733 foreach($edit->orig
as $l) {
1735 'action' => 'delete',
1737 'oldline' => $oldline++
,
1742 foreach($edit->orig
as $i => $l) {
1744 'action' => 'change',
1746 'new' => @$edit->closing
[$i],
1747 'oldline' => $oldline++
,
1748 'newline' => $newline++
,
1753 $oldline +
= count($edit->orig
);
1754 $newline +
= count($edit->orig
);
1761 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1765 define('NBSP', ' '); // iso-8859-x non-breaking space.
1770 * @ingroup DifferenceEngine
1772 class _HWLDF_WordAccumulator
{
1773 function _HWLDF_WordAccumulator () {
1774 $this->_lines
= array();
1780 function _flushGroup ($new_tag) {
1781 if ($this->_group
!== '') {
1782 if ($this->_tag
== 'ins')
1783 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1784 htmlspecialchars ( $this->_group
) . '</ins>';
1785 elseif ($this->_tag
== 'del')
1786 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1787 htmlspecialchars ( $this->_group
) . '</del>';
1789 $this->_line
.= htmlspecialchars ( $this->_group
);
1792 $this->_tag
= $new_tag;
1795 function _flushLine ($new_tag) {
1796 $this->_flushGroup($new_tag);
1797 if ($this->_line
!= '')
1798 array_push ( $this->_lines
, $this->_line
);
1800 # make empty lines visible by inserting an NBSP
1801 array_push ( $this->_lines
, NBSP
);
1805 function addWords ($words, $tag = '') {
1806 if ($tag != $this->_tag
)
1807 $this->_flushGroup($tag);
1809 foreach ($words as $word) {
1810 // new-line should only come as first char of word.
1813 if ($word[0] == "\n") {
1814 $this->_flushLine($tag);
1815 $word = substr($word, 1);
1817 assert(!strstr($word, "\n"));
1818 $this->_group
.= $word;
1822 function getLines() {
1823 $this->_flushLine('~done');
1824 return $this->_lines
;
1831 * @ingroup DifferenceEngine
1833 class WordLevelDiff
extends MappedDiff
{
1834 const MAX_LINE_LENGTH
= 10000;
1836 function WordLevelDiff ($orig_lines, $closing_lines) {
1837 wfProfileIn( __METHOD__
);
1839 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1840 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1842 $this->MappedDiff($orig_words, $closing_words,
1843 $orig_stripped, $closing_stripped);
1844 wfProfileOut( __METHOD__
);
1847 function _split($lines) {
1848 wfProfileIn( __METHOD__
);
1851 $stripped = array();
1853 foreach ( $lines as $line ) {
1854 # If the line is too long, just pretend the entire line is one big word
1855 # This prevents resource exhaustion problems
1862 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1864 $stripped[] = $line;
1867 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1870 $words = array_merge( $words, $m[0] );
1871 $stripped = array_merge( $stripped, $m[1] );
1875 wfProfileOut( __METHOD__
);
1876 return array($words, $stripped);
1880 wfProfileIn( __METHOD__
);
1881 $orig = new _HWLDF_WordAccumulator
;
1883 foreach ($this->edits
as $edit) {
1884 if ($edit->type
== 'copy')
1885 $orig->addWords($edit->orig
);
1886 elseif ($edit->orig
)
1887 $orig->addWords($edit->orig
, 'del');
1889 $lines = $orig->getLines();
1890 wfProfileOut( __METHOD__
);
1894 function closing () {
1895 wfProfileIn( __METHOD__
);
1896 $closing = new _HWLDF_WordAccumulator
;
1898 foreach ($this->edits
as $edit) {
1899 if ($edit->type
== 'copy')
1900 $closing->addWords($edit->closing
);
1901 elseif ($edit->closing
)
1902 $closing->addWords($edit->closing
, 'ins');
1904 $lines = $closing->getLines();
1905 wfProfileOut( __METHOD__
);
1911 * Wikipedia Table style diff formatter.
1914 * @ingroup DifferenceEngine
1916 class TableDiffFormatter
extends DiffFormatter
{
1917 function TableDiffFormatter() {
1918 $this->leading_context_lines
= 2;
1919 $this->trailing_context_lines
= 2;
1922 public static function escapeWhiteSpace( $msg ) {
1923 $msg = preg_replace( '/^ /m', ' ', $msg );
1924 $msg = preg_replace( '/ $/m', ' ', $msg );
1925 $msg = preg_replace( '/ /', ' ', $msg );
1929 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1930 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1931 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1935 function _start_block( $header ) {
1939 function _end_block() {
1942 function _lines( $lines, $prefix=' ', $color='white' ) {
1945 # HTML-escape parameter before calling this
1946 function addedLine( $line ) {
1947 return $this->wrapLine( '+', 'diff-addedline', $line );
1950 # HTML-escape parameter before calling this
1951 function deletedLine( $line ) {
1952 return $this->wrapLine( '-', 'diff-deletedline', $line );
1955 # HTML-escape parameter before calling this
1956 function contextLine( $line ) {
1957 return $this->wrapLine( ' ', 'diff-context', $line );
1960 private function wrapLine( $marker, $class, $line ) {
1961 if( $line !== '' ) {
1962 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1963 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1965 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1968 function emptyLine() {
1969 return '<td colspan="2"> </td>';
1972 function _added( $lines ) {
1973 foreach ($lines as $line) {
1974 echo '<tr>' . $this->emptyLine() .
1975 $this->addedLine( '<ins class="diffchange">' .
1976 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1980 function _deleted($lines) {
1981 foreach ($lines as $line) {
1982 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1983 htmlspecialchars ( $line ) . '</del>' ) .
1984 $this->emptyLine() . "</tr>\n";
1988 function _context( $lines ) {
1989 foreach ($lines as $line) {
1991 $this->contextLine( htmlspecialchars ( $line ) ) .
1992 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1996 function _changed( $orig, $closing ) {
1997 wfProfileIn( __METHOD__
);
1999 $diff = new WordLevelDiff( $orig, $closing );
2000 $del = $diff->orig();
2001 $add = $diff->closing();
2003 # Notice that WordLevelDiff returns HTML-escaped output.
2004 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2006 while ( $line = array_shift( $del ) ) {
2007 $aline = array_shift( $add );
2008 echo '<tr>' . $this->deletedLine( $line ) .
2009 $this->addedLine( $aline ) . "</tr>\n";
2011 foreach ($add as $line) { # If any leftovers
2012 echo '<tr>' . $this->emptyLine() .
2013 $this->addedLine( $line ) . "</tr>\n";
2015 wfProfileOut( __METHOD__
);