4 * @todo indicate where diff.doc can be found.
5 * @addtogroup DifferenceEngine
11 * @addtogroup DifferenceEngine
13 class DifferenceEngine
{
17 var $mOldid, $mNewid, $mTitle;
18 var $mOldtitle, $mNewtitle, $mPagetitle;
19 var $mOldtext, $mNewtext;
20 var $mOldPage, $mNewPage;
21 var $mRcidMarkPatrolled;
22 var $mOldRev, $mNewRev;
23 var $mRevisionsLoaded = false; // Have the revisions been loaded
24 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
29 * @param $titleObj Title object that the diff is associated with
30 * @param $old Integer: old ID we want to show and diff with.
31 * @param $new String: either 'prev' or 'next'.
32 * @param $rcid Integer: ??? FIXME (default 0)
34 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
35 $this->mTitle
= $titleObj;
36 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
38 if ( 'prev' === $new ) {
39 # Show diff between revision $old and the previous one.
40 # Get previous one from DB.
42 $this->mNewid
= intval($old);
44 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
46 } elseif ( 'next' === $new ) {
47 # Show diff between revision $old and the previous one.
48 # Get previous one from DB.
50 $this->mOldid
= intval($old);
51 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
52 if ( false === $this->mNewid
) {
53 # if no result, NewId points to the newest old revision. The only newer
54 # revision is cur, which is "0".
59 $this->mOldid
= intval($old);
60 $this->mNewid
= intval($new);
62 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
65 function showDiffPage( $diffOnly = false ) {
66 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
67 $fname = 'DifferenceEngine::showDiffPage';
68 wfProfileIn( $fname );
70 # If external diffs are enabled both globally and for the user,
71 # we'll use the application/x-external-editor interface to call
72 # an external diff tool like kompare, kdiff3, etc.
73 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
74 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
76 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
77 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
78 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
79 $special=$wgLang->getNsText(NS_SPECIAL
);
84 Script={$wgServer}{$wgScript}
85 Special namespace={$special}
99 $wgOut->setArticleFlag( false );
100 if ( ! $this->loadRevisionData() ) {
101 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
102 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
103 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
104 $wgOut->addWikitext( $mtext );
105 wfProfileOut( $fname );
109 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
111 if ( $this->mNewRev
->isCurrent() ) {
112 $wgOut->setArticleFlag( true );
115 # mOldid is false if the difference engine is called with a "vague" query for
116 # a diff between a version V and its previous version V' AND the version V
117 # is the first version of that article. In that case, V' does not exist.
118 if ( $this->mOldid
=== false ) {
119 $this->showFirstRevision();
120 $this->renderNewRevision(); // should we respect $diffOnly here or not?
121 wfProfileOut( $fname );
125 $wgOut->suppressQuickbar();
127 $oldTitle = $this->mOldPage
->getPrefixedText();
128 $newTitle = $this->mNewPage
->getPrefixedText();
129 if( $oldTitle == $newTitle ) {
130 $wgOut->setPageTitle( $newTitle );
132 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
134 $wgOut->setSubtitle( wfMsg( 'difference' ) );
135 $wgOut->setRobotpolicy( 'noindex,nofollow' );
137 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
138 $wgOut->loginToUse();
140 wfProfileOut( $fname );
144 $sk = $wgUser->getSkin();
146 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
147 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
151 if( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isAllowed( 'patrol' ) ) {
152 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
157 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
158 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
159 if ( $this->mNewRev
->isCurrent() ) {
160 $nextlink = ' ';
162 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
163 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
169 if ($this->mOldRev
->mMinorEdit
== 1) {
170 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
171 wfMsg( 'minoreditletter') ) . ' ';
174 if ($this->mNewRev
->mMinorEdit
== 1) {
175 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
176 wfMsg( 'minoreditletter') ) . ' ';
179 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />" .
180 $sk->revUserTools( $this->mOldRev
) . "<br />" .
181 $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly ) . "<br />" .
183 $newHeader = "<strong>{$this->mNewtitle}</strong><br />" .
184 $sk->revUserTools( $this->mNewRev
) . " $rollback<br />" .
185 $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly ) . "<br />" .
188 $this->showDiff( $oldHeader, $newHeader );
191 $this->renderNewRevision();
193 wfProfileOut( $fname );
197 * Show the new revision of the page.
199 function renderNewRevision() {
201 $fname = 'DifferenceEngine::renderNewRevision';
202 wfProfileIn( $fname );
204 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
205 #add deleted rev tag if needed
206 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
207 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
210 if( !$this->mNewRev
->isCurrent() ) {
211 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
214 $this->loadNewText();
215 if( is_object( $this->mNewRev
) ) {
216 $wgOut->setRevisionId( $this->mNewRev
->getId() );
219 $wgOut->addWikiTextTidy( $this->mNewtext
);
221 if( !$this->mNewRev
->isCurrent() ) {
222 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
225 wfProfileOut( $fname );
229 * Show the first revision of an article. Uses normal diff headers in
230 * contrast to normal "old revision" display style.
232 function showFirstRevision() {
233 global $wgOut, $wgUser;
235 $fname = 'DifferenceEngine::showFirstRevision';
236 wfProfileIn( $fname );
238 # Get article text from the DB
240 if ( ! $this->loadNewText() ) {
241 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
243 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
244 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
245 $wgOut->addWikitext( $mtext );
246 wfProfileOut( $fname );
249 if ( $this->mNewRev
->isCurrent() ) {
250 $wgOut->setArticleFlag( true );
253 # Check if user is allowed to look at this page. If not, bail out.
255 if ( !( $this->mTitle
->userCanRead() ) ) {
256 $wgOut->loginToUse();
258 wfProfileOut( $fname );
262 # Prepare the header box
264 $sk = $wgUser->getSkin();
266 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
267 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
268 $sk->revUserTools( $this->mNewRev
) . "<br />" .
269 $sk->revComment( $this->mNewRev
) . "<br />" .
270 $nextlink . "</div>\n";
272 $wgOut->addHTML( $header );
274 $wgOut->setSubtitle( wfMsg( 'difference' ) );
275 $wgOut->setRobotpolicy( 'noindex,nofollow' );
277 wfProfileOut( $fname );
281 * Get the diff text, send it to $wgOut
282 * Returns false if the diff could not be generated, otherwise returns true
284 function showDiff( $otitle, $ntitle ) {
286 $diff = $this->getDiff( $otitle, $ntitle );
287 if ( $diff === false ) {
288 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
291 $wgOut->addHTML( $diff );
297 * Get diff table, including header
298 * Note that the interface has changed, it's no longer static.
299 * Returns false on error
301 function getDiff( $otitle, $ntitle ) {
302 $body = $this->getDiffBody();
303 if ( $body === false ) {
306 $multi = $this->getMultiNotice();
307 return $this->addHeader( $body, $otitle, $ntitle, $multi );
312 * Get the diff table body, without header
314 * Returns false on error
316 function getDiffBody() {
318 $fname = 'DifferenceEngine::getDiffBody';
319 wfProfileIn( $fname );
323 if ( $this->mOldid
&& $this->mNewid
) {
325 $key = wfMemcKey( 'diff', 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
326 $difftext = $wgMemc->get( $key );
328 wfIncrStats( 'diff_cache_hit' );
329 $difftext = $this->localiseLineNumbers( $difftext );
330 $difftext .= "\n<!-- diff cache key $key -->\n";
331 wfProfileOut( $fname );
336 #loadtext is permission safe, this just clears out the diff
337 if ( !$this->loadText() ) {
338 wfProfileOut( $fname );
340 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
342 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
346 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
348 // Save to cache for 7 days
349 if ( $key !== false && $difftext !== false ) {
350 wfIncrStats( 'diff_cache_miss' );
351 $wgMemc->set( $key, $difftext, 7*86400 );
353 wfIncrStats( 'diff_uncacheable' );
355 // Replace line numbers with the text in the user's language
356 if ( $difftext !== false ) {
357 $difftext = $this->localiseLineNumbers( $difftext );
359 wfProfileOut( $fname );
364 * Generate a diff, no caching
365 * $otext and $ntext must be already segmented
367 function generateDiffBody( $otext, $ntext ) {
368 global $wgExternalDiffEngine, $wgContLang;
369 $fname = 'DifferenceEngine::generateDiffBody';
371 $otext = str_replace( "\r\n", "\n", $otext );
372 $ntext = str_replace( "\r\n", "\n", $ntext );
374 if ( $wgExternalDiffEngine == 'wikidiff' ) {
375 # For historical reasons, external diff engine expects
376 # input text to be HTML-escaped already
377 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
378 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
379 if( !function_exists( 'wikidiff_do_diff' ) ) {
380 dl('php_wikidiff.so');
382 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
385 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
386 # Better external diff engine, the 2 may some day be dropped
387 # This one does the escaping and segmenting itself
388 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
389 wfProfileIn( "$fname-dl" );
390 @dl
('php_wikidiff2.so');
391 wfProfileOut( "$fname-dl" );
393 if ( function_exists( 'wikidiff2_do_diff' ) ) {
394 wfProfileIn( 'wikidiff2_do_diff' );
395 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
396 wfProfileOut( 'wikidiff2_do_diff' );
400 if ( $wgExternalDiffEngine !== false ) {
402 global $wgTmpDirectory;
403 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
404 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
406 $tempFile1 = fopen( $tempName1, "w" );
408 wfProfileOut( $fname );
411 $tempFile2 = fopen( $tempName2, "w" );
413 wfProfileOut( $fname );
416 fwrite( $tempFile1, $otext );
417 fwrite( $tempFile2, $ntext );
418 fclose( $tempFile1 );
419 fclose( $tempFile2 );
420 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
421 wfProfileIn( "$fname-shellexec" );
422 $difftext = wfShellExec( $cmd );
423 wfProfileOut( "$fname-shellexec" );
424 unlink( $tempName1 );
425 unlink( $tempName2 );
430 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
431 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
432 $diffs = new Diff( $ota, $nta );
433 $formatter = new TableDiffFormatter();
434 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
439 * Replace line numbers with the text in the user's language
441 function localiseLineNumbers( $text ) {
442 return preg_replace_callback( '/<!--LINE (\d+)-->/',
443 array( &$this, 'localiseLineNumbersCb' ), $text );
446 function localiseLineNumbersCb( $matches ) {
448 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
453 * If there are revisions between the ones being compared, return a note saying so.
455 function getMultiNotice() {
456 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
459 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
460 // Comparing two different pages? Count would be meaningless.
464 $oldid = $this->mOldRev
->getId();
465 $newid = $this->mNewRev
->getId();
466 if ( $oldid > $newid ) {
467 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
470 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
474 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
479 * Add the header to a diff body
481 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
484 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
485 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
487 if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
488 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
491 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
493 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
494 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
499 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
501 return $header . $diff . "</table>";
505 * Use specified text instead of loading from the database
507 function setText( $oldText, $newText ) {
508 $this->mOldtext
= $oldText;
509 $this->mNewtext
= $newText;
510 $this->mTextLoaded
= 2;
514 * Load revision metadata for the specified articles. If newid is 0, then compare
515 * the old article in oldid to the current article; if oldid is 0, then
516 * compare the current article to the immediately previous one (ignoring the
519 * If oldid is false, leave the corresponding revision object set
520 * to false. This is impossible via ordinary user input, and is provided for
523 function loadRevisionData() {
525 if ( $this->mRevisionsLoaded
) {
528 // Whether it succeeds or fails, we don't want to try again
529 $this->mRevisionsLoaded
= true;
532 // Load the new revision object
533 if( $this->mNewid
) {
534 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
536 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
539 if( is_null( $this->mNewRev
) ) {
543 // Set assorted variables
544 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
545 $this->mNewPage
= $this->mNewRev
->getTitle();
546 if( $this->mNewRev
->isCurrent() ) {
547 $newLink = $this->mNewPage
->escapeLocalUrl();
548 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
549 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
551 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
552 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
555 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
556 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
557 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
559 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
560 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
563 // Load the old revision object
564 $this->mOldRev
= false;
565 if( $this->mOldid
) {
566 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
567 } elseif ( $this->mOldid
=== 0 ) {
568 $rev = $this->mNewRev
->getPrevious();
570 $this->mOldid
= $rev->getId();
571 $this->mOldRev
= $rev;
573 // No previous revision; mark to show as first-version only.
574 $this->mOldid
= false;
575 $this->mOldRev
= false;
577 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
579 if( is_null( $this->mOldRev
) ) {
583 if ( $this->mOldRev
) {
584 $this->mOldPage
= $this->mOldRev
->getTitle();
586 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
587 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
588 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
589 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
590 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
591 //now that we considered old rev, we can make undo link (bug 8133, multi-edit undo)
592 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
593 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
600 * Load the text of the revisions, as well as revision data.
602 function loadText() {
603 if ( $this->mTextLoaded
== 2 ) {
606 // Whether it succeeds or fails, we don't want to try again
607 $this->mTextLoaded
= 2;
610 if ( !$this->loadRevisionData() ) {
613 if ( $this->mOldRev
) {
614 // FIXME: permission tests
615 $this->mOldtext
= $this->mOldRev
->revText();
616 if ( $this->mOldtext
=== false ) {
620 if ( $this->mNewRev
) {
621 $this->mNewtext
= $this->mNewRev
->revText();
622 if ( $this->mNewtext
=== false ) {
630 * Load the text of the new revision, not the old one
632 function loadNewText() {
633 if ( $this->mTextLoaded
>= 1 ) {
636 $this->mTextLoaded
= 1;
638 if ( !$this->loadRevisionData() ) {
641 $this->mNewtext
= $this->mNewRev
->getText();
648 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
650 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
651 // You may copy this code freely under the conditions of the GPL.
654 define('USE_ASSERTS', function_exists('assert'));
659 * @addtogroup DifferenceEngine
667 trigger_error('pure virtual', E_USER_ERROR
);
671 return $this->orig ?
sizeof($this->orig
) : 0;
674 function nclosing() {
675 return $this->closing ?
sizeof($this->closing
) : 0;
682 * @addtogroup DifferenceEngine
684 class _DiffOp_Copy
extends _DiffOp
{
687 function _DiffOp_Copy ($orig, $closing = false) {
688 if (!is_array($closing))
691 $this->closing
= $closing;
695 return new _DiffOp_Copy($this->closing
, $this->orig
);
702 * @addtogroup DifferenceEngine
704 class _DiffOp_Delete
extends _DiffOp
{
705 var $type = 'delete';
707 function _DiffOp_Delete ($lines) {
708 $this->orig
= $lines;
709 $this->closing
= false;
713 return new _DiffOp_Add($this->orig
);
720 * @addtogroup DifferenceEngine
722 class _DiffOp_Add
extends _DiffOp
{
725 function _DiffOp_Add ($lines) {
726 $this->closing
= $lines;
731 return new _DiffOp_Delete($this->closing
);
738 * @addtogroup DifferenceEngine
740 class _DiffOp_Change
extends _DiffOp
{
741 var $type = 'change';
743 function _DiffOp_Change ($orig, $closing) {
745 $this->closing
= $closing;
749 return new _DiffOp_Change($this->closing
, $this->orig
);
755 * Class used internally by Diff to actually compute the diffs.
757 * The algorithm used here is mostly lifted from the perl module
758 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
759 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
761 * More ideas are taken from:
762 * http://www.ics.uci.edu/~eppstein/161/960229.html
764 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
765 * diffutils-2.7, which can be found at:
766 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
768 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
771 * Line length limits for robustness added by Tim Starling, 2005-08-31
773 * @author Geoffrey T. Dairiki, Tim Starling
775 * @addtogroup DifferenceEngine
779 const MAX_XREF_LENGTH
= 10000;
781 function diff ($from_lines, $to_lines) {
782 $fname = '_DiffEngine::diff';
783 wfProfileIn( $fname );
785 $n_from = sizeof($from_lines);
786 $n_to = sizeof($to_lines);
788 $this->xchanged
= $this->ychanged
= array();
789 $this->xv
= $this->yv
= array();
790 $this->xind
= $this->yind
= array();
792 unset($this->in_seq
);
795 // Skip leading common lines.
796 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
797 if ($from_lines[$skip] !== $to_lines[$skip])
799 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
801 // Skip trailing common lines.
802 $xi = $n_from; $yi = $n_to;
803 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
804 if ($from_lines[$xi] !== $to_lines[$yi])
806 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
809 // Ignore lines which do not exist in both files.
810 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
811 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
814 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
815 $line = $to_lines[$yi];
816 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
818 $yhash[$this->_line_hash($line)] = 1;
822 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
823 $line = $from_lines[$xi];
824 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
831 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
833 // Merge edits when possible
834 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
835 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
837 // Compute the edit operations.
840 while ($xi < $n_from ||
$yi < $n_to) {
841 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
842 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
844 // Skip matching "snake".
846 while ( $xi < $n_from && $yi < $n_to
847 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
848 $copy[] = $from_lines[$xi++
];
852 $edits[] = new _DiffOp_Copy($copy);
854 // Find deletes & adds.
856 while ($xi < $n_from && $this->xchanged
[$xi])
857 $delete[] = $from_lines[$xi++
];
860 while ($yi < $n_to && $this->ychanged
[$yi])
861 $add[] = $to_lines[$yi++
];
864 $edits[] = new _DiffOp_Change($delete, $add);
866 $edits[] = new _DiffOp_Delete($delete);
868 $edits[] = new _DiffOp_Add($add);
870 wfProfileOut( $fname );
875 * Returns the whole line if it's small enough, or the MD5 hash otherwise
877 function _line_hash( $line ) {
878 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
886 /* Divide the Largest Common Subsequence (LCS) of the sequences
887 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
890 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
891 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
892 * sub sequences. The first sub-sequence is contained in [X0, X1),
893 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
894 * that (X0, Y0) == (XOFF, YOFF) and
895 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
897 * This function assumes that the first lines of the specified portions
898 * of the two files do not match, and likewise that the last lines do not
899 * match. The caller must trim matching lines from the beginning and end
900 * of the portions it is going to specify.
902 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
903 $fname = '_DiffEngine::_diag';
904 wfProfileIn( $fname );
907 if ($xlim - $xoff > $ylim - $yoff) {
908 // Things seems faster (I'm not sure I understand why)
909 // when the shortest sequence in X.
911 list ($xoff, $xlim, $yoff, $ylim)
912 = array( $yoff, $ylim, $xoff, $xlim);
916 for ($i = $ylim - 1; $i >= $yoff; $i--)
917 $ymatches[$this->xv
[$i]][] = $i;
919 for ($i = $ylim - 1; $i >= $yoff; $i--)
920 $ymatches[$this->yv
[$i]][] = $i;
923 $this->seq
[0]= $yoff - 1;
924 $this->in_seq
= array();
927 $numer = $xlim - $xoff +
$nchunks - 1;
929 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
930 wfProfileIn( "$fname-chunk" );
932 for ($i = 0; $i <= $this->lcs
; $i++
)
933 $ymids[$i][$chunk-1] = $this->seq
[$i];
935 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
936 for ( ; $x < $x1; $x++
) {
937 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
938 if (empty($ymatches[$line]))
940 $matches = $ymatches[$line];
942 while (list ($junk, $y) = each($matches))
943 if (empty($this->in_seq
[$y])) {
944 $k = $this->_lcs_pos($y);
945 USE_ASSERTS
&& assert($k > 0);
946 $ymids[$k] = $ymids[$k-1];
949 while (list ( /* $junk */, $y) = each($matches)) {
950 if ($y > $this->seq
[$k-1]) {
951 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
952 // Optimization: this is a common case:
953 // next match is just replacing previous match.
954 $this->in_seq
[$this->seq
[$k]] = false;
956 $this->in_seq
[$y] = 1;
957 } else if (empty($this->in_seq
[$y])) {
958 $k = $this->_lcs_pos($y);
959 USE_ASSERTS
&& assert($k > 0);
960 $ymids[$k] = $ymids[$k-1];
964 wfProfileOut( "$fname-chunk" );
967 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
968 $ymid = $ymids[$this->lcs
];
969 for ($n = 0; $n < $nchunks - 1; $n++
) {
970 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
972 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
974 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
976 wfProfileOut( $fname );
977 return array($this->lcs
, $seps);
980 function _lcs_pos ($ypos) {
981 $fname = '_DiffEngine::_lcs_pos';
982 wfProfileIn( $fname );
985 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
986 $this->seq
[++
$this->lcs
] = $ypos;
987 $this->in_seq
[$ypos] = 1;
988 wfProfileOut( $fname );
993 while ($beg < $end) {
994 $mid = (int)(($beg +
$end) / 2);
995 if ( $ypos > $this->seq
[$mid] )
1001 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1003 $this->in_seq
[$this->seq
[$end]] = false;
1004 $this->seq
[$end] = $ypos;
1005 $this->in_seq
[$ypos] = 1;
1006 wfProfileOut( $fname );
1010 /* Find LCS of two sequences.
1012 * The results are recorded in the vectors $this->{x,y}changed[], by
1013 * storing a 1 in the element for each line that is an insertion
1014 * or deletion (ie. is not in the LCS).
1016 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1018 * Note that XLIM, YLIM are exclusive bounds.
1019 * All line numbers are origin-0 and discarded lines are not counted.
1021 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1022 $fname = '_DiffEngine::_compareseq';
1023 wfProfileIn( $fname );
1025 // Slide down the bottom initial diagonal.
1026 while ($xoff < $xlim && $yoff < $ylim
1027 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1032 // Slide up the top initial diagonal.
1033 while ($xlim > $xoff && $ylim > $yoff
1034 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1039 if ($xoff == $xlim ||
$yoff == $ylim)
1042 // This is ad hoc but seems to work well.
1043 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1044 //$nchunks = max(2,min(8,(int)$nchunks));
1045 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1047 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1051 // X and Y sequences have no common subsequence:
1052 // mark all changed.
1053 while ($yoff < $ylim)
1054 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1055 while ($xoff < $xlim)
1056 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1058 // Use the partitions to split this problem into subproblems.
1061 while ($pt2 = next($seps)) {
1062 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1066 wfProfileOut( $fname );
1069 /* Adjust inserts/deletes of identical lines to join changes
1070 * as much as possible.
1072 * We do something when a run of changed lines include a
1073 * line at one end and has an excluded, identical line at the other.
1074 * We are free to choose which identical line is included.
1075 * `compareseq' usually chooses the one at the beginning,
1076 * but usually it is cleaner to consider the following identical line
1077 * to be the "change".
1079 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1081 function _shift_boundaries ($lines, &$changed, $other_changed) {
1082 $fname = '_DiffEngine::_shift_boundaries';
1083 wfProfileIn( $fname );
1087 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1088 $len = sizeof($lines);
1089 $other_len = sizeof($other_changed);
1093 * Scan forwards to find beginning of another run of changes.
1094 * Also keep track of the corresponding point in the other file.
1096 * Throughout this code, $i and $j are adjusted together so that
1097 * the first $i elements of $changed and the first $j elements
1098 * of $other_changed both contain the same number of zeros
1099 * (unchanged lines).
1100 * Furthermore, $j is always kept so that $j == $other_len or
1101 * $other_changed[$j] == false.
1103 while ($j < $other_len && $other_changed[$j])
1106 while ($i < $len && ! $changed[$i]) {
1107 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1109 while ($j < $other_len && $other_changed[$j])
1118 // Find the end of this run of changes.
1119 while (++
$i < $len && $changed[$i])
1124 * Record the length of this run of changes, so that
1125 * we can later determine whether the run has grown.
1127 $runlength = $i - $start;
1130 * Move the changed region back, so long as the
1131 * previous unchanged line matches the last changed one.
1132 * This merges with previous changed regions.
1134 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1135 $changed[--$start] = 1;
1136 $changed[--$i] = false;
1137 while ($start > 0 && $changed[$start - 1])
1139 USE_ASSERTS
&& assert('$j > 0');
1140 while ($other_changed[--$j])
1142 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1146 * Set CORRESPONDING to the end of the changed run, at the last
1147 * point where it corresponds to a changed run in the other file.
1148 * CORRESPONDING == LEN means no such point has been found.
1150 $corresponding = $j < $other_len ?
$i : $len;
1153 * Move the changed region forward, so long as the
1154 * first changed line matches the following unchanged one.
1155 * This merges with following changed regions.
1156 * Do this second, so that if there are no merges,
1157 * the changed region is moved forward as far as possible.
1159 while ($i < $len && $lines[$start] == $lines[$i]) {
1160 $changed[$start++
] = false;
1162 while ($i < $len && $changed[$i])
1165 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1167 if ($j < $other_len && $other_changed[$j]) {
1168 $corresponding = $i;
1169 while ($j < $other_len && $other_changed[$j])
1173 } while ($runlength != $i - $start);
1176 * If possible, move the fully-merged run of changes
1177 * back to a corresponding run in the other file.
1179 while ($corresponding < $i) {
1180 $changed[--$start] = 1;
1182 USE_ASSERTS
&& assert('$j > 0');
1183 while ($other_changed[--$j])
1185 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1188 wfProfileOut( $fname );
1193 * Class representing a 'diff' between two sequences of strings.
1196 * @addtogroup DifferenceEngine
1204 * Computes diff between sequences of strings.
1206 * @param $from_lines array An array of strings.
1207 * (Typically these are lines from a file.)
1208 * @param $to_lines array An array of strings.
1210 function Diff($from_lines, $to_lines) {
1211 $eng = new _DiffEngine
;
1212 $this->edits
= $eng->diff($from_lines, $to_lines);
1213 //$this->_check($from_lines, $to_lines);
1217 * Compute reversed Diff.
1221 * $diff = new Diff($lines1, $lines2);
1222 * $rev = $diff->reverse();
1223 * @return object A Diff object representing the inverse of the
1226 function reverse () {
1228 $rev->edits
= array();
1229 foreach ($this->edits
as $edit) {
1230 $rev->edits
[] = $edit->reverse();
1236 * Check for empty diff.
1238 * @return bool True iff two sequences were identical.
1240 function isEmpty () {
1241 foreach ($this->edits
as $edit) {
1242 if ($edit->type
!= 'copy')
1249 * Compute the length of the Longest Common Subsequence (LCS).
1251 * This is mostly for diagnostic purposed.
1253 * @return int The length of the LCS.
1257 foreach ($this->edits
as $edit) {
1258 if ($edit->type
== 'copy')
1259 $lcs +
= sizeof($edit->orig
);
1265 * Get the original set of lines.
1267 * This reconstructs the $from_lines parameter passed to the
1270 * @return array The original sequence of strings.
1275 foreach ($this->edits
as $edit) {
1277 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1283 * Get the closing set of lines.
1285 * This reconstructs the $to_lines parameter passed to the
1288 * @return array The sequence of strings.
1290 function closing() {
1293 foreach ($this->edits
as $edit) {
1295 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1301 * Check a Diff for validity.
1303 * This is here only for debugging purposes.
1305 function _check ($from_lines, $to_lines) {
1306 $fname = 'Diff::_check';
1307 wfProfileIn( $fname );
1308 if (serialize($from_lines) != serialize($this->orig()))
1309 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1310 if (serialize($to_lines) != serialize($this->closing()))
1311 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1313 $rev = $this->reverse();
1314 if (serialize($to_lines) != serialize($rev->orig()))
1315 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1316 if (serialize($from_lines) != serialize($rev->closing()))
1317 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1321 foreach ($this->edits
as $edit) {
1322 if ( $prevtype == $edit->type
)
1323 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1324 $prevtype = $edit->type
;
1327 $lcs = $this->lcs();
1328 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1329 wfProfileOut( $fname );
1334 * @todo document, bad name.
1336 * @addtogroup DifferenceEngine
1338 class MappedDiff
extends Diff
1343 * Computes diff between sequences of strings.
1345 * This can be used to compute things like
1346 * case-insensitve diffs, or diffs which ignore
1347 * changes in white-space.
1349 * @param $from_lines array An array of strings.
1350 * (Typically these are lines from a file.)
1352 * @param $to_lines array An array of strings.
1354 * @param $mapped_from_lines array This array should
1355 * have the same size number of elements as $from_lines.
1356 * The elements in $mapped_from_lines and
1357 * $mapped_to_lines are what is actually compared
1358 * when computing the diff.
1360 * @param $mapped_to_lines array This array should
1361 * have the same number of elements as $to_lines.
1363 function MappedDiff($from_lines, $to_lines,
1364 $mapped_from_lines, $mapped_to_lines) {
1365 $fname = 'MappedDiff::MappedDiff';
1366 wfProfileIn( $fname );
1368 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1369 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1371 $this->Diff($mapped_from_lines, $mapped_to_lines);
1374 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1375 $orig = &$this->edits
[$i]->orig
;
1376 if (is_array($orig)) {
1377 $orig = array_slice($from_lines, $xi, sizeof($orig));
1378 $xi +
= sizeof($orig);
1381 $closing = &$this->edits
[$i]->closing
;
1382 if (is_array($closing)) {
1383 $closing = array_slice($to_lines, $yi, sizeof($closing));
1384 $yi +
= sizeof($closing);
1387 wfProfileOut( $fname );
1392 * A class to format Diffs
1394 * This class formats the diff in classic diff format.
1395 * It is intended that this class be customized via inheritance,
1396 * to obtain fancier outputs.
1399 * @addtogroup DifferenceEngine
1404 * Number of leading context "lines" to preserve.
1406 * This should be left at zero for this class, but subclasses
1407 * may want to set this to other values.
1409 var $leading_context_lines = 0;
1412 * Number of trailing context "lines" to preserve.
1414 * This should be left at zero for this class, but subclasses
1415 * may want to set this to other values.
1417 var $trailing_context_lines = 0;
1422 * @param $diff object A Diff object.
1423 * @return string The formatted output.
1425 function format($diff) {
1426 $fname = 'DiffFormatter::format';
1427 wfProfileIn( $fname );
1433 $nlead = $this->leading_context_lines
;
1434 $ntrail = $this->trailing_context_lines
;
1436 $this->_start_diff();
1438 foreach ($diff->edits
as $edit) {
1439 if ($edit->type
== 'copy') {
1440 if (is_array($block)) {
1441 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1446 $context = array_slice($edit->orig
, 0, $ntrail);
1447 $block[] = new _DiffOp_Copy($context);
1449 $this->_block($x0, $ntrail +
$xi - $x0,
1450 $y0, $ntrail +
$yi - $y0,
1455 $context = $edit->orig
;
1458 if (! is_array($block)) {
1459 $context = array_slice($context, sizeof($context) - $nlead);
1460 $x0 = $xi - sizeof($context);
1461 $y0 = $yi - sizeof($context);
1464 $block[] = new _DiffOp_Copy($context);
1470 $xi +
= sizeof($edit->orig
);
1472 $yi +
= sizeof($edit->closing
);
1475 if (is_array($block))
1476 $this->_block($x0, $xi - $x0,
1480 $end = $this->_end_diff();
1481 wfProfileOut( $fname );
1485 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1486 $fname = 'DiffFormatter::_block';
1487 wfProfileIn( $fname );
1488 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1489 foreach ($edits as $edit) {
1490 if ($edit->type
== 'copy')
1491 $this->_context($edit->orig
);
1492 elseif ($edit->type
== 'add')
1493 $this->_added($edit->closing
);
1494 elseif ($edit->type
== 'delete')
1495 $this->_deleted($edit->orig
);
1496 elseif ($edit->type
== 'change')
1497 $this->_changed($edit->orig
, $edit->closing
);
1499 trigger_error('Unknown edit type', E_USER_ERROR
);
1501 $this->_end_block();
1502 wfProfileOut( $fname );
1505 function _start_diff() {
1509 function _end_diff() {
1510 $val = ob_get_contents();
1515 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1517 $xbeg .= "," . ($xbeg +
$xlen - 1);
1519 $ybeg .= "," . ($ybeg +
$ylen - 1);
1521 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1524 function _start_block($header) {
1528 function _end_block() {
1531 function _lines($lines, $prefix = ' ') {
1532 foreach ($lines as $line)
1533 echo "$prefix $line\n";
1536 function _context($lines) {
1537 $this->_lines($lines);
1540 function _added($lines) {
1541 $this->_lines($lines, '>');
1543 function _deleted($lines) {
1544 $this->_lines($lines, '<');
1547 function _changed($orig, $closing) {
1548 $this->_deleted($orig);
1550 $this->_added($closing);
1556 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1560 define('NBSP', ' '); // iso-8859-x non-breaking space.
1565 * @addtogroup DifferenceEngine
1567 class _HWLDF_WordAccumulator
{
1568 function _HWLDF_WordAccumulator () {
1569 $this->_lines
= array();
1575 function _flushGroup ($new_tag) {
1576 if ($this->_group
!== '') {
1577 if ($this->_tag
== 'ins')
1578 $this->_line
.= '<ins class="diffchange">' .
1579 htmlspecialchars ( $this->_group
) . '</ins>';
1580 elseif ($this->_tag
== 'del')
1581 $this->_line
.= '<del class="diffchange">' .
1582 htmlspecialchars ( $this->_group
) . '</del>';
1584 $this->_line
.= htmlspecialchars ( $this->_group
);
1587 $this->_tag
= $new_tag;
1590 function _flushLine ($new_tag) {
1591 $this->_flushGroup($new_tag);
1592 if ($this->_line
!= '')
1593 array_push ( $this->_lines
, $this->_line
);
1595 # make empty lines visible by inserting an NBSP
1596 array_push ( $this->_lines
, NBSP
);
1600 function addWords ($words, $tag = '') {
1601 if ($tag != $this->_tag
)
1602 $this->_flushGroup($tag);
1604 foreach ($words as $word) {
1605 // new-line should only come as first char of word.
1608 if ($word[0] == "\n") {
1609 $this->_flushLine($tag);
1610 $word = substr($word, 1);
1612 assert(!strstr($word, "\n"));
1613 $this->_group
.= $word;
1617 function getLines() {
1618 $this->_flushLine('~done');
1619 return $this->_lines
;
1626 * @addtogroup DifferenceEngine
1628 class WordLevelDiff
extends MappedDiff
1630 const MAX_LINE_LENGTH
= 10000;
1632 function WordLevelDiff ($orig_lines, $closing_lines) {
1633 $fname = 'WordLevelDiff::WordLevelDiff';
1634 wfProfileIn( $fname );
1636 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1637 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1639 $this->MappedDiff($orig_words, $closing_words,
1640 $orig_stripped, $closing_stripped);
1641 wfProfileOut( $fname );
1644 function _split($lines) {
1645 $fname = 'WordLevelDiff::_split';
1646 wfProfileIn( $fname );
1649 $stripped = array();
1651 foreach ( $lines as $line ) {
1652 # If the line is too long, just pretend the entire line is one big word
1653 # This prevents resource exhaustion problems
1660 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1662 $stripped[] = $line;
1665 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1668 $words = array_merge( $words, $m[0] );
1669 $stripped = array_merge( $stripped, $m[1] );
1673 wfProfileOut( $fname );
1674 return array($words, $stripped);
1678 $fname = 'WordLevelDiff::orig';
1679 wfProfileIn( $fname );
1680 $orig = new _HWLDF_WordAccumulator
;
1682 foreach ($this->edits
as $edit) {
1683 if ($edit->type
== 'copy')
1684 $orig->addWords($edit->orig
);
1685 elseif ($edit->orig
)
1686 $orig->addWords($edit->orig
, 'del');
1688 $lines = $orig->getLines();
1689 wfProfileOut( $fname );
1693 function closing () {
1694 $fname = 'WordLevelDiff::closing';
1695 wfProfileIn( $fname );
1696 $closing = new _HWLDF_WordAccumulator
;
1698 foreach ($this->edits
as $edit) {
1699 if ($edit->type
== 'copy')
1700 $closing->addWords($edit->closing
);
1701 elseif ($edit->closing
)
1702 $closing->addWords($edit->closing
, 'ins');
1704 $lines = $closing->getLines();
1705 wfProfileOut( $fname );
1711 * Wikipedia Table style diff formatter.
1714 * @addtogroup DifferenceEngine
1716 class TableDiffFormatter
extends DiffFormatter
1718 function TableDiffFormatter() {
1719 $this->leading_context_lines
= 2;
1720 $this->trailing_context_lines
= 2;
1723 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1724 $r = '<tr><td colspan="2" align="left"><strong><!--LINE '.$xbeg."--></strong></td>\n" .
1725 '<td colspan="2" align="left"><strong><!--LINE '.$ybeg."--></strong></td></tr>\n";
1729 function _start_block( $header ) {
1733 function _end_block() {
1736 function _lines( $lines, $prefix=' ', $color='white' ) {
1739 # HTML-escape parameter before calling this
1740 function addedLine( $line ) {
1741 return "<td>+</td><td class='diff-addedline'><div>{$line}</div></td>";
1744 # HTML-escape parameter before calling this
1745 function deletedLine( $line ) {
1746 return "<td>-</td><td class='diff-deletedline'><div>{$line}</div></td>";
1749 # HTML-escape parameter before calling this
1750 function contextLine( $line ) {
1751 return "<td> </td><td class='diff-context'><div>{$line}</div></td>";
1754 function emptyLine() {
1755 return '<td colspan="2"> </td>';
1758 function _added( $lines ) {
1759 foreach ($lines as $line) {
1760 echo '<tr>' . $this->emptyLine() .
1761 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1765 function _deleted($lines) {
1766 foreach ($lines as $line) {
1767 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1768 $this->emptyLine() . "</tr>\n";
1772 function _context( $lines ) {
1773 foreach ($lines as $line) {
1775 $this->contextLine( htmlspecialchars ( $line ) ) .
1776 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1780 function _changed( $orig, $closing ) {
1781 $fname = 'TableDiffFormatter::_changed';
1782 wfProfileIn( $fname );
1784 $diff = new WordLevelDiff( $orig, $closing );
1785 $del = $diff->orig();
1786 $add = $diff->closing();
1788 # Notice that WordLevelDiff returns HTML-escaped output.
1789 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1791 while ( $line = array_shift( $del ) ) {
1792 $aline = array_shift( $add );
1793 echo '<tr>' . $this->deletedLine( $line ) .
1794 $this->addedLine( $aline ) . "</tr>\n";
1796 foreach ($add as $line) { # If any leftovers
1797 echo '<tr>' . $this->emptyLine() .
1798 $this->addedLine( $line ) . "</tr>\n";
1800 wfProfileOut( $fname );