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".
67 } else if( 'cur' === $new ) {
68 # Show diff between revision $old and the current one.
69 # Get previous one from DB.
71 $this->mNewid
= $this->mTitle
->getLatestRevID();
73 $this->mOldid
= intval($old);
75 $this->mOldid
= intval($old);
76 $this->mNewid
= intval($new);
78 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
79 $this->mRefreshCache
= $refreshCache;
82 function showDiffPage( $diffOnly = false ) {
83 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
84 $fname = 'DifferenceEngine::showDiffPage';
85 wfProfileIn( $fname );
87 # If external diffs are enabled both globally and for the user,
88 # we'll use the application/x-external-editor interface to call
89 # an external diff tool like kompare, kdiff3, etc.
90 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
91 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
93 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
94 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
95 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
96 $special=$wgLang->getNsText(NS_SPECIAL
);
101 Script={$wgServer}{$wgScript}
102 Special namespace={$special}
116 $wgOut->setArticleFlag( false );
117 if ( ! $this->loadRevisionData() ) {
118 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
119 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
120 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
121 $wgOut->addWikitext( $mtext );
122 wfProfileOut( $fname );
126 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
128 if ( $this->mNewRev
->isCurrent() ) {
129 $wgOut->setArticleFlag( true );
132 # mOldid is false if the difference engine is called with a "vague" query for
133 # a diff between a version V and its previous version V' AND the version V
134 # is the first version of that article. In that case, V' does not exist.
135 if ( $this->mOldid
=== false ) {
136 $this->showFirstRevision();
137 $this->renderNewRevision(); // should we respect $diffOnly here or not?
138 wfProfileOut( $fname );
142 $wgOut->suppressQuickbar();
144 $oldTitle = $this->mOldPage
->getPrefixedText();
145 $newTitle = $this->mNewPage
->getPrefixedText();
146 if( $oldTitle == $newTitle ) {
147 $wgOut->setPageTitle( $newTitle );
149 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
151 $wgOut->setSubtitle( wfMsg( 'difference' ) );
152 $wgOut->setRobotpolicy( 'noindex,nofollow' );
154 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
155 $wgOut->loginToUse();
157 wfProfileOut( $fname );
161 $sk = $wgUser->getSkin();
163 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
164 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
169 // Prepare a change patrol link, if applicable
170 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
171 // If we've been given an explicit change identifier, use it; saves time
172 if( $this->mRcidMarkPatrolled
) {
173 $rcid = $this->mRcidMarkPatrolled
;
175 // Look for an unpatrolled change corresponding to this diff
176 $db = wfGetDB( DB_SLAVE
);
177 $change = RecentChange
::newFromConds(
179 // Add redundant timestamp condition so we can use the
181 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
182 'rc_this_oldid' => $this->mNewid
,
183 'rc_last_oldid' => $this->mOldid
,
188 if( $change instanceof RecentChange
) {
189 $rcid = $change->mAttribs
['rc_id'];
197 $patrol = ' [' . $sk->makeKnownLinkObj(
199 wfMsgHtml( 'markaspatrolleddiff' ),
200 "action=markpatrolled&rcid={$rcid}"
209 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
210 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
211 if ( $this->mNewRev
->isCurrent() ) {
212 $nextlink = ' ';
214 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
215 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
221 if ($this->mOldRev
->mMinorEdit
== 1) {
222 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
223 wfMsg( 'minoreditletter') ) . ' ';
226 if ($this->mNewRev
->mMinorEdit
== 1) {
227 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
228 wfMsg( 'minoreditletter') ) . ' ';
231 $rdel = ''; $ldel = '';
232 if( $wgUser->isAllowed( 'deleterevision' ) ) {
233 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
234 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
235 // If revision was hidden from sysops
236 $ldel = wfMsgHtml('rev-delundel');
238 $ldel = $sk->makeKnownLinkObj( $revdel,
239 wfMsgHtml('rev-delundel'),
240 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
241 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
242 // Bolden oversighted content
243 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
244 $ldel = "<strong>$ldel</strong>";
246 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
247 // We don't currently handle well changing the top revision's settings
248 if( $this->mNewRev
->isCurrent() ) {
249 // If revision was hidden from sysops
250 $rdel = wfMsgHtml('rev-delundel');
251 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
252 // If revision was hidden from sysops
253 $rdel = wfMsgHtml('rev-delundel');
255 $rdel = $sk->makeKnownLinkObj( $revdel,
256 wfMsgHtml('rev-delundel'),
257 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
258 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
259 // Bolden oversighted content
260 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
261 $rdel = "<strong>$rdel</strong>";
263 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
266 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
267 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
268 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
269 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
270 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
271 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
272 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
273 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
275 $this->showDiff( $oldHeader, $newHeader );
278 $this->renderNewRevision();
280 wfProfileOut( $fname );
284 * Show the new revision of the page.
286 function renderNewRevision() {
288 $fname = 'DifferenceEngine::renderNewRevision';
289 wfProfileIn( $fname );
291 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
292 #add deleted rev tag if needed
293 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
294 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
295 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
296 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
299 if( !$this->mNewRev
->isCurrent() ) {
300 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
303 $this->loadNewText();
304 if( is_object( $this->mNewRev
) ) {
305 $wgOut->setRevisionId( $this->mNewRev
->getId() );
308 $wgOut->addWikiTextTidy( $this->mNewtext
);
310 if( !$this->mNewRev
->isCurrent() ) {
311 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
314 wfProfileOut( $fname );
318 * Show the first revision of an article. Uses normal diff headers in
319 * contrast to normal "old revision" display style.
321 function showFirstRevision() {
322 global $wgOut, $wgUser;
324 $fname = 'DifferenceEngine::showFirstRevision';
325 wfProfileIn( $fname );
327 # Get article text from the DB
329 if ( ! $this->loadNewText() ) {
330 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
332 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
333 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
334 $wgOut->addWikitext( $mtext );
335 wfProfileOut( $fname );
338 if ( $this->mNewRev
->isCurrent() ) {
339 $wgOut->setArticleFlag( true );
342 # Check if user is allowed to look at this page. If not, bail out.
344 if ( !( $this->mTitle
->userCanRead() ) ) {
345 $wgOut->loginToUse();
347 wfProfileOut( $fname );
351 # Prepare the header box
353 $sk = $wgUser->getSkin();
355 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
356 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
357 $sk->revUserTools( $this->mNewRev
) . "<br />" .
358 $sk->revComment( $this->mNewRev
) . "<br />" .
359 $nextlink . "</div>\n";
361 $wgOut->addHTML( $header );
363 $wgOut->setSubtitle( wfMsg( 'difference' ) );
364 $wgOut->setRobotpolicy( 'noindex,nofollow' );
366 wfProfileOut( $fname );
370 * Get the diff text, send it to $wgOut
371 * Returns false if the diff could not be generated, otherwise returns true
373 function showDiff( $otitle, $ntitle ) {
375 $diff = $this->getDiff( $otitle, $ntitle );
376 if ( $diff === false ) {
377 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
380 $this->showDiffStyle();
381 $wgOut->addHTML( $diff );
387 * Add style sheets and supporting JS for diff display.
389 function showDiffStyle() {
390 global $wgStylePath, $wgStyleVersion, $wgOut;
391 $wgOut->addStyle( 'common/diff.css' );
393 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
394 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
398 * Get complete diff table, including header
400 * @param Title $otitle Old title
401 * @param Title $ntitle New title
404 function getDiff( $otitle, $ntitle ) {
405 $body = $this->getDiffBody();
406 if ( $body === false ) {
409 $multi = $this->getMultiNotice();
410 return $this->addHeader( $body, $otitle, $ntitle, $multi );
415 * Get the diff table body, without header
419 function getDiffBody() {
421 $fname = 'DifferenceEngine::getDiffBody';
422 wfProfileIn( $fname );
426 if ( $this->mOldid
&& $this->mNewid
) {
427 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
429 if ( !$this->mRefreshCache
) {
430 $difftext = $wgMemc->get( $key );
432 wfIncrStats( 'diff_cache_hit' );
433 $difftext = $this->localiseLineNumbers( $difftext );
434 $difftext .= "\n<!-- diff cache key $key -->\n";
435 wfProfileOut( $fname );
438 } // don't try to load but save the result
441 // Loadtext is permission safe, this just clears out the diff
442 if ( !$this->loadText() ) {
443 wfProfileOut( $fname );
445 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
447 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
451 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
453 // Save to cache for 7 days
454 // Only do this for public revs, otherwise an admin can view the diff and a non-admin can nab it!
455 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
456 wfIncrStats( 'diff_uncacheable' );
457 } else if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
458 wfIncrStats( 'diff_uncacheable' );
459 } else 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
= htmlspecialchars( wfMsg( '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) {
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);
1676 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1680 define('NBSP', ' '); // iso-8859-x non-breaking space.
1685 * @addtogroup DifferenceEngine
1687 class _HWLDF_WordAccumulator
{
1688 function _HWLDF_WordAccumulator () {
1689 $this->_lines
= array();
1695 function _flushGroup ($new_tag) {
1696 if ($this->_group
!== '') {
1697 if ($this->_tag
== 'ins')
1698 $this->_line
.= '<ins class="diffchange">' .
1699 htmlspecialchars ( $this->_group
) . '</ins>';
1700 elseif ($this->_tag
== 'del')
1701 $this->_line
.= '<del class="diffchange">' .
1702 htmlspecialchars ( $this->_group
) . '</del>';
1704 $this->_line
.= htmlspecialchars ( $this->_group
);
1707 $this->_tag
= $new_tag;
1710 function _flushLine ($new_tag) {
1711 $this->_flushGroup($new_tag);
1712 if ($this->_line
!= '')
1713 array_push ( $this->_lines
, $this->_line
);
1715 # make empty lines visible by inserting an NBSP
1716 array_push ( $this->_lines
, NBSP
);
1720 function addWords ($words, $tag = '') {
1721 if ($tag != $this->_tag
)
1722 $this->_flushGroup($tag);
1724 foreach ($words as $word) {
1725 // new-line should only come as first char of word.
1728 if ($word[0] == "\n") {
1729 $this->_flushLine($tag);
1730 $word = substr($word, 1);
1732 assert(!strstr($word, "\n"));
1733 $this->_group
.= $word;
1737 function getLines() {
1738 $this->_flushLine('~done');
1739 return $this->_lines
;
1746 * @addtogroup DifferenceEngine
1748 class WordLevelDiff
extends MappedDiff
1750 const MAX_LINE_LENGTH
= 10000;
1752 function WordLevelDiff ($orig_lines, $closing_lines) {
1753 $fname = 'WordLevelDiff::WordLevelDiff';
1754 wfProfileIn( $fname );
1756 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1757 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1759 $this->MappedDiff($orig_words, $closing_words,
1760 $orig_stripped, $closing_stripped);
1761 wfProfileOut( $fname );
1764 function _split($lines) {
1765 $fname = 'WordLevelDiff::_split';
1766 wfProfileIn( $fname );
1769 $stripped = array();
1771 foreach ( $lines as $line ) {
1772 # If the line is too long, just pretend the entire line is one big word
1773 # This prevents resource exhaustion problems
1780 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1782 $stripped[] = $line;
1785 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1788 $words = array_merge( $words, $m[0] );
1789 $stripped = array_merge( $stripped, $m[1] );
1793 wfProfileOut( $fname );
1794 return array($words, $stripped);
1798 $fname = 'WordLevelDiff::orig';
1799 wfProfileIn( $fname );
1800 $orig = new _HWLDF_WordAccumulator
;
1802 foreach ($this->edits
as $edit) {
1803 if ($edit->type
== 'copy')
1804 $orig->addWords($edit->orig
);
1805 elseif ($edit->orig
)
1806 $orig->addWords($edit->orig
, 'del');
1808 $lines = $orig->getLines();
1809 wfProfileOut( $fname );
1813 function closing () {
1814 $fname = 'WordLevelDiff::closing';
1815 wfProfileIn( $fname );
1816 $closing = new _HWLDF_WordAccumulator
;
1818 foreach ($this->edits
as $edit) {
1819 if ($edit->type
== 'copy')
1820 $closing->addWords($edit->closing
);
1821 elseif ($edit->closing
)
1822 $closing->addWords($edit->closing
, 'ins');
1824 $lines = $closing->getLines();
1825 wfProfileOut( $fname );
1831 * Wikipedia Table style diff formatter.
1834 * @addtogroup DifferenceEngine
1836 class TableDiffFormatter
extends DiffFormatter
1838 function TableDiffFormatter() {
1839 $this->leading_context_lines
= 2;
1840 $this->trailing_context_lines
= 2;
1843 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1844 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1845 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1849 function _start_block( $header ) {
1853 function _end_block() {
1856 function _lines( $lines, $prefix=' ', $color='white' ) {
1859 # HTML-escape parameter before calling this
1860 function addedLine( $line ) {
1861 return $this->wrapLine( '+', 'diff-addedline', $line );
1864 # HTML-escape parameter before calling this
1865 function deletedLine( $line ) {
1866 return $this->wrapLine( '-', 'diff-deletedline', $line );
1869 # HTML-escape parameter before calling this
1870 function contextLine( $line ) {
1871 return $this->wrapLine( ' ', 'diff-context', $line );
1874 private function wrapLine( $marker, $class, $line ) {
1875 if( $line !== '' ) {
1876 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1877 $line = "<div>$line</div>";
1879 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1882 function emptyLine() {
1883 return '<td colspan="2"> </td>';
1886 function _added( $lines ) {
1887 foreach ($lines as $line) {
1888 echo '<tr>' . $this->emptyLine() .
1889 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1893 function _deleted($lines) {
1894 foreach ($lines as $line) {
1895 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1896 $this->emptyLine() . "</tr>\n";
1900 function _context( $lines ) {
1901 foreach ($lines as $line) {
1903 $this->contextLine( htmlspecialchars ( $line ) ) .
1904 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1908 function _changed( $orig, $closing ) {
1909 $fname = 'TableDiffFormatter::_changed';
1910 wfProfileIn( $fname );
1912 $diff = new WordLevelDiff( $orig, $closing );
1913 $del = $diff->orig();
1914 $add = $diff->closing();
1916 # Notice that WordLevelDiff returns HTML-escaped output.
1917 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1919 while ( $line = array_shift( $del ) ) {
1920 $aline = array_shift( $add );
1921 echo '<tr>' . $this->deletedLine( $line ) .
1922 $this->addedLine( $aline ) . "</tr>\n";
1924 foreach ($add as $line) { # If any leftovers
1925 echo '<tr>' . $this->emptyLine() .
1926 $this->addedLine( $line ) . "</tr>\n";
1928 wfProfileOut( $fname );