4 * @addtogroup DifferenceEngine
10 * @addtogroup DifferenceEngine
12 class DifferenceEngine
{
16 var $mOldid, $mNewid, $mTitle;
17 var $mOldtitle, $mNewtitle, $mPagetitle;
18 var $mOldtext, $mNewtext;
19 var $mOldPage, $mNewPage;
20 var $mRcidMarkPatrolled;
21 var $mOldRev, $mNewRev;
22 var $mRevisionsLoaded = false; // Have the revisions been loaded
23 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
28 * @param $titleObj Title object that the diff is associated with
29 * @param $old Integer: old ID we want to show and diff with.
30 * @param $new String: either 'prev' or 'next'.
31 * @param $rcid Integer: ??? FIXME (default 0)
33 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
34 $this->mTitle
= $titleObj;
35 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
37 if ( 'prev' === $new ) {
38 # Show diff between revision $old and the previous one.
39 # Get previous one from DB.
41 $this->mNewid
= intval($old);
43 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
45 } elseif ( 'next' === $new ) {
46 # Show diff between revision $old and the previous one.
47 # Get previous one from DB.
49 $this->mOldid
= intval($old);
50 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
51 if ( false === $this->mNewid
) {
52 # if no result, NewId points to the newest old revision. The only newer
53 # revision is cur, which is "0".
58 $this->mOldid
= intval($old);
59 $this->mNewid
= intval($new);
61 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
64 function showDiffPage( $diffOnly = false ) {
65 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
66 $fname = 'DifferenceEngine::showDiffPage';
67 wfProfileIn( $fname );
69 # If external diffs are enabled both globally and for the user,
70 # we'll use the application/x-external-editor interface to call
71 # an external diff tool like kompare, kdiff3, etc.
72 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
73 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
75 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
76 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
77 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
78 $special=$wgLang->getNsText(NS_SPECIAL
);
83 Script={$wgServer}{$wgScript}
84 Special namespace={$special}
98 $wgOut->setArticleFlag( false );
99 if ( ! $this->loadRevisionData() ) {
100 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
101 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
102 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
103 $wgOut->addWikitext( $mtext );
104 wfProfileOut( $fname );
108 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
110 if ( $this->mNewRev
->isCurrent() ) {
111 $wgOut->setArticleFlag( true );
114 # mOldid is false if the difference engine is called with a "vague" query for
115 # a diff between a version V and its previous version V' AND the version V
116 # is the first version of that article. In that case, V' does not exist.
117 if ( $this->mOldid
=== false ) {
118 $this->showFirstRevision();
119 $this->renderNewRevision(); // should we respect $diffOnly here or not?
120 wfProfileOut( $fname );
124 $wgOut->suppressQuickbar();
126 $oldTitle = $this->mOldPage
->getPrefixedText();
127 $newTitle = $this->mNewPage
->getPrefixedText();
128 if( $oldTitle == $newTitle ) {
129 $wgOut->setPageTitle( $newTitle );
131 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
133 $wgOut->setSubtitle( wfMsg( 'difference' ) );
134 $wgOut->setRobotpolicy( 'noindex,nofollow' );
136 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
137 $wgOut->loginToUse();
139 wfProfileOut( $fname );
143 $sk = $wgUser->getSkin();
145 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
146 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
150 if( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isAllowed( 'patrol' ) ) {
151 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
156 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
157 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
158 if ( $this->mNewRev
->isCurrent() ) {
159 $nextlink = ' ';
161 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
162 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
168 if ($this->mOldRev
->mMinorEdit
== 1) {
169 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
170 wfMsg( 'minoreditletter') ) . ' ';
173 if ($this->mNewRev
->mMinorEdit
== 1) {
174 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
175 wfMsg( 'minoreditletter') ) . ' ';
178 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />" .
179 $sk->revUserTools( $this->mOldRev
) . "<br />" .
180 $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly ) . "<br />" .
182 $newHeader = "<strong>{$this->mNewtitle}</strong><br />" .
183 $sk->revUserTools( $this->mNewRev
) . " $rollback<br />" .
184 $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly ) . "<br />" .
187 $this->showDiff( $oldHeader, $newHeader );
190 $this->renderNewRevision();
192 wfProfileOut( $fname );
196 * Show the new revision of the page.
198 function renderNewRevision() {
200 $fname = 'DifferenceEngine::renderNewRevision';
201 wfProfileIn( $fname );
203 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
204 #add deleted rev tag if needed
205 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
206 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
209 if( !$this->mNewRev
->isCurrent() ) {
210 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
213 $this->loadNewText();
214 if( is_object( $this->mNewRev
) ) {
215 $wgOut->setRevisionId( $this->mNewRev
->getId() );
218 $wgOut->addWikiTextTidy( $this->mNewtext
);
220 if( !$this->mNewRev
->isCurrent() ) {
221 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
224 wfProfileOut( $fname );
228 * Show the first revision of an article. Uses normal diff headers in
229 * contrast to normal "old revision" display style.
231 function showFirstRevision() {
232 global $wgOut, $wgUser;
234 $fname = 'DifferenceEngine::showFirstRevision';
235 wfProfileIn( $fname );
237 # Get article text from the DB
239 if ( ! $this->loadNewText() ) {
240 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
242 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
243 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
244 $wgOut->addWikitext( $mtext );
245 wfProfileOut( $fname );
248 if ( $this->mNewRev
->isCurrent() ) {
249 $wgOut->setArticleFlag( true );
252 # Check if user is allowed to look at this page. If not, bail out.
254 if ( !( $this->mTitle
->userCanRead() ) ) {
255 $wgOut->loginToUse();
257 wfProfileOut( $fname );
261 # Prepare the header box
263 $sk = $wgUser->getSkin();
265 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
266 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
267 $sk->revUserTools( $this->mNewRev
) . "<br />" .
268 $sk->revComment( $this->mNewRev
) . "<br />" .
269 $nextlink . "</div>\n";
271 $wgOut->addHTML( $header );
273 $wgOut->setSubtitle( wfMsg( 'difference' ) );
274 $wgOut->setRobotpolicy( 'noindex,nofollow' );
276 wfProfileOut( $fname );
280 * Get the diff text, send it to $wgOut
281 * Returns false if the diff could not be generated, otherwise returns true
283 function showDiff( $otitle, $ntitle ) {
285 $diff = $this->getDiff( $otitle, $ntitle );
286 if ( $diff === false ) {
287 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
290 $wgOut->addHTML( $diff );
296 * Get diff table, including header
297 * Note that the interface has changed, it's no longer static.
298 * Returns false on error
300 function getDiff( $otitle, $ntitle ) {
301 $body = $this->getDiffBody();
302 if ( $body === false ) {
305 $multi = $this->getMultiNotice();
306 return $this->addHeader( $body, $otitle, $ntitle, $multi );
311 * Get the diff table body, without header
313 * Returns false on error
315 function getDiffBody() {
317 $fname = 'DifferenceEngine::getDiffBody';
318 wfProfileIn( $fname );
322 if ( $this->mOldid
&& $this->mNewid
) {
324 $key = wfMemcKey( 'diff', 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
325 $difftext = $wgMemc->get( $key );
327 wfIncrStats( 'diff_cache_hit' );
328 $difftext = $this->localiseLineNumbers( $difftext );
329 $difftext .= "\n<!-- diff cache key $key -->\n";
330 wfProfileOut( $fname );
335 #loadtext is permission safe, this just clears out the diff
336 if ( !$this->loadText() ) {
337 wfProfileOut( $fname );
339 } else if ( !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ||
!$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
343 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
345 // Save to cache for 7 days
346 if ( $key !== false && $difftext !== false ) {
347 wfIncrStats( 'diff_cache_miss' );
348 $wgMemc->set( $key, $difftext, 7*86400 );
350 wfIncrStats( 'diff_uncacheable' );
352 // Replace line numbers with the text in the user's language
353 if ( $difftext !== false ) {
354 $difftext = $this->localiseLineNumbers( $difftext );
356 wfProfileOut( $fname );
361 * Generate a diff, no caching
362 * $otext and $ntext must be already segmented
364 function generateDiffBody( $otext, $ntext ) {
365 global $wgExternalDiffEngine, $wgContLang;
366 $fname = 'DifferenceEngine::generateDiffBody';
368 $otext = str_replace( "\r\n", "\n", $otext );
369 $ntext = str_replace( "\r\n", "\n", $ntext );
371 if ( $wgExternalDiffEngine == 'wikidiff' ) {
372 # For historical reasons, external diff engine expects
373 # input text to be HTML-escaped already
374 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
375 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
376 if( !function_exists( 'wikidiff_do_diff' ) ) {
377 dl('php_wikidiff.so');
379 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
382 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
383 # Better external diff engine, the 2 may some day be dropped
384 # This one does the escaping and segmenting itself
385 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
386 wfProfileIn( "$fname-dl" );
387 @dl
('php_wikidiff2.so');
388 wfProfileOut( "$fname-dl" );
390 if ( function_exists( 'wikidiff2_do_diff' ) ) {
391 wfProfileIn( 'wikidiff2_do_diff' );
392 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
393 wfProfileOut( 'wikidiff2_do_diff' );
397 if ( $wgExternalDiffEngine !== false ) {
399 global $wgTmpDirectory;
400 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
401 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
403 $tempFile1 = fopen( $tempName1, "w" );
405 wfProfileOut( $fname );
408 $tempFile2 = fopen( $tempName2, "w" );
410 wfProfileOut( $fname );
413 fwrite( $tempFile1, $otext );
414 fwrite( $tempFile2, $ntext );
415 fclose( $tempFile1 );
416 fclose( $tempFile2 );
417 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
418 wfProfileIn( "$fname-shellexec" );
419 $difftext = wfShellExec( $cmd );
420 wfProfileOut( "$fname-shellexec" );
421 unlink( $tempName1 );
422 unlink( $tempName2 );
427 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
428 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
429 $diffs = new Diff( $ota, $nta );
430 $formatter = new TableDiffFormatter();
431 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
436 * Replace line numbers with the text in the user's language
438 function localiseLineNumbers( $text ) {
439 return preg_replace_callback( '/<!--LINE (\d+)-->/',
440 array( &$this, 'localiseLineNumbersCb' ), $text );
443 function localiseLineNumbersCb( $matches ) {
445 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
450 * If there are revisions between the ones being compared, return a note saying so.
452 function getMultiNotice() {
453 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
456 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
457 // Comparing two different pages? Count would be meaningless.
461 $oldid = $this->mOldRev
->getId();
462 $newid = $this->mNewRev
->getId();
463 if ( $oldid > $newid ) {
464 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
467 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
471 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
476 * Add the header to a diff body
478 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
481 if ( !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
482 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
484 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
485 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
488 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
490 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
491 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
496 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
498 return $header . $diff . "</table>";
502 * Use specified text instead of loading from the database
504 function setText( $oldText, $newText ) {
505 $this->mOldtext
= $oldText;
506 $this->mNewtext
= $newText;
507 $this->mTextLoaded
= 2;
511 * Load revision metadata for the specified articles. If newid is 0, then compare
512 * the old article in oldid to the current article; if oldid is 0, then
513 * compare the current article to the immediately previous one (ignoring the
516 * If oldid is false, leave the corresponding revision object set
517 * to false. This is impossible via ordinary user input, and is provided for
520 function loadRevisionData() {
522 if ( $this->mRevisionsLoaded
) {
525 // Whether it succeeds or fails, we don't want to try again
526 $this->mRevisionsLoaded
= true;
529 // Load the new revision object
530 if( $this->mNewid
) {
531 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
533 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
536 if( is_null( $this->mNewRev
) ) {
540 // Set assorted variables
541 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
542 $this->mNewPage
= $this->mNewRev
->getTitle();
543 if( $this->mNewRev
->isCurrent() ) {
544 $newLink = $this->mNewPage
->escapeLocalUrl();
545 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
546 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
547 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undo=' . $this->mNewid
);
549 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
550 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)"
551 . " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
554 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
555 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
556 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undo=' . $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>)"
561 . " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
564 // Load the old revision object
565 $this->mOldRev
= false;
566 if( $this->mOldid
) {
567 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
568 } elseif ( $this->mOldid
=== 0 ) {
569 $rev = $this->mNewRev
->getPrevious();
571 $this->mOldid
= $rev->getId();
572 $this->mOldRev
= $rev;
574 // No previous revision; mark to show as first-version only.
575 $this->mOldid
= false;
576 $this->mOldRev
= false;
578 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
580 if( is_null( $this->mOldRev
) ) {
584 if ( $this->mOldRev
) {
585 $this->mOldPage
= $this->mOldRev
->getTitle();
587 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
588 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
589 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
590 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
591 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
598 * Load the text of the revisions, as well as revision data.
600 function loadText() {
601 if ( $this->mTextLoaded
== 2 ) {
604 // Whether it succeeds or fails, we don't want to try again
605 $this->mTextLoaded
= 2;
608 if ( !$this->loadRevisionData() ) {
611 if ( $this->mOldRev
) {
612 // FIXME: permission tests
613 $this->mOldtext
= $this->mOldRev
->getText();
614 if ( $this->mOldtext
=== false ) {
618 if ( $this->mNewRev
) {
619 $this->mNewtext
= $this->mNewRev
->getText();
620 if ( $this->mNewtext
=== false ) {
628 * Load the text of the new revision, not the old one
630 function loadNewText() {
631 if ( $this->mTextLoaded
>= 1 ) {
634 $this->mTextLoaded
= 1;
636 if ( !$this->loadRevisionData() ) {
639 $this->mNewtext
= $this->mNewRev
->getText();
646 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
648 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
649 // You may copy this code freely under the conditions of the GPL.
652 define('USE_ASSERTS', function_exists('assert'));
657 * @addtogroup DifferenceEngine
665 trigger_error('pure virtual', E_USER_ERROR
);
669 return $this->orig ?
sizeof($this->orig
) : 0;
672 function nclosing() {
673 return $this->closing ?
sizeof($this->closing
) : 0;
680 * @addtogroup DifferenceEngine
682 class _DiffOp_Copy
extends _DiffOp
{
685 function _DiffOp_Copy ($orig, $closing = false) {
686 if (!is_array($closing))
689 $this->closing
= $closing;
693 return new _DiffOp_Copy($this->closing
, $this->orig
);
700 * @addtogroup DifferenceEngine
702 class _DiffOp_Delete
extends _DiffOp
{
703 var $type = 'delete';
705 function _DiffOp_Delete ($lines) {
706 $this->orig
= $lines;
707 $this->closing
= false;
711 return new _DiffOp_Add($this->orig
);
718 * @addtogroup DifferenceEngine
720 class _DiffOp_Add
extends _DiffOp
{
723 function _DiffOp_Add ($lines) {
724 $this->closing
= $lines;
729 return new _DiffOp_Delete($this->closing
);
736 * @addtogroup DifferenceEngine
738 class _DiffOp_Change
extends _DiffOp
{
739 var $type = 'change';
741 function _DiffOp_Change ($orig, $closing) {
743 $this->closing
= $closing;
747 return new _DiffOp_Change($this->closing
, $this->orig
);
753 * Class used internally by Diff to actually compute the diffs.
755 * The algorithm used here is mostly lifted from the perl module
756 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
757 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
759 * More ideas are taken from:
760 * http://www.ics.uci.edu/~eppstein/161/960229.html
762 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
763 * diffutils-2.7, which can be found at:
764 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
766 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
769 * Line length limits for robustness added by Tim Starling, 2005-08-31
771 * @author Geoffrey T. Dairiki, Tim Starling
773 * @addtogroup DifferenceEngine
777 const MAX_XREF_LENGTH
= 10000;
779 function diff ($from_lines, $to_lines) {
780 $fname = '_DiffEngine::diff';
781 wfProfileIn( $fname );
783 $n_from = sizeof($from_lines);
784 $n_to = sizeof($to_lines);
786 $this->xchanged
= $this->ychanged
= array();
787 $this->xv
= $this->yv
= array();
788 $this->xind
= $this->yind
= array();
790 unset($this->in_seq
);
793 // Skip leading common lines.
794 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
795 if ($from_lines[$skip] !== $to_lines[$skip])
797 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
799 // Skip trailing common lines.
800 $xi = $n_from; $yi = $n_to;
801 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
802 if ($from_lines[$xi] !== $to_lines[$yi])
804 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
807 // Ignore lines which do not exist in both files.
808 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
809 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
812 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
813 $line = $to_lines[$yi];
814 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
816 $yhash[$this->_line_hash($line)] = 1;
820 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
821 $line = $from_lines[$xi];
822 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
829 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
831 // Merge edits when possible
832 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
833 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
835 // Compute the edit operations.
838 while ($xi < $n_from ||
$yi < $n_to) {
839 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
840 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
842 // Skip matching "snake".
844 while ( $xi < $n_from && $yi < $n_to
845 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
846 $copy[] = $from_lines[$xi++
];
850 $edits[] = new _DiffOp_Copy($copy);
852 // Find deletes & adds.
854 while ($xi < $n_from && $this->xchanged
[$xi])
855 $delete[] = $from_lines[$xi++
];
858 while ($yi < $n_to && $this->ychanged
[$yi])
859 $add[] = $to_lines[$yi++
];
862 $edits[] = new _DiffOp_Change($delete, $add);
864 $edits[] = new _DiffOp_Delete($delete);
866 $edits[] = new _DiffOp_Add($add);
868 wfProfileOut( $fname );
873 * Returns the whole line if it's small enough, or the MD5 hash otherwise
875 function _line_hash( $line ) {
876 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
884 /* Divide the Largest Common Subsequence (LCS) of the sequences
885 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
888 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
889 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
890 * sub sequences. The first sub-sequence is contained in [X0, X1),
891 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
892 * that (X0, Y0) == (XOFF, YOFF) and
893 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
895 * This function assumes that the first lines of the specified portions
896 * of the two files do not match, and likewise that the last lines do not
897 * match. The caller must trim matching lines from the beginning and end
898 * of the portions it is going to specify.
900 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
901 $fname = '_DiffEngine::_diag';
902 wfProfileIn( $fname );
905 if ($xlim - $xoff > $ylim - $yoff) {
906 // Things seems faster (I'm not sure I understand why)
907 // when the shortest sequence in X.
909 list ($xoff, $xlim, $yoff, $ylim)
910 = array( $yoff, $ylim, $xoff, $xlim);
914 for ($i = $ylim - 1; $i >= $yoff; $i--)
915 $ymatches[$this->xv
[$i]][] = $i;
917 for ($i = $ylim - 1; $i >= $yoff; $i--)
918 $ymatches[$this->yv
[$i]][] = $i;
921 $this->seq
[0]= $yoff - 1;
922 $this->in_seq
= array();
925 $numer = $xlim - $xoff +
$nchunks - 1;
927 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
928 wfProfileIn( "$fname-chunk" );
930 for ($i = 0; $i <= $this->lcs
; $i++
)
931 $ymids[$i][$chunk-1] = $this->seq
[$i];
933 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
934 for ( ; $x < $x1; $x++
) {
935 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
936 if (empty($ymatches[$line]))
938 $matches = $ymatches[$line];
940 while (list ($junk, $y) = each($matches))
941 if (empty($this->in_seq
[$y])) {
942 $k = $this->_lcs_pos($y);
943 USE_ASSERTS
&& assert($k > 0);
944 $ymids[$k] = $ymids[$k-1];
947 while (list ( /* $junk */, $y) = each($matches)) {
948 if ($y > $this->seq
[$k-1]) {
949 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
950 // Optimization: this is a common case:
951 // next match is just replacing previous match.
952 $this->in_seq
[$this->seq
[$k]] = false;
954 $this->in_seq
[$y] = 1;
955 } else if (empty($this->in_seq
[$y])) {
956 $k = $this->_lcs_pos($y);
957 USE_ASSERTS
&& assert($k > 0);
958 $ymids[$k] = $ymids[$k-1];
962 wfProfileOut( "$fname-chunk" );
965 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
966 $ymid = $ymids[$this->lcs
];
967 for ($n = 0; $n < $nchunks - 1; $n++
) {
968 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
970 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
972 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
974 wfProfileOut( $fname );
975 return array($this->lcs
, $seps);
978 function _lcs_pos ($ypos) {
979 $fname = '_DiffEngine::_lcs_pos';
980 wfProfileIn( $fname );
983 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
984 $this->seq
[++
$this->lcs
] = $ypos;
985 $this->in_seq
[$ypos] = 1;
986 wfProfileOut( $fname );
991 while ($beg < $end) {
992 $mid = (int)(($beg +
$end) / 2);
993 if ( $ypos > $this->seq
[$mid] )
999 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1001 $this->in_seq
[$this->seq
[$end]] = false;
1002 $this->seq
[$end] = $ypos;
1003 $this->in_seq
[$ypos] = 1;
1004 wfProfileOut( $fname );
1008 /* Find LCS of two sequences.
1010 * The results are recorded in the vectors $this->{x,y}changed[], by
1011 * storing a 1 in the element for each line that is an insertion
1012 * or deletion (ie. is not in the LCS).
1014 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1016 * Note that XLIM, YLIM are exclusive bounds.
1017 * All line numbers are origin-0 and discarded lines are not counted.
1019 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1020 $fname = '_DiffEngine::_compareseq';
1021 wfProfileIn( $fname );
1023 // Slide down the bottom initial diagonal.
1024 while ($xoff < $xlim && $yoff < $ylim
1025 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1030 // Slide up the top initial diagonal.
1031 while ($xlim > $xoff && $ylim > $yoff
1032 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1037 if ($xoff == $xlim ||
$yoff == $ylim)
1040 // This is ad hoc but seems to work well.
1041 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1042 //$nchunks = max(2,min(8,(int)$nchunks));
1043 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1045 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1049 // X and Y sequences have no common subsequence:
1050 // mark all changed.
1051 while ($yoff < $ylim)
1052 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1053 while ($xoff < $xlim)
1054 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1056 // Use the partitions to split this problem into subproblems.
1059 while ($pt2 = next($seps)) {
1060 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1064 wfProfileOut( $fname );
1067 /* Adjust inserts/deletes of identical lines to join changes
1068 * as much as possible.
1070 * We do something when a run of changed lines include a
1071 * line at one end and has an excluded, identical line at the other.
1072 * We are free to choose which identical line is included.
1073 * `compareseq' usually chooses the one at the beginning,
1074 * but usually it is cleaner to consider the following identical line
1075 * to be the "change".
1077 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1079 function _shift_boundaries ($lines, &$changed, $other_changed) {
1080 $fname = '_DiffEngine::_shift_boundaries';
1081 wfProfileIn( $fname );
1085 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1086 $len = sizeof($lines);
1087 $other_len = sizeof($other_changed);
1091 * Scan forwards to find beginning of another run of changes.
1092 * Also keep track of the corresponding point in the other file.
1094 * Throughout this code, $i and $j are adjusted together so that
1095 * the first $i elements of $changed and the first $j elements
1096 * of $other_changed both contain the same number of zeros
1097 * (unchanged lines).
1098 * Furthermore, $j is always kept so that $j == $other_len or
1099 * $other_changed[$j] == false.
1101 while ($j < $other_len && $other_changed[$j])
1104 while ($i < $len && ! $changed[$i]) {
1105 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1107 while ($j < $other_len && $other_changed[$j])
1116 // Find the end of this run of changes.
1117 while (++
$i < $len && $changed[$i])
1122 * Record the length of this run of changes, so that
1123 * we can later determine whether the run has grown.
1125 $runlength = $i - $start;
1128 * Move the changed region back, so long as the
1129 * previous unchanged line matches the last changed one.
1130 * This merges with previous changed regions.
1132 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1133 $changed[--$start] = 1;
1134 $changed[--$i] = false;
1135 while ($start > 0 && $changed[$start - 1])
1137 USE_ASSERTS
&& assert('$j > 0');
1138 while ($other_changed[--$j])
1140 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1144 * Set CORRESPONDING to the end of the changed run, at the last
1145 * point where it corresponds to a changed run in the other file.
1146 * CORRESPONDING == LEN means no such point has been found.
1148 $corresponding = $j < $other_len ?
$i : $len;
1151 * Move the changed region forward, so long as the
1152 * first changed line matches the following unchanged one.
1153 * This merges with following changed regions.
1154 * Do this second, so that if there are no merges,
1155 * the changed region is moved forward as far as possible.
1157 while ($i < $len && $lines[$start] == $lines[$i]) {
1158 $changed[$start++
] = false;
1160 while ($i < $len && $changed[$i])
1163 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1165 if ($j < $other_len && $other_changed[$j]) {
1166 $corresponding = $i;
1167 while ($j < $other_len && $other_changed[$j])
1171 } while ($runlength != $i - $start);
1174 * If possible, move the fully-merged run of changes
1175 * back to a corresponding run in the other file.
1177 while ($corresponding < $i) {
1178 $changed[--$start] = 1;
1180 USE_ASSERTS
&& assert('$j > 0');
1181 while ($other_changed[--$j])
1183 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1186 wfProfileOut( $fname );
1191 * Class representing a 'diff' between two sequences of strings.
1194 * @addtogroup DifferenceEngine
1202 * Computes diff between sequences of strings.
1204 * @param $from_lines array An array of strings.
1205 * (Typically these are lines from a file.)
1206 * @param $to_lines array An array of strings.
1208 function Diff($from_lines, $to_lines) {
1209 $eng = new _DiffEngine
;
1210 $this->edits
= $eng->diff($from_lines, $to_lines);
1211 //$this->_check($from_lines, $to_lines);
1215 * Compute reversed Diff.
1219 * $diff = new Diff($lines1, $lines2);
1220 * $rev = $diff->reverse();
1221 * @return object A Diff object representing the inverse of the
1224 function reverse () {
1226 $rev->edits
= array();
1227 foreach ($this->edits
as $edit) {
1228 $rev->edits
[] = $edit->reverse();
1234 * Check for empty diff.
1236 * @return bool True iff two sequences were identical.
1238 function isEmpty () {
1239 foreach ($this->edits
as $edit) {
1240 if ($edit->type
!= 'copy')
1247 * Compute the length of the Longest Common Subsequence (LCS).
1249 * This is mostly for diagnostic purposed.
1251 * @return int The length of the LCS.
1255 foreach ($this->edits
as $edit) {
1256 if ($edit->type
== 'copy')
1257 $lcs +
= sizeof($edit->orig
);
1263 * Get the original set of lines.
1265 * This reconstructs the $from_lines parameter passed to the
1268 * @return array The original sequence of strings.
1273 foreach ($this->edits
as $edit) {
1275 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1281 * Get the closing set of lines.
1283 * This reconstructs the $to_lines parameter passed to the
1286 * @return array The sequence of strings.
1288 function closing() {
1291 foreach ($this->edits
as $edit) {
1293 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1299 * Check a Diff for validity.
1301 * This is here only for debugging purposes.
1303 function _check ($from_lines, $to_lines) {
1304 $fname = 'Diff::_check';
1305 wfProfileIn( $fname );
1306 if (serialize($from_lines) != serialize($this->orig()))
1307 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1308 if (serialize($to_lines) != serialize($this->closing()))
1309 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1311 $rev = $this->reverse();
1312 if (serialize($to_lines) != serialize($rev->orig()))
1313 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1314 if (serialize($from_lines) != serialize($rev->closing()))
1315 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1319 foreach ($this->edits
as $edit) {
1320 if ( $prevtype == $edit->type
)
1321 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1322 $prevtype = $edit->type
;
1325 $lcs = $this->lcs();
1326 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1327 wfProfileOut( $fname );
1335 * @addtogroup DifferenceEngine
1337 class MappedDiff
extends Diff
1342 * Computes diff between sequences of strings.
1344 * This can be used to compute things like
1345 * case-insensitve diffs, or diffs which ignore
1346 * changes in white-space.
1348 * @param $from_lines array An array of strings.
1349 * (Typically these are lines from a file.)
1351 * @param $to_lines array An array of strings.
1353 * @param $mapped_from_lines array This array should
1354 * have the same size number of elements as $from_lines.
1355 * The elements in $mapped_from_lines and
1356 * $mapped_to_lines are what is actually compared
1357 * when computing the diff.
1359 * @param $mapped_to_lines array This array should
1360 * have the same number of elements as $to_lines.
1362 function MappedDiff($from_lines, $to_lines,
1363 $mapped_from_lines, $mapped_to_lines) {
1364 $fname = 'MappedDiff::MappedDiff';
1365 wfProfileIn( $fname );
1367 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1368 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1370 $this->Diff($mapped_from_lines, $mapped_to_lines);
1373 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1374 $orig = &$this->edits
[$i]->orig
;
1375 if (is_array($orig)) {
1376 $orig = array_slice($from_lines, $xi, sizeof($orig));
1377 $xi +
= sizeof($orig);
1380 $closing = &$this->edits
[$i]->closing
;
1381 if (is_array($closing)) {
1382 $closing = array_slice($to_lines, $yi, sizeof($closing));
1383 $yi +
= sizeof($closing);
1386 wfProfileOut( $fname );
1391 * A class to format Diffs
1393 * This class formats the diff in classic diff format.
1394 * It is intended that this class be customized via inheritance,
1395 * to obtain fancier outputs.
1398 * @addtogroup DifferenceEngine
1403 * Number of leading context "lines" to preserve.
1405 * This should be left at zero for this class, but subclasses
1406 * may want to set this to other values.
1408 var $leading_context_lines = 0;
1411 * Number of trailing context "lines" to preserve.
1413 * This should be left at zero for this class, but subclasses
1414 * may want to set this to other values.
1416 var $trailing_context_lines = 0;
1421 * @param $diff object A Diff object.
1422 * @return string The formatted output.
1424 function format($diff) {
1425 $fname = 'DiffFormatter::format';
1426 wfProfileIn( $fname );
1432 $nlead = $this->leading_context_lines
;
1433 $ntrail = $this->trailing_context_lines
;
1435 $this->_start_diff();
1437 foreach ($diff->edits
as $edit) {
1438 if ($edit->type
== 'copy') {
1439 if (is_array($block)) {
1440 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1445 $context = array_slice($edit->orig
, 0, $ntrail);
1446 $block[] = new _DiffOp_Copy($context);
1448 $this->_block($x0, $ntrail +
$xi - $x0,
1449 $y0, $ntrail +
$yi - $y0,
1454 $context = $edit->orig
;
1457 if (! is_array($block)) {
1458 $context = array_slice($context, sizeof($context) - $nlead);
1459 $x0 = $xi - sizeof($context);
1460 $y0 = $yi - sizeof($context);
1463 $block[] = new _DiffOp_Copy($context);
1469 $xi +
= sizeof($edit->orig
);
1471 $yi +
= sizeof($edit->closing
);
1474 if (is_array($block))
1475 $this->_block($x0, $xi - $x0,
1479 $end = $this->_end_diff();
1480 wfProfileOut( $fname );
1484 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1485 $fname = 'DiffFormatter::_block';
1486 wfProfileIn( $fname );
1487 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1488 foreach ($edits as $edit) {
1489 if ($edit->type
== 'copy')
1490 $this->_context($edit->orig
);
1491 elseif ($edit->type
== 'add')
1492 $this->_added($edit->closing
);
1493 elseif ($edit->type
== 'delete')
1494 $this->_deleted($edit->orig
);
1495 elseif ($edit->type
== 'change')
1496 $this->_changed($edit->orig
, $edit->closing
);
1498 trigger_error('Unknown edit type', E_USER_ERROR
);
1500 $this->_end_block();
1501 wfProfileOut( $fname );
1504 function _start_diff() {
1508 function _end_diff() {
1509 $val = ob_get_contents();
1514 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1516 $xbeg .= "," . ($xbeg +
$xlen - 1);
1518 $ybeg .= "," . ($ybeg +
$ylen - 1);
1520 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1523 function _start_block($header) {
1527 function _end_block() {
1530 function _lines($lines, $prefix = ' ') {
1531 foreach ($lines as $line)
1532 echo "$prefix $line\n";
1535 function _context($lines) {
1536 $this->_lines($lines);
1539 function _added($lines) {
1540 $this->_lines($lines, '>');
1542 function _deleted($lines) {
1543 $this->_lines($lines, '<');
1546 function _changed($orig, $closing) {
1547 $this->_deleted($orig);
1549 $this->_added($closing);
1555 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1559 define('NBSP', ' '); // iso-8859-x non-breaking space.
1564 * @addtogroup DifferenceEngine
1566 class _HWLDF_WordAccumulator
{
1567 function _HWLDF_WordAccumulator () {
1568 $this->_lines
= array();
1574 function _flushGroup ($new_tag) {
1575 if ($this->_group
!== '') {
1576 if ($this->_tag
== 'ins')
1577 $this->_line
.= '<ins class="diffchange">' .
1578 htmlspecialchars ( $this->_group
) . '</ins>';
1579 elseif ($this->_tag
== 'del')
1580 $this->_line
.= '<del class="diffchange">' .
1581 htmlspecialchars ( $this->_group
) . '</del>';
1583 $this->_line
.= htmlspecialchars ( $this->_group
);
1586 $this->_tag
= $new_tag;
1589 function _flushLine ($new_tag) {
1590 $this->_flushGroup($new_tag);
1591 if ($this->_line
!= '')
1592 array_push ( $this->_lines
, $this->_line
);
1594 # make empty lines visible by inserting an NBSP
1595 array_push ( $this->_lines
, NBSP
);
1599 function addWords ($words, $tag = '') {
1600 if ($tag != $this->_tag
)
1601 $this->_flushGroup($tag);
1603 foreach ($words as $word) {
1604 // new-line should only come as first char of word.
1607 if ($word[0] == "\n") {
1608 $this->_flushLine($tag);
1609 $word = substr($word, 1);
1611 assert(!strstr($word, "\n"));
1612 $this->_group
.= $word;
1616 function getLines() {
1617 $this->_flushLine('~done');
1618 return $this->_lines
;
1625 * @addtogroup DifferenceEngine
1627 class WordLevelDiff
extends MappedDiff
1629 const MAX_LINE_LENGTH
= 10000;
1631 function WordLevelDiff ($orig_lines, $closing_lines) {
1632 $fname = 'WordLevelDiff::WordLevelDiff';
1633 wfProfileIn( $fname );
1635 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1636 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1638 $this->MappedDiff($orig_words, $closing_words,
1639 $orig_stripped, $closing_stripped);
1640 wfProfileOut( $fname );
1643 function _split($lines) {
1644 $fname = 'WordLevelDiff::_split';
1645 wfProfileIn( $fname );
1648 $stripped = array();
1650 foreach ( $lines as $line ) {
1651 # If the line is too long, just pretend the entire line is one big word
1652 # This prevents resource exhaustion problems
1659 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1661 $stripped[] = $line;
1664 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1667 $words = array_merge( $words, $m[0] );
1668 $stripped = array_merge( $stripped, $m[1] );
1672 wfProfileOut( $fname );
1673 return array($words, $stripped);
1677 $fname = 'WordLevelDiff::orig';
1678 wfProfileIn( $fname );
1679 $orig = new _HWLDF_WordAccumulator
;
1681 foreach ($this->edits
as $edit) {
1682 if ($edit->type
== 'copy')
1683 $orig->addWords($edit->orig
);
1684 elseif ($edit->orig
)
1685 $orig->addWords($edit->orig
, 'del');
1687 $lines = $orig->getLines();
1688 wfProfileOut( $fname );
1692 function closing () {
1693 $fname = 'WordLevelDiff::closing';
1694 wfProfileIn( $fname );
1695 $closing = new _HWLDF_WordAccumulator
;
1697 foreach ($this->edits
as $edit) {
1698 if ($edit->type
== 'copy')
1699 $closing->addWords($edit->closing
);
1700 elseif ($edit->closing
)
1701 $closing->addWords($edit->closing
, 'ins');
1703 $lines = $closing->getLines();
1704 wfProfileOut( $fname );
1710 * Wikipedia Table style diff formatter.
1713 * @addtogroup DifferenceEngine
1715 class TableDiffFormatter
extends DiffFormatter
1717 function TableDiffFormatter() {
1718 $this->leading_context_lines
= 2;
1719 $this->trailing_context_lines
= 2;
1722 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1723 $r = '<tr><td colspan="2" align="left"><strong><!--LINE '.$xbeg."--></strong></td>\n" .
1724 '<td colspan="2" align="left"><strong><!--LINE '.$ybeg."--></strong></td></tr>\n";
1728 function _start_block( $header ) {
1732 function _end_block() {
1735 function _lines( $lines, $prefix=' ', $color='white' ) {
1738 # HTML-escape parameter before calling this
1739 function addedLine( $line ) {
1740 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1743 # HTML-escape parameter before calling this
1744 function deletedLine( $line ) {
1745 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1748 # HTML-escape parameter before calling this
1749 function contextLine( $line ) {
1750 return "<td> </td><td class='diff-context'>{$line}</td>";
1753 function emptyLine() {
1754 return '<td colspan="2"> </td>';
1757 function _added( $lines ) {
1758 foreach ($lines as $line) {
1759 echo '<tr>' . $this->emptyLine() .
1760 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1764 function _deleted($lines) {
1765 foreach ($lines as $line) {
1766 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1767 $this->emptyLine() . "</tr>\n";
1771 function _context( $lines ) {
1772 foreach ($lines as $line) {
1774 $this->contextLine( htmlspecialchars ( $line ) ) .
1775 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1779 function _changed( $orig, $closing ) {
1780 $fname = 'TableDiffFormatter::_changed';
1781 wfProfileIn( $fname );
1783 $diff = new WordLevelDiff( $orig, $closing );
1784 $del = $diff->orig();
1785 $add = $diff->closing();
1787 # Notice that WordLevelDiff returns HTML-escaped output.
1788 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1790 while ( $line = array_shift( $del ) ) {
1791 $aline = array_shift( $add );
1792 echo '<tr>' . $this->deletedLine( $line ) .
1793 $this->addedLine( $aline ) . "</tr>\n";
1795 foreach ($add as $line) { # If any leftovers
1796 echo '<tr>' . $this->emptyLine() .
1797 $this->addedLine( $line ) . "</tr>\n";
1799 wfProfileOut( $fname );