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 __construct( $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 wfProfileIn( __METHOD__
);
79 # If external diffs are enabled both globally and for the user,
80 # we'll use the application/x-external-editor interface to call
81 # an external diff tool like kompare, kdiff3, etc.
82 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
83 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
85 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
86 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
87 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
88 $special=$wgLang->getNsText(NS_SPECIAL
);
93 Script={$wgServer}{$wgScript}
94 Special namespace={$special}
108 $wgOut->setArticleFlag( false );
109 if ( ! $this->loadRevisionData() ) {
110 $t = $this->mTitle
->getPrefixedText() . ' ' . wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
111 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
112 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
113 wfProfileOut( __METHOD__
);
117 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
119 if ( $this->mNewRev
->isCurrent() ) {
120 $wgOut->setArticleFlag( true );
123 # mOldid is false if the difference engine is called with a "vague" query for
124 # a diff between a version V and its previous version V' AND the version V
125 # is the first version of that article. In that case, V' does not exist.
126 if ( $this->mOldid
=== false ) {
127 $this->showFirstRevision();
128 $this->renderNewRevision(); // should we respect $diffOnly here or not?
129 wfProfileOut( __METHOD__
);
133 $wgOut->suppressQuickbar();
135 $oldTitle = $this->mOldPage
->getPrefixedText();
136 $newTitle = $this->mNewPage
->getPrefixedText();
137 if( $oldTitle == $newTitle ) {
138 $wgOut->setPageTitle( $newTitle );
140 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
142 $wgOut->setSubtitle( wfMsg( 'difference' ) );
143 $wgOut->setRobotpolicy( 'noindex,nofollow' );
145 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
146 $wgOut->loginToUse();
148 wfProfileOut( __METHOD__
);
152 $sk = $wgUser->getSkin();
154 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
155 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
160 // Prepare a change patrol link, if applicable
161 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
162 // If we've been given an explicit change identifier, use it; saves time
163 if( $this->mRcidMarkPatrolled
) {
164 $rcid = $this->mRcidMarkPatrolled
;
166 // Look for an unpatrolled change corresponding to this diff
167 $db = wfGetDB( DB_SLAVE
);
168 $change = RecentChange
::newFromConds(
170 // Add redundant user,timestamp condition so we can use the existing index
171 'rc_user_text' => $this->mNewRev
->getRawUserText(),
172 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
173 'rc_this_oldid' => $this->mNewid
,
174 'rc_last_oldid' => $this->mOldid
,
179 if( $change instanceof RecentChange
) {
180 $rcid = $change->mAttribs
['rc_id'];
188 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
190 wfMsgHtml( 'markaspatrolleddiff' ),
191 "action=markpatrolled&rcid={$rcid}"
200 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
201 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
202 if ( $this->mNewRev
->isCurrent() ) {
203 $nextlink = ' ';
205 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
206 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
212 if ($this->mOldRev
->mMinorEdit
== 1) {
213 $oldminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
216 if ($this->mNewRev
->mMinorEdit
== 1) {
217 $newminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
220 $rdel = ''; $ldel = '';
221 if( $wgUser->isAllowed( 'deleterevision' ) ) {
222 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
223 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
224 // If revision was hidden from sysops
225 $ldel = wfMsgHtml('rev-delundel');
227 $ldel = $sk->makeKnownLinkObj( $revdel,
228 wfMsgHtml('rev-delundel'),
229 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
230 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
231 // Bolden oversighted content
232 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
233 $ldel = "<strong>$ldel</strong>";
235 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
236 // We don't currently handle well changing the top revision's settings
237 if( $this->mNewRev
->isCurrent() ) {
238 // If revision was hidden from sysops
239 $rdel = wfMsgHtml('rev-delundel');
240 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
241 // If revision was hidden from sysops
242 $rdel = wfMsgHtml('rev-delundel');
244 $rdel = $sk->makeKnownLinkObj( $revdel,
245 wfMsgHtml('rev-delundel'),
246 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
247 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
248 // Bolden oversighted content
249 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
250 $rdel = "<strong>$rdel</strong>";
252 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
255 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
256 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
257 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
258 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
259 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
260 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
261 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
262 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
264 $this->showDiff( $oldHeader, $newHeader );
267 $this->renderNewRevision();
269 wfProfileOut( __METHOD__
);
273 * Show the new revision of the page.
275 function renderNewRevision() {
277 wfProfileIn( __METHOD__
);
279 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
280 #add deleted rev tag if needed
281 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
282 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
283 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
284 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
287 if( !$this->mNewRev
->isCurrent() ) {
288 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
291 $this->loadNewText();
292 if( is_object( $this->mNewRev
) ) {
293 $wgOut->setRevisionId( $this->mNewRev
->getId() );
296 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
297 // Stolen from Article::view --AG 2007-10-11
299 // Give hooks a chance to customise the output
300 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
301 // Wrap the whole lot in a <pre> and don't parse
303 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
304 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
305 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
306 $wgOut->addHtml( "\n</pre>\n" );
309 $wgOut->addWikiTextTidy( $this->mNewtext
);
311 if( !$this->mNewRev
->isCurrent() ) {
312 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
315 wfProfileOut( __METHOD__
);
319 * Show the first revision of an article. Uses normal diff headers in
320 * contrast to normal "old revision" display style.
322 function showFirstRevision() {
323 global $wgOut, $wgUser;
324 wfProfileIn( __METHOD__
);
326 # Get article text from the DB
328 if ( ! $this->loadNewText() ) {
329 $t = $this->mTitle
->getPrefixedText() . ' ' . wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
330 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
331 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
332 wfProfileOut( __METHOD__
);
335 if ( $this->mNewRev
->isCurrent() ) {
336 $wgOut->setArticleFlag( true );
339 # Check if user is allowed to look at this page. If not, bail out.
341 if ( !( $this->mTitle
->userCanRead() ) ) {
342 $wgOut->loginToUse();
344 wfProfileOut( __METHOD__
);
348 # Prepare the header box
350 $sk = $wgUser->getSkin();
352 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
353 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
354 $sk->revUserTools( $this->mNewRev
) . "<br />" .
355 $sk->revComment( $this->mNewRev
) . "<br />" .
356 $nextlink . "</div>\n";
358 $wgOut->addHTML( $header );
360 $wgOut->setSubtitle( wfMsg( 'difference' ) );
361 $wgOut->setRobotpolicy( 'noindex,nofollow' );
363 wfProfileOut( __METHOD__
);
367 * Get the diff text, send it to $wgOut
368 * Returns false if the diff could not be generated, otherwise returns true
370 function showDiff( $otitle, $ntitle ) {
372 $diff = $this->getDiff( $otitle, $ntitle );
373 if ( $diff === false ) {
374 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" );
377 $this->showDiffStyle();
378 $wgOut->addHTML( $diff );
384 * Add style sheets and supporting JS for diff display.
386 function showDiffStyle() {
387 global $wgStylePath, $wgStyleVersion, $wgOut;
388 $wgOut->addStyle( 'common/diff.css' );
390 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
391 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
395 * Get complete diff table, including header
397 * @param Title $otitle Old title
398 * @param Title $ntitle New title
401 function getDiff( $otitle, $ntitle ) {
402 $body = $this->getDiffBody();
403 if ( $body === false ) {
406 $multi = $this->getMultiNotice();
407 return $this->addHeader( $body, $otitle, $ntitle, $multi );
412 * Get the diff table body, without header
416 function getDiffBody() {
418 wfProfileIn( __METHOD__
);
419 // Check if the diff should be hidden from this user
420 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
422 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
427 if ( $this->mOldid
&& $this->mNewid
) {
428 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
430 if ( !$this->mRefreshCache
) {
431 $difftext = $wgMemc->get( $key );
433 wfIncrStats( 'diff_cache_hit' );
434 $difftext = $this->localiseLineNumbers( $difftext );
435 $difftext .= "\n<!-- diff cache key $key -->\n";
436 wfProfileOut( __METHOD__
);
439 } // don't try to load but save the result
442 // Loadtext is permission safe, this just clears out the diff
443 if ( !$this->loadText() ) {
444 wfProfileOut( __METHOD__
);
448 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
450 // Save to cache for 7 days
451 if ( $key !== false && $difftext !== false ) {
452 wfIncrStats( 'diff_cache_miss' );
453 $wgMemc->set( $key, $difftext, 7*86400 );
455 wfIncrStats( 'diff_uncacheable' );
457 // Replace line numbers with the text in the user's language
458 if ( $difftext !== false ) {
459 $difftext = $this->localiseLineNumbers( $difftext );
461 wfProfileOut( __METHOD__
);
466 * Generate a diff, no caching
467 * $otext and $ntext must be already segmented
469 function generateDiffBody( $otext, $ntext ) {
470 global $wgExternalDiffEngine, $wgContLang;
472 $otext = str_replace( "\r\n", "\n", $otext );
473 $ntext = str_replace( "\r\n", "\n", $ntext );
475 if ( $wgExternalDiffEngine == 'wikidiff' ) {
476 # For historical reasons, external diff engine expects
477 # input text to be HTML-escaped already
478 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
479 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
480 if( !function_exists( 'wikidiff_do_diff' ) ) {
481 dl('php_wikidiff.so');
483 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
484 $this->debug( 'wikidiff1' );
487 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
488 # Better external diff engine, the 2 may some day be dropped
489 # This one does the escaping and segmenting itself
490 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
491 wfProfileIn( __METHOD__
. "-dl" );
492 @dl
('php_wikidiff2.so');
493 wfProfileOut( __METHOD__
. "-dl" );
495 if ( function_exists( 'wikidiff2_do_diff' ) ) {
496 wfProfileIn( 'wikidiff2_do_diff' );
497 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
498 $text .= $this->debug( 'wikidiff2' );
499 wfProfileOut( 'wikidiff2_do_diff' );
503 if ( $wgExternalDiffEngine !== false ) {
505 global $wgTmpDirectory;
506 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
507 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
509 $tempFile1 = fopen( $tempName1, "w" );
511 wfProfileOut( __METHOD__
);
514 $tempFile2 = fopen( $tempName2, "w" );
516 wfProfileOut( __METHOD__
);
519 fwrite( $tempFile1, $otext );
520 fwrite( $tempFile2, $ntext );
521 fclose( $tempFile1 );
522 fclose( $tempFile2 );
523 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
524 wfProfileIn( __METHOD__
. "-shellexec" );
525 $difftext = wfShellExec( $cmd );
526 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
527 wfProfileOut( __METHOD__
. "-shellexec" );
528 unlink( $tempName1 );
529 unlink( $tempName2 );
534 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
535 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
536 $diffs = new Diff( $ota, $nta );
537 $formatter = new TableDiffFormatter();
538 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
543 * Generate a debug comment indicating diff generating time,
544 * server node, and generator backend.
546 protected function debug( $generator="internal" ) {
547 global $wgShowHostnames, $wgNodeName;
548 $data = array( $generator );
549 if( $wgShowHostnames ) {
550 $data[] = $wgNodeName;
552 $data[] = wfTimestamp( TS_DB
);
553 return "<!-- diff generator: " .
562 * Replace line numbers with the text in the user's language
564 function localiseLineNumbers( $text ) {
565 return preg_replace_callback( '/<!--LINE (\d+)-->/',
566 array( &$this, 'localiseLineNumbersCb' ), $text );
569 function localiseLineNumbersCb( $matches ) {
571 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
576 * If there are revisions between the ones being compared, return a note saying so.
578 function getMultiNotice() {
579 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
582 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
583 // Comparing two different pages? Count would be meaningless.
587 $oldid = $this->mOldRev
->getId();
588 $newid = $this->mNewRev
->getId();
589 if ( $oldid > $newid ) {
590 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
593 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
597 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
602 * Add the header to a diff body
604 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
609 <col class='diff-marker' />
610 <col class='diff-content' />
611 <col class='diff-marker' />
612 <col class='diff-content' />
614 <td colspan='2' class='diff-otitle'>{$otitle}</td>
615 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
620 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
622 return $header . $diff . "</table>";
626 * Use specified text instead of loading from the database
628 function setText( $oldText, $newText ) {
629 $this->mOldtext
= $oldText;
630 $this->mNewtext
= $newText;
631 $this->mTextLoaded
= 2;
635 * Load revision metadata for the specified articles. If newid is 0, then compare
636 * the old article in oldid to the current article; if oldid is 0, then
637 * compare the current article to the immediately previous one (ignoring the
640 * If oldid is false, leave the corresponding revision object set
641 * to false. This is impossible via ordinary user input, and is provided for
644 function loadRevisionData() {
646 if ( $this->mRevisionsLoaded
) {
649 // Whether it succeeds or fails, we don't want to try again
650 $this->mRevisionsLoaded
= true;
653 // Load the new revision object
654 $this->mNewRev
= $this->mNewid
655 ? Revision
::newFromId( $this->mNewid
)
656 : Revision
::newFromTitle( $this->mTitle
);
657 if( !$this->mNewRev
instanceof Revision
)
660 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
661 $this->mNewid
= $this->mNewRev
->getId();
663 // Check if page is editable
664 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
666 // Set assorted variables
667 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
668 $this->mNewPage
= $this->mNewRev
->getTitle();
669 if( $this->mNewRev
->isCurrent() ) {
670 $newLink = $this->mNewPage
->escapeLocalUrl();
671 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
672 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
674 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
675 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
678 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
679 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
680 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
682 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
683 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
685 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
686 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
687 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
688 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
691 // Load the old revision object
692 $this->mOldRev
= false;
693 if( $this->mOldid
) {
694 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
695 } elseif ( $this->mOldid
=== 0 ) {
696 $rev = $this->mNewRev
->getPrevious();
698 $this->mOldid
= $rev->getId();
699 $this->mOldRev
= $rev;
701 // No previous revision; mark to show as first-version only.
702 $this->mOldid
= false;
703 $this->mOldRev
= false;
705 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
707 if( is_null( $this->mOldRev
) ) {
711 if ( $this->mOldRev
) {
712 $this->mOldPage
= $this->mOldRev
->getTitle();
714 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
715 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
716 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
717 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
719 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
720 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
721 // Add an "undo" link
722 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
723 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
724 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
727 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
728 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
729 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
730 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
738 * Load the text of the revisions, as well as revision data.
740 function loadText() {
741 if ( $this->mTextLoaded
== 2 ) {
744 // Whether it succeeds or fails, we don't want to try again
745 $this->mTextLoaded
= 2;
748 if ( !$this->loadRevisionData() ) {
751 if ( $this->mOldRev
) {
752 $this->mOldtext
= $this->mOldRev
->revText();
753 if ( $this->mOldtext
=== false ) {
757 if ( $this->mNewRev
) {
758 $this->mNewtext
= $this->mNewRev
->revText();
759 if ( $this->mNewtext
=== false ) {
767 * Load the text of the new revision, not the old one
769 function loadNewText() {
770 if ( $this->mTextLoaded
>= 1 ) {
773 $this->mTextLoaded
= 1;
775 if ( !$this->loadRevisionData() ) {
778 $this->mNewtext
= $this->mNewRev
->getText();
785 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
787 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
788 // You may copy this code freely under the conditions of the GPL.
791 define('USE_ASSERTS', function_exists('assert'));
796 * @addtogroup DifferenceEngine
804 trigger_error('pure virtual', E_USER_ERROR
);
808 return $this->orig ?
sizeof($this->orig
) : 0;
811 function nclosing() {
812 return $this->closing ?
sizeof($this->closing
) : 0;
819 * @addtogroup DifferenceEngine
821 class _DiffOp_Copy
extends _DiffOp
{
824 function _DiffOp_Copy ($orig, $closing = false) {
825 if (!is_array($closing))
828 $this->closing
= $closing;
832 return new _DiffOp_Copy($this->closing
, $this->orig
);
839 * @addtogroup DifferenceEngine
841 class _DiffOp_Delete
extends _DiffOp
{
842 var $type = 'delete';
844 function _DiffOp_Delete ($lines) {
845 $this->orig
= $lines;
846 $this->closing
= false;
850 return new _DiffOp_Add($this->orig
);
857 * @addtogroup DifferenceEngine
859 class _DiffOp_Add
extends _DiffOp
{
862 function _DiffOp_Add ($lines) {
863 $this->closing
= $lines;
868 return new _DiffOp_Delete($this->closing
);
875 * @addtogroup DifferenceEngine
877 class _DiffOp_Change
extends _DiffOp
{
878 var $type = 'change';
880 function _DiffOp_Change ($orig, $closing) {
882 $this->closing
= $closing;
886 return new _DiffOp_Change($this->closing
, $this->orig
);
892 * Class used internally by Diff to actually compute the diffs.
894 * The algorithm used here is mostly lifted from the perl module
895 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
896 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
898 * More ideas are taken from:
899 * http://www.ics.uci.edu/~eppstein/161/960229.html
901 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
902 * diffutils-2.7, which can be found at:
903 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
905 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
908 * Line length limits for robustness added by Tim Starling, 2005-08-31
910 * @author Geoffrey T. Dairiki, Tim Starling
912 * @addtogroup DifferenceEngine
915 const MAX_XREF_LENGTH
= 10000;
917 function diff ($from_lines, $to_lines) {
918 wfProfileIn( __METHOD__
);
920 $n_from = sizeof($from_lines);
921 $n_to = sizeof($to_lines);
923 $this->xchanged
= $this->ychanged
= array();
924 $this->xv
= $this->yv
= array();
925 $this->xind
= $this->yind
= array();
927 unset($this->in_seq
);
930 // Skip leading common lines.
931 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
932 if ($from_lines[$skip] !== $to_lines[$skip])
934 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
936 // Skip trailing common lines.
937 $xi = $n_from; $yi = $n_to;
938 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
939 if ($from_lines[$xi] !== $to_lines[$yi])
941 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
944 // Ignore lines which do not exist in both files.
945 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
946 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
949 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
950 $line = $to_lines[$yi];
951 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
953 $yhash[$this->_line_hash($line)] = 1;
957 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
958 $line = $from_lines[$xi];
959 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
966 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
968 // Merge edits when possible
969 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
970 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
972 // Compute the edit operations.
975 while ($xi < $n_from ||
$yi < $n_to) {
976 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
977 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
979 // Skip matching "snake".
981 while ( $xi < $n_from && $yi < $n_to
982 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
983 $copy[] = $from_lines[$xi++
];
987 $edits[] = new _DiffOp_Copy($copy);
989 // Find deletes & adds.
991 while ($xi < $n_from && $this->xchanged
[$xi])
992 $delete[] = $from_lines[$xi++
];
995 while ($yi < $n_to && $this->ychanged
[$yi])
996 $add[] = $to_lines[$yi++
];
999 $edits[] = new _DiffOp_Change($delete, $add);
1001 $edits[] = new _DiffOp_Delete($delete);
1003 $edits[] = new _DiffOp_Add($add);
1005 wfProfileOut( __METHOD__
);
1010 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1012 function _line_hash( $line ) {
1013 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1014 return md5( $line );
1021 /* Divide the Largest Common Subsequence (LCS) of the sequences
1022 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1025 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1026 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1027 * sub sequences. The first sub-sequence is contained in [X0, X1),
1028 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1029 * that (X0, Y0) == (XOFF, YOFF) and
1030 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1032 * This function assumes that the first lines of the specified portions
1033 * of the two files do not match, and likewise that the last lines do not
1034 * match. The caller must trim matching lines from the beginning and end
1035 * of the portions it is going to specify.
1037 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1038 wfProfileIn( __METHOD__
);
1041 if ($xlim - $xoff > $ylim - $yoff) {
1042 // Things seems faster (I'm not sure I understand why)
1043 // when the shortest sequence in X.
1045 list ($xoff, $xlim, $yoff, $ylim)
1046 = array( $yoff, $ylim, $xoff, $xlim);
1050 for ($i = $ylim - 1; $i >= $yoff; $i--)
1051 $ymatches[$this->xv
[$i]][] = $i;
1053 for ($i = $ylim - 1; $i >= $yoff; $i--)
1054 $ymatches[$this->yv
[$i]][] = $i;
1057 $this->seq
[0]= $yoff - 1;
1058 $this->in_seq
= array();
1059 $ymids[0] = array();
1061 $numer = $xlim - $xoff +
$nchunks - 1;
1063 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1064 wfProfileIn( __METHOD__
. "-chunk" );
1066 for ($i = 0; $i <= $this->lcs
; $i++
)
1067 $ymids[$i][$chunk-1] = $this->seq
[$i];
1069 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1070 for ( ; $x < $x1; $x++
) {
1071 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1072 if (empty($ymatches[$line]))
1074 $matches = $ymatches[$line];
1076 while (list ($junk, $y) = each($matches))
1077 if (empty($this->in_seq
[$y])) {
1078 $k = $this->_lcs_pos($y);
1079 USE_ASSERTS
&& assert($k > 0);
1080 $ymids[$k] = $ymids[$k-1];
1083 while (list ( /* $junk */, $y) = each($matches)) {
1084 if ($y > $this->seq
[$k-1]) {
1085 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1086 // Optimization: this is a common case:
1087 // next match is just replacing previous match.
1088 $this->in_seq
[$this->seq
[$k]] = false;
1089 $this->seq
[$k] = $y;
1090 $this->in_seq
[$y] = 1;
1091 } else if (empty($this->in_seq
[$y])) {
1092 $k = $this->_lcs_pos($y);
1093 USE_ASSERTS
&& assert($k > 0);
1094 $ymids[$k] = $ymids[$k-1];
1098 wfProfileOut( __METHOD__
. "-chunk" );
1101 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1102 $ymid = $ymids[$this->lcs
];
1103 for ($n = 0; $n < $nchunks - 1; $n++
) {
1104 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1105 $y1 = $ymid[$n] +
1;
1106 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1108 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1110 wfProfileOut( __METHOD__
);
1111 return array($this->lcs
, $seps);
1114 function _lcs_pos ($ypos) {
1115 wfProfileIn( __METHOD__
);
1118 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1119 $this->seq
[++
$this->lcs
] = $ypos;
1120 $this->in_seq
[$ypos] = 1;
1121 wfProfileOut( __METHOD__
);
1126 while ($beg < $end) {
1127 $mid = (int)(($beg +
$end) / 2);
1128 if ( $ypos > $this->seq
[$mid] )
1134 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1136 $this->in_seq
[$this->seq
[$end]] = false;
1137 $this->seq
[$end] = $ypos;
1138 $this->in_seq
[$ypos] = 1;
1139 wfProfileOut( __METHOD__
);
1143 /* Find LCS of two sequences.
1145 * The results are recorded in the vectors $this->{x,y}changed[], by
1146 * storing a 1 in the element for each line that is an insertion
1147 * or deletion (ie. is not in the LCS).
1149 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1151 * Note that XLIM, YLIM are exclusive bounds.
1152 * All line numbers are origin-0 and discarded lines are not counted.
1154 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1155 wfProfileIn( __METHOD__
);
1157 // Slide down the bottom initial diagonal.
1158 while ($xoff < $xlim && $yoff < $ylim
1159 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1164 // Slide up the top initial diagonal.
1165 while ($xlim > $xoff && $ylim > $yoff
1166 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1171 if ($xoff == $xlim ||
$yoff == $ylim)
1174 // This is ad hoc but seems to work well.
1175 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1176 //$nchunks = max(2,min(8,(int)$nchunks));
1177 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1179 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1183 // X and Y sequences have no common subsequence:
1184 // mark all changed.
1185 while ($yoff < $ylim)
1186 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1187 while ($xoff < $xlim)
1188 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1190 // Use the partitions to split this problem into subproblems.
1193 while ($pt2 = next($seps)) {
1194 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1198 wfProfileOut( __METHOD__
);
1201 /* Adjust inserts/deletes of identical lines to join changes
1202 * as much as possible.
1204 * We do something when a run of changed lines include a
1205 * line at one end and has an excluded, identical line at the other.
1206 * We are free to choose which identical line is included.
1207 * `compareseq' usually chooses the one at the beginning,
1208 * but usually it is cleaner to consider the following identical line
1209 * to be the "change".
1211 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1213 function _shift_boundaries ($lines, &$changed, $other_changed) {
1214 wfProfileIn( __METHOD__
);
1218 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1219 $len = sizeof($lines);
1220 $other_len = sizeof($other_changed);
1224 * Scan forwards to find beginning of another run of changes.
1225 * Also keep track of the corresponding point in the other file.
1227 * Throughout this code, $i and $j are adjusted together so that
1228 * the first $i elements of $changed and the first $j elements
1229 * of $other_changed both contain the same number of zeros
1230 * (unchanged lines).
1231 * Furthermore, $j is always kept so that $j == $other_len or
1232 * $other_changed[$j] == false.
1234 while ($j < $other_len && $other_changed[$j])
1237 while ($i < $len && ! $changed[$i]) {
1238 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1240 while ($j < $other_len && $other_changed[$j])
1249 // Find the end of this run of changes.
1250 while (++
$i < $len && $changed[$i])
1255 * Record the length of this run of changes, so that
1256 * we can later determine whether the run has grown.
1258 $runlength = $i - $start;
1261 * Move the changed region back, so long as the
1262 * previous unchanged line matches the last changed one.
1263 * This merges with previous changed regions.
1265 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1266 $changed[--$start] = 1;
1267 $changed[--$i] = false;
1268 while ($start > 0 && $changed[$start - 1])
1270 USE_ASSERTS
&& assert('$j > 0');
1271 while ($other_changed[--$j])
1273 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1277 * Set CORRESPONDING to the end of the changed run, at the last
1278 * point where it corresponds to a changed run in the other file.
1279 * CORRESPONDING == LEN means no such point has been found.
1281 $corresponding = $j < $other_len ?
$i : $len;
1284 * Move the changed region forward, so long as the
1285 * first changed line matches the following unchanged one.
1286 * This merges with following changed regions.
1287 * Do this second, so that if there are no merges,
1288 * the changed region is moved forward as far as possible.
1290 while ($i < $len && $lines[$start] == $lines[$i]) {
1291 $changed[$start++
] = false;
1293 while ($i < $len && $changed[$i])
1296 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1298 if ($j < $other_len && $other_changed[$j]) {
1299 $corresponding = $i;
1300 while ($j < $other_len && $other_changed[$j])
1304 } while ($runlength != $i - $start);
1307 * If possible, move the fully-merged run of changes
1308 * back to a corresponding run in the other file.
1310 while ($corresponding < $i) {
1311 $changed[--$start] = 1;
1313 USE_ASSERTS
&& assert('$j > 0');
1314 while ($other_changed[--$j])
1316 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1319 wfProfileOut( __METHOD__
);
1324 * Class representing a 'diff' between two sequences of strings.
1327 * @addtogroup DifferenceEngine
1335 * Computes diff between sequences of strings.
1337 * @param $from_lines array An array of strings.
1338 * (Typically these are lines from a file.)
1339 * @param $to_lines array An array of strings.
1341 function Diff($from_lines, $to_lines) {
1342 $eng = new _DiffEngine
;
1343 $this->edits
= $eng->diff($from_lines, $to_lines);
1344 //$this->_check($from_lines, $to_lines);
1348 * Compute reversed Diff.
1352 * $diff = new Diff($lines1, $lines2);
1353 * $rev = $diff->reverse();
1354 * @return object A Diff object representing the inverse of the
1357 function reverse () {
1359 $rev->edits
= array();
1360 foreach ($this->edits
as $edit) {
1361 $rev->edits
[] = $edit->reverse();
1367 * Check for empty diff.
1369 * @return bool True iff two sequences were identical.
1371 function isEmpty () {
1372 foreach ($this->edits
as $edit) {
1373 if ($edit->type
!= 'copy')
1380 * Compute the length of the Longest Common Subsequence (LCS).
1382 * This is mostly for diagnostic purposed.
1384 * @return int The length of the LCS.
1388 foreach ($this->edits
as $edit) {
1389 if ($edit->type
== 'copy')
1390 $lcs +
= sizeof($edit->orig
);
1396 * Get the original set of lines.
1398 * This reconstructs the $from_lines parameter passed to the
1401 * @return array The original sequence of strings.
1406 foreach ($this->edits
as $edit) {
1408 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1414 * Get the closing set of lines.
1416 * This reconstructs the $to_lines parameter passed to the
1419 * @return array The sequence of strings.
1421 function closing() {
1424 foreach ($this->edits
as $edit) {
1426 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1432 * Check a Diff for validity.
1434 * This is here only for debugging purposes.
1436 function _check ($from_lines, $to_lines) {
1437 wfProfileIn( __METHOD__
);
1438 if (serialize($from_lines) != serialize($this->orig()))
1439 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1440 if (serialize($to_lines) != serialize($this->closing()))
1441 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1443 $rev = $this->reverse();
1444 if (serialize($to_lines) != serialize($rev->orig()))
1445 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1446 if (serialize($from_lines) != serialize($rev->closing()))
1447 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1451 foreach ($this->edits
as $edit) {
1452 if ( $prevtype == $edit->type
)
1453 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1454 $prevtype = $edit->type
;
1457 $lcs = $this->lcs();
1458 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1459 wfProfileOut( __METHOD__
);
1464 * @todo document, bad name.
1466 * @addtogroup DifferenceEngine
1468 class MappedDiff
extends Diff
1473 * Computes diff between sequences of strings.
1475 * This can be used to compute things like
1476 * case-insensitve diffs, or diffs which ignore
1477 * changes in white-space.
1479 * @param $from_lines array An array of strings.
1480 * (Typically these are lines from a file.)
1482 * @param $to_lines array An array of strings.
1484 * @param $mapped_from_lines array This array should
1485 * have the same size number of elements as $from_lines.
1486 * The elements in $mapped_from_lines and
1487 * $mapped_to_lines are what is actually compared
1488 * when computing the diff.
1490 * @param $mapped_to_lines array This array should
1491 * have the same number of elements as $to_lines.
1493 function MappedDiff($from_lines, $to_lines,
1494 $mapped_from_lines, $mapped_to_lines) {
1495 wfProfileIn( __METHOD__
);
1497 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1498 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1500 $this->Diff($mapped_from_lines, $mapped_to_lines);
1503 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1504 $orig = &$this->edits
[$i]->orig
;
1505 if (is_array($orig)) {
1506 $orig = array_slice($from_lines, $xi, sizeof($orig));
1507 $xi +
= sizeof($orig);
1510 $closing = &$this->edits
[$i]->closing
;
1511 if (is_array($closing)) {
1512 $closing = array_slice($to_lines, $yi, sizeof($closing));
1513 $yi +
= sizeof($closing);
1516 wfProfileOut( __METHOD__
);
1521 * A class to format Diffs
1523 * This class formats the diff in classic diff format.
1524 * It is intended that this class be customized via inheritance,
1525 * to obtain fancier outputs.
1528 * @addtogroup DifferenceEngine
1530 class DiffFormatter
{
1532 * Number of leading 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 $leading_context_lines = 0;
1540 * Number of trailing context "lines" to preserve.
1542 * This should be left at zero for this class, but subclasses
1543 * may want to set this to other values.
1545 var $trailing_context_lines = 0;
1550 * @param $diff object A Diff object.
1551 * @return string The formatted output.
1553 function format($diff) {
1554 wfProfileIn( __METHOD__
);
1560 $nlead = $this->leading_context_lines
;
1561 $ntrail = $this->trailing_context_lines
;
1563 $this->_start_diff();
1565 foreach ($diff->edits
as $edit) {
1566 if ($edit->type
== 'copy') {
1567 if (is_array($block)) {
1568 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1573 $context = array_slice($edit->orig
, 0, $ntrail);
1574 $block[] = new _DiffOp_Copy($context);
1576 $this->_block($x0, $ntrail +
$xi - $x0,
1577 $y0, $ntrail +
$yi - $y0,
1582 $context = $edit->orig
;
1585 if (! is_array($block)) {
1586 $context = array_slice($context, sizeof($context) - $nlead);
1587 $x0 = $xi - sizeof($context);
1588 $y0 = $yi - sizeof($context);
1591 $block[] = new _DiffOp_Copy($context);
1597 $xi +
= sizeof($edit->orig
);
1599 $yi +
= sizeof($edit->closing
);
1602 if (is_array($block))
1603 $this->_block($x0, $xi - $x0,
1607 $end = $this->_end_diff();
1608 wfProfileOut( __METHOD__
);
1612 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1613 wfProfileIn( __METHOD__
);
1614 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1615 foreach ($edits as $edit) {
1616 if ($edit->type
== 'copy')
1617 $this->_context($edit->orig
);
1618 elseif ($edit->type
== 'add')
1619 $this->_added($edit->closing
);
1620 elseif ($edit->type
== 'delete')
1621 $this->_deleted($edit->orig
);
1622 elseif ($edit->type
== 'change')
1623 $this->_changed($edit->orig
, $edit->closing
);
1625 trigger_error('Unknown edit type', E_USER_ERROR
);
1627 $this->_end_block();
1628 wfProfileOut( __METHOD__
);
1631 function _start_diff() {
1635 function _end_diff() {
1636 $val = ob_get_contents();
1641 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1643 $xbeg .= "," . ($xbeg +
$xlen - 1);
1645 $ybeg .= "," . ($ybeg +
$ylen - 1);
1647 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1650 function _start_block($header) {
1651 echo $header . "\n";
1654 function _end_block() {
1657 function _lines($lines, $prefix = ' ') {
1658 foreach ($lines as $line)
1659 echo "$prefix $line\n";
1662 function _context($lines) {
1663 $this->_lines($lines);
1666 function _added($lines) {
1667 $this->_lines($lines, '>');
1669 function _deleted($lines) {
1670 $this->_lines($lines, '<');
1673 function _changed($orig, $closing) {
1674 $this->_deleted($orig);
1676 $this->_added($closing);
1681 * A formatter that outputs unified diffs
1682 * @addtogroup DifferenceEngine
1685 class UnifiedDiffFormatter
extends DiffFormatter
{
1686 var $leading_context_lines = 2;
1687 var $trailing_context_lines = 2;
1689 function _added($lines) {
1690 $this->_lines($lines, '+');
1692 function _deleted($lines) {
1693 $this->_lines($lines, '-');
1695 function _changed($orig, $closing) {
1696 $this->_deleted($orig);
1697 $this->_added($closing);
1699 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1700 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1705 * A pseudo-formatter that just passes along the Diff::$edits array
1706 * @addtogroup DifferenceEngine
1708 class ArrayDiffFormatter
extends DiffFormatter
{
1709 function format($diff) {
1713 foreach($diff->edits
as $edit)
1714 switch($edit->type
) {
1716 foreach($edit->closing
as $l) {
1720 'newline' => $newline++
1725 foreach($edit->orig
as $l) {
1727 'action' => 'delete',
1729 'oldline' => $oldline++
,
1734 foreach($edit->orig
as $i => $l) {
1736 'action' => 'change',
1738 'new' => @$edit->closing
[$i],
1739 'oldline' => $oldline++
,
1740 'newline' => $newline++
,
1745 $oldline +
= count($edit->orig
);
1746 $newline +
= count($edit->orig
);
1753 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1757 define('NBSP', ' '); // iso-8859-x non-breaking space.
1762 * @addtogroup DifferenceEngine
1764 class _HWLDF_WordAccumulator
{
1765 function _HWLDF_WordAccumulator () {
1766 $this->_lines
= array();
1772 function _flushGroup ($new_tag) {
1773 if ($this->_group
!== '') {
1774 if ($this->_tag
== 'ins')
1775 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1776 htmlspecialchars ( $this->_group
) . '</ins>';
1777 elseif ($this->_tag
== 'del')
1778 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1779 htmlspecialchars ( $this->_group
) . '</del>';
1781 $this->_line
.= htmlspecialchars ( $this->_group
);
1784 $this->_tag
= $new_tag;
1787 function _flushLine ($new_tag) {
1788 $this->_flushGroup($new_tag);
1789 if ($this->_line
!= '')
1790 array_push ( $this->_lines
, $this->_line
);
1792 # make empty lines visible by inserting an NBSP
1793 array_push ( $this->_lines
, NBSP
);
1797 function addWords ($words, $tag = '') {
1798 if ($tag != $this->_tag
)
1799 $this->_flushGroup($tag);
1801 foreach ($words as $word) {
1802 // new-line should only come as first char of word.
1805 if ($word[0] == "\n") {
1806 $this->_flushLine($tag);
1807 $word = substr($word, 1);
1809 assert(!strstr($word, "\n"));
1810 $this->_group
.= $word;
1814 function getLines() {
1815 $this->_flushLine('~done');
1816 return $this->_lines
;
1823 * @addtogroup DifferenceEngine
1825 class WordLevelDiff
extends MappedDiff
{
1826 const MAX_LINE_LENGTH
= 10000;
1828 function WordLevelDiff ($orig_lines, $closing_lines) {
1829 wfProfileIn( __METHOD__
);
1831 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1832 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1834 $this->MappedDiff($orig_words, $closing_words,
1835 $orig_stripped, $closing_stripped);
1836 wfProfileOut( __METHOD__
);
1839 function _split($lines) {
1840 wfProfileIn( __METHOD__
);
1843 $stripped = array();
1845 foreach ( $lines as $line ) {
1846 # If the line is too long, just pretend the entire line is one big word
1847 # This prevents resource exhaustion problems
1854 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1856 $stripped[] = $line;
1859 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1862 $words = array_merge( $words, $m[0] );
1863 $stripped = array_merge( $stripped, $m[1] );
1867 wfProfileOut( __METHOD__
);
1868 return array($words, $stripped);
1872 wfProfileIn( __METHOD__
);
1873 $orig = new _HWLDF_WordAccumulator
;
1875 foreach ($this->edits
as $edit) {
1876 if ($edit->type
== 'copy')
1877 $orig->addWords($edit->orig
);
1878 elseif ($edit->orig
)
1879 $orig->addWords($edit->orig
, 'del');
1881 $lines = $orig->getLines();
1882 wfProfileOut( __METHOD__
);
1886 function closing () {
1887 wfProfileIn( __METHOD__
);
1888 $closing = new _HWLDF_WordAccumulator
;
1890 foreach ($this->edits
as $edit) {
1891 if ($edit->type
== 'copy')
1892 $closing->addWords($edit->closing
);
1893 elseif ($edit->closing
)
1894 $closing->addWords($edit->closing
, 'ins');
1896 $lines = $closing->getLines();
1897 wfProfileOut( __METHOD__
);
1903 * Wikipedia Table style diff formatter.
1906 * @addtogroup DifferenceEngine
1908 class TableDiffFormatter
extends DiffFormatter
{
1909 function TableDiffFormatter() {
1910 $this->leading_context_lines
= 2;
1911 $this->trailing_context_lines
= 2;
1914 public static function escapeWhiteSpace( $msg ) {
1915 $msg = preg_replace( '/^ /m', ' ', $msg );
1916 $msg = preg_replace( '/ $/m', ' ', $msg );
1917 $msg = preg_replace( '/ /', ' ', $msg );
1921 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1922 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1923 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1927 function _start_block( $header ) {
1931 function _end_block() {
1934 function _lines( $lines, $prefix=' ', $color='white' ) {
1937 # HTML-escape parameter before calling this
1938 function addedLine( $line ) {
1939 return $this->wrapLine( '+', 'diff-addedline', $line );
1942 # HTML-escape parameter before calling this
1943 function deletedLine( $line ) {
1944 return $this->wrapLine( '-', 'diff-deletedline', $line );
1947 # HTML-escape parameter before calling this
1948 function contextLine( $line ) {
1949 return $this->wrapLine( ' ', 'diff-context', $line );
1952 private function wrapLine( $marker, $class, $line ) {
1953 if( $line !== '' ) {
1954 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1955 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1957 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1960 function emptyLine() {
1961 return '<td colspan="2"> </td>';
1964 function _added( $lines ) {
1965 foreach ($lines as $line) {
1966 echo '<tr>' . $this->emptyLine() .
1967 $this->addedLine( '<ins class="diffchange">' .
1968 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1972 function _deleted($lines) {
1973 foreach ($lines as $line) {
1974 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1975 htmlspecialchars ( $line ) . '</del>' ) .
1976 $this->emptyLine() . "</tr>\n";
1980 function _context( $lines ) {
1981 foreach ($lines as $line) {
1983 $this->contextLine( htmlspecialchars ( $line ) ) .
1984 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1988 function _changed( $orig, $closing ) {
1989 wfProfileIn( __METHOD__
);
1991 $diff = new WordLevelDiff( $orig, $closing );
1992 $del = $diff->orig();
1993 $add = $diff->closing();
1995 # Notice that WordLevelDiff returns HTML-escaped output.
1996 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1998 while ( $line = array_shift( $del ) ) {
1999 $aline = array_shift( $add );
2000 echo '<tr>' . $this->deletedLine( $line ) .
2001 $this->addedLine( $aline ) . "</tr>\n";
2003 foreach ($add as $line) { # If any leftovers
2004 echo '<tr>' . $this->emptyLine() .
2005 $this->addedLine( $line ) . "</tr>\n";
2007 wfProfileOut( __METHOD__
);