4 * @todo indicate where diff.doc can be found.
5 * @addtogroup DifferenceEngine
9 * Constant to indicate diff cache compatibility.
10 * Bump this when changing the diff formatting in a way that
11 * fixes important bugs or such to force cached diff views to
14 define( 'MW_DIFF_VERSION', '1.11a' );
19 * @addtogroup DifferenceEngine
21 class DifferenceEngine
{
25 var $mOldid, $mNewid, $mTitle;
26 var $mOldtitle, $mNewtitle, $mPagetitle;
27 var $mOldtext, $mNewtext;
28 var $mOldPage, $mNewPage;
29 var $mRcidMarkPatrolled;
30 var $mOldRev, $mNewRev;
31 var $mRevisionsLoaded = false; // Have the revisions been loaded
32 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
37 * @param $titleObj Title object that the diff is associated with
38 * @param $old Integer: old ID we want to show and diff with.
39 * @param $new String: either 'prev' or 'next'.
40 * @param $rcid Integer: ??? FIXME (default 0)
41 * @param $refreshCache boolean If set, refreshes the diff cache
43 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false ) {
44 $this->mTitle
= $titleObj;
45 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
47 if ( 'prev' === $new ) {
48 # Show diff between revision $old and the previous one.
49 # Get previous one from DB.
51 $this->mNewid
= intval($old);
53 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
55 } elseif ( 'next' === $new ) {
56 # Show diff between revision $old and the previous one.
57 # Get previous one from DB.
59 $this->mOldid
= intval($old);
60 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
61 if ( false === $this->mNewid
) {
62 # if no result, NewId points to the newest old revision. The only newer
63 # revision is cur, which is "0".
68 $this->mOldid
= intval($old);
69 $this->mNewid
= intval($new);
71 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
72 $this->mRefreshCache
= $refreshCache;
75 function showDiffPage( $diffOnly = false ) {
76 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
77 $fname = 'DifferenceEngine::showDiffPage';
78 wfProfileIn( $fname );
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() . " (Diff: {$this->mOldid}, {$this->mNewid})";
112 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
113 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
114 wfProfileOut( $fname );
118 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
120 if ( $this->mNewRev
->isCurrent() ) {
121 $wgOut->setArticleFlag( true );
124 # mOldid is false if the difference engine is called with a "vague" query for
125 # a diff between a version V and its previous version V' AND the version V
126 # is the first version of that article. In that case, V' does not exist.
127 if ( $this->mOldid
=== false ) {
128 $this->showFirstRevision();
129 $this->renderNewRevision(); // should we respect $diffOnly here or not?
130 wfProfileOut( $fname );
134 $wgOut->suppressQuickbar();
136 $oldTitle = $this->mOldPage
->getPrefixedText();
137 $newTitle = $this->mNewPage
->getPrefixedText();
138 if( $oldTitle == $newTitle ) {
139 $wgOut->setPageTitle( $newTitle );
141 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
143 $wgOut->setSubtitle( wfMsg( 'difference' ) );
144 $wgOut->setRobotpolicy( 'noindex,nofollow' );
146 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
147 $wgOut->loginToUse();
149 wfProfileOut( $fname );
153 $sk = $wgUser->getSkin();
155 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
156 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
161 // Prepare a change patrol link, if applicable
162 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
163 // If we've been given an explicit change identifier, use it; saves time
164 if( $this->mRcidMarkPatrolled
) {
165 $rcid = $this->mRcidMarkPatrolled
;
167 // Look for an unpatrolled change corresponding to this diff
168 $db = wfGetDB( DB_SLAVE
);
169 $change = RecentChange
::newFromConds(
171 // Add redundant user,timestamp condition so we can use the existing index
172 'rc_user_text' => $this->mNewRev
->getRawUserText(),
173 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
174 'rc_this_oldid' => $this->mNewid
,
175 'rc_last_oldid' => $this->mOldid
,
180 if( $change instanceof RecentChange
) {
181 $rcid = $change->mAttribs
['rc_id'];
189 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
191 wfMsgHtml( 'markaspatrolleddiff' ),
192 "action=markpatrolled&rcid={$rcid}"
201 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
202 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
203 if ( $this->mNewRev
->isCurrent() ) {
204 $nextlink = ' ';
206 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
207 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
213 if ($this->mOldRev
->mMinorEdit
== 1) {
214 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
215 wfMsg( 'minoreditletter') ) . ' ';
218 if ($this->mNewRev
->mMinorEdit
== 1) {
219 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
220 wfMsg( 'minoreditletter') ) . ' ';
223 $rdel = ''; $ldel = '';
224 if( $wgUser->isAllowed( 'deleterevision' ) ) {
225 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
226 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
227 // If revision was hidden from sysops
228 $ldel = wfMsgHtml('rev-delundel');
230 $ldel = $sk->makeKnownLinkObj( $revdel,
231 wfMsgHtml('rev-delundel'),
232 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
233 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
234 // Bolden oversighted content
235 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
236 $ldel = "<strong>$ldel</strong>";
238 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
239 // We don't currently handle well changing the top revision's settings
240 if( $this->mNewRev
->isCurrent() ) {
241 // If revision was hidden from sysops
242 $rdel = wfMsgHtml('rev-delundel');
243 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
244 // If revision was hidden from sysops
245 $rdel = wfMsgHtml('rev-delundel');
247 $rdel = $sk->makeKnownLinkObj( $revdel,
248 wfMsgHtml('rev-delundel'),
249 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
250 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
251 // Bolden oversighted content
252 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
253 $rdel = "<strong>$rdel</strong>";
255 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
258 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
259 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
260 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
261 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
262 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
263 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
264 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
265 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
267 $this->showDiff( $oldHeader, $newHeader );
270 $this->renderNewRevision();
272 wfProfileOut( $fname );
276 * Show the new revision of the page.
278 function renderNewRevision() {
280 $fname = 'DifferenceEngine::renderNewRevision';
281 wfProfileIn( $fname );
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( $fname );
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;
329 $fname = 'DifferenceEngine::showFirstRevision';
330 wfProfileIn( $fname );
332 # Get article text from the DB
334 if ( ! $this->loadNewText() ) {
335 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
337 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
338 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
339 wfProfileOut( $fname );
342 if ( $this->mNewRev
->isCurrent() ) {
343 $wgOut->setArticleFlag( true );
346 # Check if user is allowed to look at this page. If not, bail out.
348 if ( !( $this->mTitle
->userCanRead() ) ) {
349 $wgOut->loginToUse();
351 wfProfileOut( $fname );
355 # Prepare the header box
357 $sk = $wgUser->getSkin();
359 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
360 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
361 $sk->revUserTools( $this->mNewRev
) . "<br />" .
362 $sk->revComment( $this->mNewRev
) . "<br />" .
363 $nextlink . "</div>\n";
365 $wgOut->addHTML( $header );
367 $wgOut->setSubtitle( wfMsg( 'difference' ) );
368 $wgOut->setRobotpolicy( 'noindex,nofollow' );
370 wfProfileOut( $fname );
374 * Get the diff text, send it to $wgOut
375 * Returns false if the diff could not be generated, otherwise returns true
377 function showDiff( $otitle, $ntitle ) {
379 $diff = $this->getDiff( $otitle, $ntitle );
380 if ( $diff === false ) {
381 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" );
384 $this->showDiffStyle();
385 $wgOut->addHTML( $diff );
391 * Add style sheets and supporting JS for diff display.
393 function showDiffStyle() {
394 global $wgStylePath, $wgStyleVersion, $wgOut;
395 $wgOut->addStyle( 'common/diff.css' );
397 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
398 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
402 * Get complete diff table, including header
404 * @param Title $otitle Old title
405 * @param Title $ntitle New title
408 function getDiff( $otitle, $ntitle ) {
409 $body = $this->getDiffBody();
410 if ( $body === false ) {
413 $multi = $this->getMultiNotice();
414 return $this->addHeader( $body, $otitle, $ntitle, $multi );
419 * Get the diff table body, without header
423 function getDiffBody() {
425 $fname = 'DifferenceEngine::getDiffBody';
426 wfProfileIn( $fname );
427 // Check if the diff should be hidden from this user
428 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
430 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
435 if ( $this->mOldid
&& $this->mNewid
) {
436 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
438 if ( !$this->mRefreshCache
) {
439 $difftext = $wgMemc->get( $key );
441 wfIncrStats( 'diff_cache_hit' );
442 $difftext = $this->localiseLineNumbers( $difftext );
443 $difftext .= "\n<!-- diff cache key $key -->\n";
444 wfProfileOut( $fname );
447 } // don't try to load but save the result
450 // Loadtext is permission safe, this just clears out the diff
451 if ( !$this->loadText() ) {
452 wfProfileOut( $fname );
456 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
458 // Save to cache for 7 days
459 if ( $key !== false && $difftext !== false ) {
460 wfIncrStats( 'diff_cache_miss' );
461 $wgMemc->set( $key, $difftext, 7*86400 );
463 wfIncrStats( 'diff_uncacheable' );
465 // Replace line numbers with the text in the user's language
466 if ( $difftext !== false ) {
467 $difftext = $this->localiseLineNumbers( $difftext );
469 wfProfileOut( $fname );
474 * Generate a diff, no caching
475 * $otext and $ntext must be already segmented
477 function generateDiffBody( $otext, $ntext ) {
478 global $wgExternalDiffEngine, $wgContLang;
479 $fname = 'DifferenceEngine::generateDiffBody';
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 ) );
495 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
496 # Better external diff engine, the 2 may some day be dropped
497 # This one does the escaping and segmenting itself
498 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
499 wfProfileIn( "$fname-dl" );
500 @dl
('php_wikidiff2.so');
501 wfProfileOut( "$fname-dl" );
503 if ( function_exists( 'wikidiff2_do_diff' ) ) {
504 wfProfileIn( 'wikidiff2_do_diff' );
505 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
506 wfProfileOut( 'wikidiff2_do_diff' );
510 if ( $wgExternalDiffEngine !== false ) {
512 global $wgTmpDirectory;
513 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
514 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
516 $tempFile1 = fopen( $tempName1, "w" );
518 wfProfileOut( $fname );
521 $tempFile2 = fopen( $tempName2, "w" );
523 wfProfileOut( $fname );
526 fwrite( $tempFile1, $otext );
527 fwrite( $tempFile2, $ntext );
528 fclose( $tempFile1 );
529 fclose( $tempFile2 );
530 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
531 wfProfileIn( "$fname-shellexec" );
532 $difftext = wfShellExec( $cmd );
533 wfProfileOut( "$fname-shellexec" );
534 unlink( $tempName1 );
535 unlink( $tempName2 );
540 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
541 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
542 $diffs = new Diff( $ota, $nta );
543 $formatter = new TableDiffFormatter();
544 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
549 * Replace line numbers with the text in the user's language
551 function localiseLineNumbers( $text ) {
552 return preg_replace_callback( '/<!--LINE (\d+)-->/',
553 array( &$this, 'localiseLineNumbersCb' ), $text );
556 function localiseLineNumbersCb( $matches ) {
558 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
563 * If there are revisions between the ones being compared, return a note saying so.
565 function getMultiNotice() {
566 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
569 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
570 // Comparing two different pages? Count would be meaningless.
574 $oldid = $this->mOldRev
->getId();
575 $newid = $this->mNewRev
->getId();
576 if ( $oldid > $newid ) {
577 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
580 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
584 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
589 * Add the header to a diff body
591 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
596 <col class='diff-marker' />
597 <col class='diff-content' />
598 <col class='diff-marker' />
599 <col class='diff-content' />
601 <td colspan='2' class='diff-otitle'>{$otitle}</td>
602 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
607 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
609 return $header . $diff . "</table>";
613 * Use specified text instead of loading from the database
615 function setText( $oldText, $newText ) {
616 $this->mOldtext
= $oldText;
617 $this->mNewtext
= $newText;
618 $this->mTextLoaded
= 2;
622 * Load revision metadata for the specified articles. If newid is 0, then compare
623 * the old article in oldid to the current article; if oldid is 0, then
624 * compare the current article to the immediately previous one (ignoring the
627 * If oldid is false, leave the corresponding revision object set
628 * to false. This is impossible via ordinary user input, and is provided for
631 function loadRevisionData() {
633 if ( $this->mRevisionsLoaded
) {
636 // Whether it succeeds or fails, we don't want to try again
637 $this->mRevisionsLoaded
= true;
640 // Load the new revision object
641 $this->mNewRev
= $this->mNewid
642 ? Revision
::newFromId( $this->mNewid
)
643 : Revision
::newFromTitle( $this->mTitle
);
644 if( !$this->mNewRev
instanceof Revision
)
647 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
648 $this->mNewid
= $this->mNewRev
->getId();
650 // Set assorted variables
651 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
652 $this->mNewPage
= $this->mNewRev
->getTitle();
653 if( $this->mNewRev
->isCurrent() ) {
654 $newLink = $this->mNewPage
->escapeLocalUrl();
655 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
656 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
658 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
659 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
662 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
663 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
664 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
666 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
667 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
669 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
670 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
671 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
672 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
675 // Load the old revision object
676 $this->mOldRev
= false;
677 if( $this->mOldid
) {
678 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
679 } elseif ( $this->mOldid
=== 0 ) {
680 $rev = $this->mNewRev
->getPrevious();
682 $this->mOldid
= $rev->getId();
683 $this->mOldRev
= $rev;
685 // No previous revision; mark to show as first-version only.
686 $this->mOldid
= false;
687 $this->mOldRev
= false;
689 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
691 if( is_null( $this->mOldRev
) ) {
695 if ( $this->mOldRev
) {
696 $this->mOldPage
= $this->mOldRev
->getTitle();
698 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
699 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
700 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
701 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
703 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
704 . " (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
705 // Add an "undo" link
706 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
707 if ( $this->mNewRev
->userCan(Revision
::DELETED_TEXT
) )
708 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
710 if ( !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
711 $this->mOldtitle
= "<span class='history-deleted'>{$this->mOldPagetitle}</span>";
712 } else if ( $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
713 $this->mOldtitle
= '<span class="history-deleted">'.$this->mOldtitle
.'</span>';
721 * Load the text of the revisions, as well as revision data.
723 function loadText() {
724 if ( $this->mTextLoaded
== 2 ) {
727 // Whether it succeeds or fails, we don't want to try again
728 $this->mTextLoaded
= 2;
731 if ( !$this->loadRevisionData() ) {
734 if ( $this->mOldRev
) {
735 $this->mOldtext
= $this->mOldRev
->revText();
736 if ( $this->mOldtext
=== false ) {
740 if ( $this->mNewRev
) {
741 $this->mNewtext
= $this->mNewRev
->revText();
742 if ( $this->mNewtext
=== false ) {
750 * Load the text of the new revision, not the old one
752 function loadNewText() {
753 if ( $this->mTextLoaded
>= 1 ) {
756 $this->mTextLoaded
= 1;
758 if ( !$this->loadRevisionData() ) {
761 $this->mNewtext
= $this->mNewRev
->getText();
768 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
770 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
771 // You may copy this code freely under the conditions of the GPL.
774 define('USE_ASSERTS', function_exists('assert'));
779 * @addtogroup DifferenceEngine
787 trigger_error('pure virtual', E_USER_ERROR
);
791 return $this->orig ?
sizeof($this->orig
) : 0;
794 function nclosing() {
795 return $this->closing ?
sizeof($this->closing
) : 0;
802 * @addtogroup DifferenceEngine
804 class _DiffOp_Copy
extends _DiffOp
{
807 function _DiffOp_Copy ($orig, $closing = false) {
808 if (!is_array($closing))
811 $this->closing
= $closing;
815 return new _DiffOp_Copy($this->closing
, $this->orig
);
822 * @addtogroup DifferenceEngine
824 class _DiffOp_Delete
extends _DiffOp
{
825 var $type = 'delete';
827 function _DiffOp_Delete ($lines) {
828 $this->orig
= $lines;
829 $this->closing
= false;
833 return new _DiffOp_Add($this->orig
);
840 * @addtogroup DifferenceEngine
842 class _DiffOp_Add
extends _DiffOp
{
845 function _DiffOp_Add ($lines) {
846 $this->closing
= $lines;
851 return new _DiffOp_Delete($this->closing
);
858 * @addtogroup DifferenceEngine
860 class _DiffOp_Change
extends _DiffOp
{
861 var $type = 'change';
863 function _DiffOp_Change ($orig, $closing) {
865 $this->closing
= $closing;
869 return new _DiffOp_Change($this->closing
, $this->orig
);
875 * Class used internally by Diff to actually compute the diffs.
877 * The algorithm used here is mostly lifted from the perl module
878 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
879 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
881 * More ideas are taken from:
882 * http://www.ics.uci.edu/~eppstein/161/960229.html
884 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
885 * diffutils-2.7, which can be found at:
886 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
888 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
891 * Line length limits for robustness added by Tim Starling, 2005-08-31
893 * @author Geoffrey T. Dairiki, Tim Starling
895 * @addtogroup DifferenceEngine
899 const MAX_XREF_LENGTH
= 10000;
901 function diff ($from_lines, $to_lines) {
902 $fname = '_DiffEngine::diff';
903 wfProfileIn( $fname );
905 $n_from = sizeof($from_lines);
906 $n_to = sizeof($to_lines);
908 $this->xchanged
= $this->ychanged
= array();
909 $this->xv
= $this->yv
= array();
910 $this->xind
= $this->yind
= array();
912 unset($this->in_seq
);
915 // Skip leading common lines.
916 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
917 if ($from_lines[$skip] !== $to_lines[$skip])
919 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
921 // Skip trailing common lines.
922 $xi = $n_from; $yi = $n_to;
923 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
924 if ($from_lines[$xi] !== $to_lines[$yi])
926 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
929 // Ignore lines which do not exist in both files.
930 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
931 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
934 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
935 $line = $to_lines[$yi];
936 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
938 $yhash[$this->_line_hash($line)] = 1;
942 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
943 $line = $from_lines[$xi];
944 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
951 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
953 // Merge edits when possible
954 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
955 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
957 // Compute the edit operations.
960 while ($xi < $n_from ||
$yi < $n_to) {
961 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
962 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
964 // Skip matching "snake".
966 while ( $xi < $n_from && $yi < $n_to
967 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
968 $copy[] = $from_lines[$xi++
];
972 $edits[] = new _DiffOp_Copy($copy);
974 // Find deletes & adds.
976 while ($xi < $n_from && $this->xchanged
[$xi])
977 $delete[] = $from_lines[$xi++
];
980 while ($yi < $n_to && $this->ychanged
[$yi])
981 $add[] = $to_lines[$yi++
];
984 $edits[] = new _DiffOp_Change($delete, $add);
986 $edits[] = new _DiffOp_Delete($delete);
988 $edits[] = new _DiffOp_Add($add);
990 wfProfileOut( $fname );
995 * Returns the whole line if it's small enough, or the MD5 hash otherwise
997 function _line_hash( $line ) {
998 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1006 /* Divide the Largest Common Subsequence (LCS) of the sequences
1007 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1010 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1011 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1012 * sub sequences. The first sub-sequence is contained in [X0, X1),
1013 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1014 * that (X0, Y0) == (XOFF, YOFF) and
1015 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1017 * This function assumes that the first lines of the specified portions
1018 * of the two files do not match, and likewise that the last lines do not
1019 * match. The caller must trim matching lines from the beginning and end
1020 * of the portions it is going to specify.
1022 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1023 $fname = '_DiffEngine::_diag';
1024 wfProfileIn( $fname );
1027 if ($xlim - $xoff > $ylim - $yoff) {
1028 // Things seems faster (I'm not sure I understand why)
1029 // when the shortest sequence in X.
1031 list ($xoff, $xlim, $yoff, $ylim)
1032 = array( $yoff, $ylim, $xoff, $xlim);
1036 for ($i = $ylim - 1; $i >= $yoff; $i--)
1037 $ymatches[$this->xv
[$i]][] = $i;
1039 for ($i = $ylim - 1; $i >= $yoff; $i--)
1040 $ymatches[$this->yv
[$i]][] = $i;
1043 $this->seq
[0]= $yoff - 1;
1044 $this->in_seq
= array();
1045 $ymids[0] = array();
1047 $numer = $xlim - $xoff +
$nchunks - 1;
1049 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1050 wfProfileIn( "$fname-chunk" );
1052 for ($i = 0; $i <= $this->lcs
; $i++
)
1053 $ymids[$i][$chunk-1] = $this->seq
[$i];
1055 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1056 for ( ; $x < $x1; $x++
) {
1057 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1058 if (empty($ymatches[$line]))
1060 $matches = $ymatches[$line];
1062 while (list ($junk, $y) = each($matches))
1063 if (empty($this->in_seq
[$y])) {
1064 $k = $this->_lcs_pos($y);
1065 USE_ASSERTS
&& assert($k > 0);
1066 $ymids[$k] = $ymids[$k-1];
1069 while (list ( /* $junk */, $y) = each($matches)) {
1070 if ($y > $this->seq
[$k-1]) {
1071 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1072 // Optimization: this is a common case:
1073 // next match is just replacing previous match.
1074 $this->in_seq
[$this->seq
[$k]] = false;
1075 $this->seq
[$k] = $y;
1076 $this->in_seq
[$y] = 1;
1077 } else if (empty($this->in_seq
[$y])) {
1078 $k = $this->_lcs_pos($y);
1079 USE_ASSERTS
&& assert($k > 0);
1080 $ymids[$k] = $ymids[$k-1];
1084 wfProfileOut( "$fname-chunk" );
1087 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1088 $ymid = $ymids[$this->lcs
];
1089 for ($n = 0; $n < $nchunks - 1; $n++
) {
1090 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1091 $y1 = $ymid[$n] +
1;
1092 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1094 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1096 wfProfileOut( $fname );
1097 return array($this->lcs
, $seps);
1100 function _lcs_pos ($ypos) {
1101 $fname = '_DiffEngine::_lcs_pos';
1102 wfProfileIn( $fname );
1105 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1106 $this->seq
[++
$this->lcs
] = $ypos;
1107 $this->in_seq
[$ypos] = 1;
1108 wfProfileOut( $fname );
1113 while ($beg < $end) {
1114 $mid = (int)(($beg +
$end) / 2);
1115 if ( $ypos > $this->seq
[$mid] )
1121 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1123 $this->in_seq
[$this->seq
[$end]] = false;
1124 $this->seq
[$end] = $ypos;
1125 $this->in_seq
[$ypos] = 1;
1126 wfProfileOut( $fname );
1130 /* Find LCS of two sequences.
1132 * The results are recorded in the vectors $this->{x,y}changed[], by
1133 * storing a 1 in the element for each line that is an insertion
1134 * or deletion (ie. is not in the LCS).
1136 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1138 * Note that XLIM, YLIM are exclusive bounds.
1139 * All line numbers are origin-0 and discarded lines are not counted.
1141 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1142 $fname = '_DiffEngine::_compareseq';
1143 wfProfileIn( $fname );
1145 // Slide down the bottom initial diagonal.
1146 while ($xoff < $xlim && $yoff < $ylim
1147 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1152 // Slide up the top initial diagonal.
1153 while ($xlim > $xoff && $ylim > $yoff
1154 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1159 if ($xoff == $xlim ||
$yoff == $ylim)
1162 // This is ad hoc but seems to work well.
1163 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1164 //$nchunks = max(2,min(8,(int)$nchunks));
1165 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1167 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1171 // X and Y sequences have no common subsequence:
1172 // mark all changed.
1173 while ($yoff < $ylim)
1174 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1175 while ($xoff < $xlim)
1176 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1178 // Use the partitions to split this problem into subproblems.
1181 while ($pt2 = next($seps)) {
1182 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1186 wfProfileOut( $fname );
1189 /* Adjust inserts/deletes of identical lines to join changes
1190 * as much as possible.
1192 * We do something when a run of changed lines include a
1193 * line at one end and has an excluded, identical line at the other.
1194 * We are free to choose which identical line is included.
1195 * `compareseq' usually chooses the one at the beginning,
1196 * but usually it is cleaner to consider the following identical line
1197 * to be the "change".
1199 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1201 function _shift_boundaries ($lines, &$changed, $other_changed) {
1202 $fname = '_DiffEngine::_shift_boundaries';
1203 wfProfileIn( $fname );
1207 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1208 $len = sizeof($lines);
1209 $other_len = sizeof($other_changed);
1213 * Scan forwards to find beginning of another run of changes.
1214 * Also keep track of the corresponding point in the other file.
1216 * Throughout this code, $i and $j are adjusted together so that
1217 * the first $i elements of $changed and the first $j elements
1218 * of $other_changed both contain the same number of zeros
1219 * (unchanged lines).
1220 * Furthermore, $j is always kept so that $j == $other_len or
1221 * $other_changed[$j] == false.
1223 while ($j < $other_len && $other_changed[$j])
1226 while ($i < $len && ! $changed[$i]) {
1227 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1229 while ($j < $other_len && $other_changed[$j])
1238 // Find the end of this run of changes.
1239 while (++
$i < $len && $changed[$i])
1244 * Record the length of this run of changes, so that
1245 * we can later determine whether the run has grown.
1247 $runlength = $i - $start;
1250 * Move the changed region back, so long as the
1251 * previous unchanged line matches the last changed one.
1252 * This merges with previous changed regions.
1254 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1255 $changed[--$start] = 1;
1256 $changed[--$i] = false;
1257 while ($start > 0 && $changed[$start - 1])
1259 USE_ASSERTS
&& assert('$j > 0');
1260 while ($other_changed[--$j])
1262 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1266 * Set CORRESPONDING to the end of the changed run, at the last
1267 * point where it corresponds to a changed run in the other file.
1268 * CORRESPONDING == LEN means no such point has been found.
1270 $corresponding = $j < $other_len ?
$i : $len;
1273 * Move the changed region forward, so long as the
1274 * first changed line matches the following unchanged one.
1275 * This merges with following changed regions.
1276 * Do this second, so that if there are no merges,
1277 * the changed region is moved forward as far as possible.
1279 while ($i < $len && $lines[$start] == $lines[$i]) {
1280 $changed[$start++
] = false;
1282 while ($i < $len && $changed[$i])
1285 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1287 if ($j < $other_len && $other_changed[$j]) {
1288 $corresponding = $i;
1289 while ($j < $other_len && $other_changed[$j])
1293 } while ($runlength != $i - $start);
1296 * If possible, move the fully-merged run of changes
1297 * back to a corresponding run in the other file.
1299 while ($corresponding < $i) {
1300 $changed[--$start] = 1;
1302 USE_ASSERTS
&& assert('$j > 0');
1303 while ($other_changed[--$j])
1305 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1308 wfProfileOut( $fname );
1313 * Class representing a 'diff' between two sequences of strings.
1316 * @addtogroup DifferenceEngine
1324 * Computes diff between sequences of strings.
1326 * @param $from_lines array An array of strings.
1327 * (Typically these are lines from a file.)
1328 * @param $to_lines array An array of strings.
1330 function Diff($from_lines, $to_lines) {
1331 $eng = new _DiffEngine
;
1332 $this->edits
= $eng->diff($from_lines, $to_lines);
1333 //$this->_check($from_lines, $to_lines);
1337 * Compute reversed Diff.
1341 * $diff = new Diff($lines1, $lines2);
1342 * $rev = $diff->reverse();
1343 * @return object A Diff object representing the inverse of the
1346 function reverse () {
1348 $rev->edits
= array();
1349 foreach ($this->edits
as $edit) {
1350 $rev->edits
[] = $edit->reverse();
1356 * Check for empty diff.
1358 * @return bool True iff two sequences were identical.
1360 function isEmpty () {
1361 foreach ($this->edits
as $edit) {
1362 if ($edit->type
!= 'copy')
1369 * Compute the length of the Longest Common Subsequence (LCS).
1371 * This is mostly for diagnostic purposed.
1373 * @return int The length of the LCS.
1377 foreach ($this->edits
as $edit) {
1378 if ($edit->type
== 'copy')
1379 $lcs +
= sizeof($edit->orig
);
1385 * Get the original set of lines.
1387 * This reconstructs the $from_lines parameter passed to the
1390 * @return array The original sequence of strings.
1395 foreach ($this->edits
as $edit) {
1397 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1403 * Get the closing set of lines.
1405 * This reconstructs the $to_lines parameter passed to the
1408 * @return array The sequence of strings.
1410 function closing() {
1413 foreach ($this->edits
as $edit) {
1415 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1421 * Check a Diff for validity.
1423 * This is here only for debugging purposes.
1425 function _check ($from_lines, $to_lines) {
1426 $fname = 'Diff::_check';
1427 wfProfileIn( $fname );
1428 if (serialize($from_lines) != serialize($this->orig()))
1429 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1430 if (serialize($to_lines) != serialize($this->closing()))
1431 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1433 $rev = $this->reverse();
1434 if (serialize($to_lines) != serialize($rev->orig()))
1435 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1436 if (serialize($from_lines) != serialize($rev->closing()))
1437 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1441 foreach ($this->edits
as $edit) {
1442 if ( $prevtype == $edit->type
)
1443 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1444 $prevtype = $edit->type
;
1447 $lcs = $this->lcs();
1448 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1449 wfProfileOut( $fname );
1454 * @todo document, bad name.
1456 * @addtogroup DifferenceEngine
1458 class MappedDiff
extends Diff
1463 * Computes diff between sequences of strings.
1465 * This can be used to compute things like
1466 * case-insensitve diffs, or diffs which ignore
1467 * changes in white-space.
1469 * @param $from_lines array An array of strings.
1470 * (Typically these are lines from a file.)
1472 * @param $to_lines array An array of strings.
1474 * @param $mapped_from_lines array This array should
1475 * have the same size number of elements as $from_lines.
1476 * The elements in $mapped_from_lines and
1477 * $mapped_to_lines are what is actually compared
1478 * when computing the diff.
1480 * @param $mapped_to_lines array This array should
1481 * have the same number of elements as $to_lines.
1483 function MappedDiff($from_lines, $to_lines,
1484 $mapped_from_lines, $mapped_to_lines) {
1485 $fname = 'MappedDiff::MappedDiff';
1486 wfProfileIn( $fname );
1488 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1489 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1491 $this->Diff($mapped_from_lines, $mapped_to_lines);
1494 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1495 $orig = &$this->edits
[$i]->orig
;
1496 if (is_array($orig)) {
1497 $orig = array_slice($from_lines, $xi, sizeof($orig));
1498 $xi +
= sizeof($orig);
1501 $closing = &$this->edits
[$i]->closing
;
1502 if (is_array($closing)) {
1503 $closing = array_slice($to_lines, $yi, sizeof($closing));
1504 $yi +
= sizeof($closing);
1507 wfProfileOut( $fname );
1512 * A class to format Diffs
1514 * This class formats the diff in classic diff format.
1515 * It is intended that this class be customized via inheritance,
1516 * to obtain fancier outputs.
1519 * @addtogroup DifferenceEngine
1524 * Number of leading context "lines" to preserve.
1526 * This should be left at zero for this class, but subclasses
1527 * may want to set this to other values.
1529 var $leading_context_lines = 0;
1532 * Number of trailing context "lines" to preserve.
1534 * This should be left at zero for this class, but subclasses
1535 * may want to set this to other values.
1537 var $trailing_context_lines = 0;
1542 * @param $diff object A Diff object.
1543 * @return string The formatted output.
1545 function format($diff) {
1546 $fname = 'DiffFormatter::format';
1547 wfProfileIn( $fname );
1553 $nlead = $this->leading_context_lines
;
1554 $ntrail = $this->trailing_context_lines
;
1556 $this->_start_diff();
1558 foreach ($diff->edits
as $edit) {
1559 if ($edit->type
== 'copy') {
1560 if (is_array($block)) {
1561 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1566 $context = array_slice($edit->orig
, 0, $ntrail);
1567 $block[] = new _DiffOp_Copy($context);
1569 $this->_block($x0, $ntrail +
$xi - $x0,
1570 $y0, $ntrail +
$yi - $y0,
1575 $context = $edit->orig
;
1578 if (! is_array($block)) {
1579 $context = array_slice($context, sizeof($context) - $nlead);
1580 $x0 = $xi - sizeof($context);
1581 $y0 = $yi - sizeof($context);
1584 $block[] = new _DiffOp_Copy($context);
1590 $xi +
= sizeof($edit->orig
);
1592 $yi +
= sizeof($edit->closing
);
1595 if (is_array($block))
1596 $this->_block($x0, $xi - $x0,
1600 $end = $this->_end_diff();
1601 wfProfileOut( $fname );
1605 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1606 $fname = 'DiffFormatter::_block';
1607 wfProfileIn( $fname );
1608 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1609 foreach ($edits as $edit) {
1610 if ($edit->type
== 'copy')
1611 $this->_context($edit->orig
);
1612 elseif ($edit->type
== 'add')
1613 $this->_added($edit->closing
);
1614 elseif ($edit->type
== 'delete')
1615 $this->_deleted($edit->orig
);
1616 elseif ($edit->type
== 'change')
1617 $this->_changed($edit->orig
, $edit->closing
);
1619 trigger_error('Unknown edit type', E_USER_ERROR
);
1621 $this->_end_block();
1622 wfProfileOut( $fname );
1625 function _start_diff() {
1629 function _end_diff() {
1630 $val = ob_get_contents();
1635 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1637 $xbeg .= "," . ($xbeg +
$xlen - 1);
1639 $ybeg .= "," . ($ybeg +
$ylen - 1);
1641 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1644 function _start_block($header) {
1645 echo $header . "\n";
1648 function _end_block() {
1651 function _lines($lines, $prefix = ' ') {
1652 foreach ($lines as $line)
1653 echo "$prefix $line\n";
1656 function _context($lines) {
1657 $this->_lines($lines);
1660 function _added($lines) {
1661 $this->_lines($lines, '>');
1663 function _deleted($lines) {
1664 $this->_lines($lines, '<');
1667 function _changed($orig, $closing) {
1668 $this->_deleted($orig);
1670 $this->_added($closing);
1675 * A formatter that outputs unified diffs
1676 * @addtogroup DifferenceEngine
1679 class UnifiedDiffFormatter
extends DiffFormatter
1681 var $leading_context_lines = 2;
1682 var $trailing_context_lines = 2;
1684 function _added($lines) {
1685 $this->_lines($lines, '+');
1687 function _deleted($lines) {
1688 $this->_lines($lines, '-');
1690 function _changed($orig, $closing) {
1691 $this->_deleted($orig);
1692 $this->_added($closing);
1694 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1695 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1700 * A pseudo-formatter that just passes along the Diff::$edits array
1701 * @addtogroup DifferenceEngine
1703 class ArrayDiffFormatter
extends DiffFormatter
1705 function format($diff)
1710 foreach($diff->edits
as $edit)
1714 foreach($edit->closing
as $l)
1719 'newline' => $newline++
1724 foreach($edit->orig
as $l)
1727 'action' => 'delete',
1729 'oldline' => $oldline++
,
1734 foreach($edit->orig
as $i => $l)
1737 'action' => 'change',
1739 'new' => @$edit->closing
[$i],
1740 'oldline' => $oldline++
,
1741 'newline' => $newline++
,
1746 $oldline +
= count($edit->orig
);
1747 $newline +
= count($edit->orig
);
1754 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1758 define('NBSP', ' '); // iso-8859-x non-breaking space.
1763 * @addtogroup DifferenceEngine
1765 class _HWLDF_WordAccumulator
{
1766 function _HWLDF_WordAccumulator () {
1767 $this->_lines
= array();
1773 function _flushGroup ($new_tag) {
1774 if ($this->_group
!== '') {
1775 if ($this->_tag
== 'ins')
1776 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1777 htmlspecialchars ( $this->_group
) . '</ins>';
1778 elseif ($this->_tag
== 'del')
1779 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1780 htmlspecialchars ( $this->_group
) . '</del>';
1782 $this->_line
.= htmlspecialchars ( $this->_group
);
1785 $this->_tag
= $new_tag;
1788 function _flushLine ($new_tag) {
1789 $this->_flushGroup($new_tag);
1790 if ($this->_line
!= '')
1791 array_push ( $this->_lines
, $this->_line
);
1793 # make empty lines visible by inserting an NBSP
1794 array_push ( $this->_lines
, NBSP
);
1798 function addWords ($words, $tag = '') {
1799 if ($tag != $this->_tag
)
1800 $this->_flushGroup($tag);
1802 foreach ($words as $word) {
1803 // new-line should only come as first char of word.
1806 if ($word[0] == "\n") {
1807 $this->_flushLine($tag);
1808 $word = substr($word, 1);
1810 assert(!strstr($word, "\n"));
1811 $this->_group
.= $word;
1815 function getLines() {
1816 $this->_flushLine('~done');
1817 return $this->_lines
;
1824 * @addtogroup DifferenceEngine
1826 class WordLevelDiff
extends MappedDiff
1828 const MAX_LINE_LENGTH
= 10000;
1830 function WordLevelDiff ($orig_lines, $closing_lines) {
1831 $fname = 'WordLevelDiff::WordLevelDiff';
1832 wfProfileIn( $fname );
1834 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1835 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1837 $this->MappedDiff($orig_words, $closing_words,
1838 $orig_stripped, $closing_stripped);
1839 wfProfileOut( $fname );
1842 function _split($lines) {
1843 $fname = 'WordLevelDiff::_split';
1844 wfProfileIn( $fname );
1847 $stripped = array();
1849 foreach ( $lines as $line ) {
1850 # If the line is too long, just pretend the entire line is one big word
1851 # This prevents resource exhaustion problems
1858 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1860 $stripped[] = $line;
1863 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1866 $words = array_merge( $words, $m[0] );
1867 $stripped = array_merge( $stripped, $m[1] );
1871 wfProfileOut( $fname );
1872 return array($words, $stripped);
1876 $fname = 'WordLevelDiff::orig';
1877 wfProfileIn( $fname );
1878 $orig = new _HWLDF_WordAccumulator
;
1880 foreach ($this->edits
as $edit) {
1881 if ($edit->type
== 'copy')
1882 $orig->addWords($edit->orig
);
1883 elseif ($edit->orig
)
1884 $orig->addWords($edit->orig
, 'del');
1886 $lines = $orig->getLines();
1887 wfProfileOut( $fname );
1891 function closing () {
1892 $fname = 'WordLevelDiff::closing';
1893 wfProfileIn( $fname );
1894 $closing = new _HWLDF_WordAccumulator
;
1896 foreach ($this->edits
as $edit) {
1897 if ($edit->type
== 'copy')
1898 $closing->addWords($edit->closing
);
1899 elseif ($edit->closing
)
1900 $closing->addWords($edit->closing
, 'ins');
1902 $lines = $closing->getLines();
1903 wfProfileOut( $fname );
1909 * Wikipedia Table style diff formatter.
1912 * @addtogroup DifferenceEngine
1914 class TableDiffFormatter
extends DiffFormatter
1916 function TableDiffFormatter() {
1917 $this->leading_context_lines
= 2;
1918 $this->trailing_context_lines
= 2;
1921 public static function escapeWhiteSpace( $msg ) {
1922 $msg = preg_replace( '/^ /m', ' ', $msg );
1923 $msg = preg_replace( '/ $/m', ' ', $msg );
1924 $msg = preg_replace( '/ /', ' ', $msg );
1928 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1929 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1930 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1934 function _start_block( $header ) {
1938 function _end_block() {
1941 function _lines( $lines, $prefix=' ', $color='white' ) {
1944 # HTML-escape parameter before calling this
1945 function addedLine( $line ) {
1946 return $this->wrapLine( '+', 'diff-addedline', $line );
1949 # HTML-escape parameter before calling this
1950 function deletedLine( $line ) {
1951 return $this->wrapLine( '-', 'diff-deletedline', $line );
1954 # HTML-escape parameter before calling this
1955 function contextLine( $line ) {
1956 return $this->wrapLine( ' ', 'diff-context', $line );
1959 private function wrapLine( $marker, $class, $line ) {
1960 if( $line !== '' ) {
1961 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1962 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1964 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1967 function emptyLine() {
1968 return '<td colspan="2"> </td>';
1971 function _added( $lines ) {
1972 foreach ($lines as $line) {
1973 echo '<tr>' . $this->emptyLine() .
1974 $this->addedLine( '<ins class="diffchange">' .
1975 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1979 function _deleted($lines) {
1980 foreach ($lines as $line) {
1981 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1982 htmlspecialchars ( $line ) . '</del>' ) .
1983 $this->emptyLine() . "</tr>\n";
1987 function _context( $lines ) {
1988 foreach ($lines as $line) {
1990 $this->contextLine( htmlspecialchars ( $line ) ) .
1991 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1995 function _changed( $orig, $closing ) {
1996 $fname = 'TableDiffFormatter::_changed';
1997 wfProfileIn( $fname );
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( $fname );