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->addStyle( 'common/diff.css' );
100 $wgOut->setArticleFlag( false );
101 if ( ! $this->loadRevisionData() ) {
102 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
103 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
104 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
105 $wgOut->addWikitext( $mtext );
106 wfProfileOut( $fname );
110 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
112 if ( $this->mNewRev
->isCurrent() ) {
113 $wgOut->setArticleFlag( true );
116 # mOldid is false if the difference engine is called with a "vague" query for
117 # a diff between a version V and its previous version V' AND the version V
118 # is the first version of that article. In that case, V' does not exist.
119 if ( $this->mOldid
=== false ) {
120 $this->showFirstRevision();
121 $this->renderNewRevision(); // should we respect $diffOnly here or not?
122 wfProfileOut( $fname );
126 $wgOut->suppressQuickbar();
128 $oldTitle = $this->mOldPage
->getPrefixedText();
129 $newTitle = $this->mNewPage
->getPrefixedText();
130 if( $oldTitle == $newTitle ) {
131 $wgOut->setPageTitle( $newTitle );
133 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
135 $wgOut->setSubtitle( wfMsg( 'difference' ) );
136 $wgOut->setRobotpolicy( 'noindex,nofollow' );
138 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
139 $wgOut->loginToUse();
141 wfProfileOut( $fname );
145 $sk = $wgUser->getSkin();
147 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
148 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
152 if( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isAllowed( 'patrol' ) ) {
153 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
158 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
159 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
160 if ( $this->mNewRev
->isCurrent() ) {
161 $nextlink = ' ';
163 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
164 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
170 if ($this->mOldRev
->mMinorEdit
== 1) {
171 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
172 wfMsg( 'minoreditletter') ) . ' ';
175 if ($this->mNewRev
->mMinorEdit
== 1) {
176 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
177 wfMsg( 'minoreditletter') ) . ' ';
180 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />" .
181 $sk->revUserTools( $this->mOldRev
) . "<br />" .
182 $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly ) . "<br />" .
184 $newHeader = "<strong>{$this->mNewtitle}</strong><br />" .
185 $sk->revUserTools( $this->mNewRev
) . " $rollback<br />" .
186 $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly ) . "<br />" .
189 $this->showDiff( $oldHeader, $newHeader );
192 $this->renderNewRevision();
194 wfProfileOut( $fname );
198 * Show the new revision of the page.
200 function renderNewRevision() {
202 $fname = 'DifferenceEngine::renderNewRevision';
203 wfProfileIn( $fname );
205 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
206 #add deleted rev tag if needed
207 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
208 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
211 if( !$this->mNewRev
->isCurrent() ) {
212 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
215 $this->loadNewText();
216 if( is_object( $this->mNewRev
) ) {
217 $wgOut->setRevisionId( $this->mNewRev
->getId() );
220 $wgOut->addWikiTextTidy( $this->mNewtext
);
222 if( !$this->mNewRev
->isCurrent() ) {
223 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
226 wfProfileOut( $fname );
230 * Show the first revision of an article. Uses normal diff headers in
231 * contrast to normal "old revision" display style.
233 function showFirstRevision() {
234 global $wgOut, $wgUser;
236 $fname = 'DifferenceEngine::showFirstRevision';
237 wfProfileIn( $fname );
239 # Get article text from the DB
241 if ( ! $this->loadNewText() ) {
242 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
244 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
245 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
246 $wgOut->addWikitext( $mtext );
247 wfProfileOut( $fname );
250 if ( $this->mNewRev
->isCurrent() ) {
251 $wgOut->setArticleFlag( true );
254 # Check if user is allowed to look at this page. If not, bail out.
256 if ( !( $this->mTitle
->userCanRead() ) ) {
257 $wgOut->loginToUse();
259 wfProfileOut( $fname );
263 # Prepare the header box
265 $sk = $wgUser->getSkin();
267 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
268 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
269 $sk->revUserTools( $this->mNewRev
) . "<br />" .
270 $sk->revComment( $this->mNewRev
) . "<br />" .
271 $nextlink . "</div>\n";
273 $wgOut->addHTML( $header );
275 $wgOut->setSubtitle( wfMsg( 'difference' ) );
276 $wgOut->setRobotpolicy( 'noindex,nofollow' );
278 wfProfileOut( $fname );
282 * Get the diff text, send it to $wgOut
283 * Returns false if the diff could not be generated, otherwise returns true
285 function showDiff( $otitle, $ntitle ) {
287 $diff = $this->getDiff( $otitle, $ntitle );
288 if ( $diff === false ) {
289 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
292 $wgOut->addHTML( $diff );
298 * Get diff table, including header
299 * Note that the interface has changed, it's no longer static.
300 * Returns false on error
302 function getDiff( $otitle, $ntitle ) {
303 $body = $this->getDiffBody();
304 if ( $body === false ) {
307 $multi = $this->getMultiNotice();
308 return $this->addHeader( $body, $otitle, $ntitle, $multi );
313 * Get the diff table body, without header
315 * Returns false on error
317 function getDiffBody() {
319 $fname = 'DifferenceEngine::getDiffBody';
320 wfProfileIn( $fname );
324 if ( $this->mOldid
&& $this->mNewid
) {
326 $key = wfMemcKey( 'diff', 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
327 $difftext = $wgMemc->get( $key );
329 wfIncrStats( 'diff_cache_hit' );
330 $difftext = $this->localiseLineNumbers( $difftext );
331 $difftext .= "\n<!-- diff cache key $key -->\n";
332 wfProfileOut( $fname );
337 #loadtext is permission safe, this just clears out the diff
338 if ( !$this->loadText() ) {
339 wfProfileOut( $fname );
341 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
343 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
347 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
349 // Save to cache for 7 days
350 if ( $key !== false && $difftext !== false ) {
351 wfIncrStats( 'diff_cache_miss' );
352 $wgMemc->set( $key, $difftext, 7*86400 );
354 wfIncrStats( 'diff_uncacheable' );
356 // Replace line numbers with the text in the user's language
357 if ( $difftext !== false ) {
358 $difftext = $this->localiseLineNumbers( $difftext );
360 wfProfileOut( $fname );
365 * Generate a diff, no caching
366 * $otext and $ntext must be already segmented
368 function generateDiffBody( $otext, $ntext ) {
369 global $wgExternalDiffEngine, $wgContLang;
370 $fname = 'DifferenceEngine::generateDiffBody';
372 $otext = str_replace( "\r\n", "\n", $otext );
373 $ntext = str_replace( "\r\n", "\n", $ntext );
375 if ( $wgExternalDiffEngine == 'wikidiff' ) {
376 # For historical reasons, external diff engine expects
377 # input text to be HTML-escaped already
378 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
379 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
380 if( !function_exists( 'wikidiff_do_diff' ) ) {
381 dl('php_wikidiff.so');
383 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
386 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
387 # Better external diff engine, the 2 may some day be dropped
388 # This one does the escaping and segmenting itself
389 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
390 wfProfileIn( "$fname-dl" );
391 @dl
('php_wikidiff2.so');
392 wfProfileOut( "$fname-dl" );
394 if ( function_exists( 'wikidiff2_do_diff' ) ) {
395 wfProfileIn( 'wikidiff2_do_diff' );
396 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
397 wfProfileOut( 'wikidiff2_do_diff' );
401 if ( $wgExternalDiffEngine !== false ) {
403 global $wgTmpDirectory;
404 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
405 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
407 $tempFile1 = fopen( $tempName1, "w" );
409 wfProfileOut( $fname );
412 $tempFile2 = fopen( $tempName2, "w" );
414 wfProfileOut( $fname );
417 fwrite( $tempFile1, $otext );
418 fwrite( $tempFile2, $ntext );
419 fclose( $tempFile1 );
420 fclose( $tempFile2 );
421 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
422 wfProfileIn( "$fname-shellexec" );
423 $difftext = wfShellExec( $cmd );
424 wfProfileOut( "$fname-shellexec" );
425 unlink( $tempName1 );
426 unlink( $tempName2 );
431 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
432 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
433 $diffs = new Diff( $ota, $nta );
434 $formatter = new TableDiffFormatter();
435 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
440 * Replace line numbers with the text in the user's language
442 function localiseLineNumbers( $text ) {
443 return preg_replace_callback( '/<!--LINE (\d+)-->/',
444 array( &$this, 'localiseLineNumbersCb' ), $text );
447 function localiseLineNumbersCb( $matches ) {
449 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
454 * If there are revisions between the ones being compared, return a note saying so.
456 function getMultiNotice() {
457 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
460 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
461 // Comparing two different pages? Count would be meaningless.
465 $oldid = $this->mOldRev
->getId();
466 $newid = $this->mNewRev
->getId();
467 if ( $oldid > $newid ) {
468 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
471 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
475 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
480 * Add the header to a diff body
482 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
485 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
486 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
488 if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
489 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
493 <col class='diff-marker' />
494 <col class='diff-content' />
495 <col class='diff-marker' />
496 <col class='diff-content' />
498 <td colspan='2' class='diff-otitle'>{$otitle}</td>
499 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
504 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
506 return $header . $diff . "</table>";
510 * Use specified text instead of loading from the database
512 function setText( $oldText, $newText ) {
513 $this->mOldtext
= $oldText;
514 $this->mNewtext
= $newText;
515 $this->mTextLoaded
= 2;
519 * Load revision metadata for the specified articles. If newid is 0, then compare
520 * the old article in oldid to the current article; if oldid is 0, then
521 * compare the current article to the immediately previous one (ignoring the
524 * If oldid is false, leave the corresponding revision object set
525 * to false. This is impossible via ordinary user input, and is provided for
528 function loadRevisionData() {
530 if ( $this->mRevisionsLoaded
) {
533 // Whether it succeeds or fails, we don't want to try again
534 $this->mRevisionsLoaded
= true;
537 // Load the new revision object
538 if( $this->mNewid
) {
539 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
541 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
544 if( is_null( $this->mNewRev
) ) {
548 // Set assorted variables
549 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
550 $this->mNewPage
= $this->mNewRev
->getTitle();
551 if( $this->mNewRev
->isCurrent() ) {
552 $newLink = $this->mNewPage
->escapeLocalUrl();
553 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
554 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
556 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
557 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
560 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
561 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
562 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
564 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
565 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
568 // Load the old revision object
569 $this->mOldRev
= false;
570 if( $this->mOldid
) {
571 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
572 } elseif ( $this->mOldid
=== 0 ) {
573 $rev = $this->mNewRev
->getPrevious();
575 $this->mOldid
= $rev->getId();
576 $this->mOldRev
= $rev;
578 // No previous revision; mark to show as first-version only.
579 $this->mOldid
= false;
580 $this->mOldRev
= false;
582 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
584 if( is_null( $this->mOldRev
) ) {
588 if ( $this->mOldRev
) {
589 $this->mOldPage
= $this->mOldRev
->getTitle();
591 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
592 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
593 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
594 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
595 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
596 //now that we considered old rev, we can make undo link (bug 8133, multi-edit undo)
597 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
598 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
605 * Load the text of the revisions, as well as revision data.
607 function loadText() {
608 if ( $this->mTextLoaded
== 2 ) {
611 // Whether it succeeds or fails, we don't want to try again
612 $this->mTextLoaded
= 2;
615 if ( !$this->loadRevisionData() ) {
618 if ( $this->mOldRev
) {
619 // FIXME: permission tests
620 $this->mOldtext
= $this->mOldRev
->revText();
621 if ( $this->mOldtext
=== false ) {
625 if ( $this->mNewRev
) {
626 $this->mNewtext
= $this->mNewRev
->revText();
627 if ( $this->mNewtext
=== false ) {
635 * Load the text of the new revision, not the old one
637 function loadNewText() {
638 if ( $this->mTextLoaded
>= 1 ) {
641 $this->mTextLoaded
= 1;
643 if ( !$this->loadRevisionData() ) {
646 $this->mNewtext
= $this->mNewRev
->getText();
653 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
655 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
656 // You may copy this code freely under the conditions of the GPL.
659 define('USE_ASSERTS', function_exists('assert'));
664 * @addtogroup DifferenceEngine
672 trigger_error('pure virtual', E_USER_ERROR
);
676 return $this->orig ?
sizeof($this->orig
) : 0;
679 function nclosing() {
680 return $this->closing ?
sizeof($this->closing
) : 0;
687 * @addtogroup DifferenceEngine
689 class _DiffOp_Copy
extends _DiffOp
{
692 function _DiffOp_Copy ($orig, $closing = false) {
693 if (!is_array($closing))
696 $this->closing
= $closing;
700 return new _DiffOp_Copy($this->closing
, $this->orig
);
707 * @addtogroup DifferenceEngine
709 class _DiffOp_Delete
extends _DiffOp
{
710 var $type = 'delete';
712 function _DiffOp_Delete ($lines) {
713 $this->orig
= $lines;
714 $this->closing
= false;
718 return new _DiffOp_Add($this->orig
);
725 * @addtogroup DifferenceEngine
727 class _DiffOp_Add
extends _DiffOp
{
730 function _DiffOp_Add ($lines) {
731 $this->closing
= $lines;
736 return new _DiffOp_Delete($this->closing
);
743 * @addtogroup DifferenceEngine
745 class _DiffOp_Change
extends _DiffOp
{
746 var $type = 'change';
748 function _DiffOp_Change ($orig, $closing) {
750 $this->closing
= $closing;
754 return new _DiffOp_Change($this->closing
, $this->orig
);
760 * Class used internally by Diff to actually compute the diffs.
762 * The algorithm used here is mostly lifted from the perl module
763 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
764 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
766 * More ideas are taken from:
767 * http://www.ics.uci.edu/~eppstein/161/960229.html
769 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
770 * diffutils-2.7, which can be found at:
771 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
773 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
776 * Line length limits for robustness added by Tim Starling, 2005-08-31
778 * @author Geoffrey T. Dairiki, Tim Starling
780 * @addtogroup DifferenceEngine
784 const MAX_XREF_LENGTH
= 10000;
786 function diff ($from_lines, $to_lines) {
787 $fname = '_DiffEngine::diff';
788 wfProfileIn( $fname );
790 $n_from = sizeof($from_lines);
791 $n_to = sizeof($to_lines);
793 $this->xchanged
= $this->ychanged
= array();
794 $this->xv
= $this->yv
= array();
795 $this->xind
= $this->yind
= array();
797 unset($this->in_seq
);
800 // Skip leading common lines.
801 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
802 if ($from_lines[$skip] !== $to_lines[$skip])
804 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
806 // Skip trailing common lines.
807 $xi = $n_from; $yi = $n_to;
808 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
809 if ($from_lines[$xi] !== $to_lines[$yi])
811 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
814 // Ignore lines which do not exist in both files.
815 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
816 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
819 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
820 $line = $to_lines[$yi];
821 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
823 $yhash[$this->_line_hash($line)] = 1;
827 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
828 $line = $from_lines[$xi];
829 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
836 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
838 // Merge edits when possible
839 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
840 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
842 // Compute the edit operations.
845 while ($xi < $n_from ||
$yi < $n_to) {
846 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
847 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
849 // Skip matching "snake".
851 while ( $xi < $n_from && $yi < $n_to
852 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
853 $copy[] = $from_lines[$xi++
];
857 $edits[] = new _DiffOp_Copy($copy);
859 // Find deletes & adds.
861 while ($xi < $n_from && $this->xchanged
[$xi])
862 $delete[] = $from_lines[$xi++
];
865 while ($yi < $n_to && $this->ychanged
[$yi])
866 $add[] = $to_lines[$yi++
];
869 $edits[] = new _DiffOp_Change($delete, $add);
871 $edits[] = new _DiffOp_Delete($delete);
873 $edits[] = new _DiffOp_Add($add);
875 wfProfileOut( $fname );
880 * Returns the whole line if it's small enough, or the MD5 hash otherwise
882 function _line_hash( $line ) {
883 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
891 /* Divide the Largest Common Subsequence (LCS) of the sequences
892 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
895 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
896 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
897 * sub sequences. The first sub-sequence is contained in [X0, X1),
898 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
899 * that (X0, Y0) == (XOFF, YOFF) and
900 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
902 * This function assumes that the first lines of the specified portions
903 * of the two files do not match, and likewise that the last lines do not
904 * match. The caller must trim matching lines from the beginning and end
905 * of the portions it is going to specify.
907 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
908 $fname = '_DiffEngine::_diag';
909 wfProfileIn( $fname );
912 if ($xlim - $xoff > $ylim - $yoff) {
913 // Things seems faster (I'm not sure I understand why)
914 // when the shortest sequence in X.
916 list ($xoff, $xlim, $yoff, $ylim)
917 = array( $yoff, $ylim, $xoff, $xlim);
921 for ($i = $ylim - 1; $i >= $yoff; $i--)
922 $ymatches[$this->xv
[$i]][] = $i;
924 for ($i = $ylim - 1; $i >= $yoff; $i--)
925 $ymatches[$this->yv
[$i]][] = $i;
928 $this->seq
[0]= $yoff - 1;
929 $this->in_seq
= array();
932 $numer = $xlim - $xoff +
$nchunks - 1;
934 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
935 wfProfileIn( "$fname-chunk" );
937 for ($i = 0; $i <= $this->lcs
; $i++
)
938 $ymids[$i][$chunk-1] = $this->seq
[$i];
940 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
941 for ( ; $x < $x1; $x++
) {
942 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
943 if (empty($ymatches[$line]))
945 $matches = $ymatches[$line];
947 while (list ($junk, $y) = each($matches))
948 if (empty($this->in_seq
[$y])) {
949 $k = $this->_lcs_pos($y);
950 USE_ASSERTS
&& assert($k > 0);
951 $ymids[$k] = $ymids[$k-1];
954 while (list ( /* $junk */, $y) = each($matches)) {
955 if ($y > $this->seq
[$k-1]) {
956 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
957 // Optimization: this is a common case:
958 // next match is just replacing previous match.
959 $this->in_seq
[$this->seq
[$k]] = false;
961 $this->in_seq
[$y] = 1;
962 } else if (empty($this->in_seq
[$y])) {
963 $k = $this->_lcs_pos($y);
964 USE_ASSERTS
&& assert($k > 0);
965 $ymids[$k] = $ymids[$k-1];
969 wfProfileOut( "$fname-chunk" );
972 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
973 $ymid = $ymids[$this->lcs
];
974 for ($n = 0; $n < $nchunks - 1; $n++
) {
975 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
977 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
979 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
981 wfProfileOut( $fname );
982 return array($this->lcs
, $seps);
985 function _lcs_pos ($ypos) {
986 $fname = '_DiffEngine::_lcs_pos';
987 wfProfileIn( $fname );
990 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
991 $this->seq
[++
$this->lcs
] = $ypos;
992 $this->in_seq
[$ypos] = 1;
993 wfProfileOut( $fname );
998 while ($beg < $end) {
999 $mid = (int)(($beg +
$end) / 2);
1000 if ( $ypos > $this->seq
[$mid] )
1006 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1008 $this->in_seq
[$this->seq
[$end]] = false;
1009 $this->seq
[$end] = $ypos;
1010 $this->in_seq
[$ypos] = 1;
1011 wfProfileOut( $fname );
1015 /* Find LCS of two sequences.
1017 * The results are recorded in the vectors $this->{x,y}changed[], by
1018 * storing a 1 in the element for each line that is an insertion
1019 * or deletion (ie. is not in the LCS).
1021 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1023 * Note that XLIM, YLIM are exclusive bounds.
1024 * All line numbers are origin-0 and discarded lines are not counted.
1026 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1027 $fname = '_DiffEngine::_compareseq';
1028 wfProfileIn( $fname );
1030 // Slide down the bottom initial diagonal.
1031 while ($xoff < $xlim && $yoff < $ylim
1032 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1037 // Slide up the top initial diagonal.
1038 while ($xlim > $xoff && $ylim > $yoff
1039 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1044 if ($xoff == $xlim ||
$yoff == $ylim)
1047 // This is ad hoc but seems to work well.
1048 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1049 //$nchunks = max(2,min(8,(int)$nchunks));
1050 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1052 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1056 // X and Y sequences have no common subsequence:
1057 // mark all changed.
1058 while ($yoff < $ylim)
1059 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1060 while ($xoff < $xlim)
1061 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1063 // Use the partitions to split this problem into subproblems.
1066 while ($pt2 = next($seps)) {
1067 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1071 wfProfileOut( $fname );
1074 /* Adjust inserts/deletes of identical lines to join changes
1075 * as much as possible.
1077 * We do something when a run of changed lines include a
1078 * line at one end and has an excluded, identical line at the other.
1079 * We are free to choose which identical line is included.
1080 * `compareseq' usually chooses the one at the beginning,
1081 * but usually it is cleaner to consider the following identical line
1082 * to be the "change".
1084 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1086 function _shift_boundaries ($lines, &$changed, $other_changed) {
1087 $fname = '_DiffEngine::_shift_boundaries';
1088 wfProfileIn( $fname );
1092 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1093 $len = sizeof($lines);
1094 $other_len = sizeof($other_changed);
1098 * Scan forwards to find beginning of another run of changes.
1099 * Also keep track of the corresponding point in the other file.
1101 * Throughout this code, $i and $j are adjusted together so that
1102 * the first $i elements of $changed and the first $j elements
1103 * of $other_changed both contain the same number of zeros
1104 * (unchanged lines).
1105 * Furthermore, $j is always kept so that $j == $other_len or
1106 * $other_changed[$j] == false.
1108 while ($j < $other_len && $other_changed[$j])
1111 while ($i < $len && ! $changed[$i]) {
1112 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1114 while ($j < $other_len && $other_changed[$j])
1123 // Find the end of this run of changes.
1124 while (++
$i < $len && $changed[$i])
1129 * Record the length of this run of changes, so that
1130 * we can later determine whether the run has grown.
1132 $runlength = $i - $start;
1135 * Move the changed region back, so long as the
1136 * previous unchanged line matches the last changed one.
1137 * This merges with previous changed regions.
1139 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1140 $changed[--$start] = 1;
1141 $changed[--$i] = false;
1142 while ($start > 0 && $changed[$start - 1])
1144 USE_ASSERTS
&& assert('$j > 0');
1145 while ($other_changed[--$j])
1147 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1151 * Set CORRESPONDING to the end of the changed run, at the last
1152 * point where it corresponds to a changed run in the other file.
1153 * CORRESPONDING == LEN means no such point has been found.
1155 $corresponding = $j < $other_len ?
$i : $len;
1158 * Move the changed region forward, so long as the
1159 * first changed line matches the following unchanged one.
1160 * This merges with following changed regions.
1161 * Do this second, so that if there are no merges,
1162 * the changed region is moved forward as far as possible.
1164 while ($i < $len && $lines[$start] == $lines[$i]) {
1165 $changed[$start++
] = false;
1167 while ($i < $len && $changed[$i])
1170 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1172 if ($j < $other_len && $other_changed[$j]) {
1173 $corresponding = $i;
1174 while ($j < $other_len && $other_changed[$j])
1178 } while ($runlength != $i - $start);
1181 * If possible, move the fully-merged run of changes
1182 * back to a corresponding run in the other file.
1184 while ($corresponding < $i) {
1185 $changed[--$start] = 1;
1187 USE_ASSERTS
&& assert('$j > 0');
1188 while ($other_changed[--$j])
1190 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1193 wfProfileOut( $fname );
1198 * Class representing a 'diff' between two sequences of strings.
1201 * @addtogroup DifferenceEngine
1209 * Computes diff between sequences of strings.
1211 * @param $from_lines array An array of strings.
1212 * (Typically these are lines from a file.)
1213 * @param $to_lines array An array of strings.
1215 function Diff($from_lines, $to_lines) {
1216 $eng = new _DiffEngine
;
1217 $this->edits
= $eng->diff($from_lines, $to_lines);
1218 //$this->_check($from_lines, $to_lines);
1222 * Compute reversed Diff.
1226 * $diff = new Diff($lines1, $lines2);
1227 * $rev = $diff->reverse();
1228 * @return object A Diff object representing the inverse of the
1231 function reverse () {
1233 $rev->edits
= array();
1234 foreach ($this->edits
as $edit) {
1235 $rev->edits
[] = $edit->reverse();
1241 * Check for empty diff.
1243 * @return bool True iff two sequences were identical.
1245 function isEmpty () {
1246 foreach ($this->edits
as $edit) {
1247 if ($edit->type
!= 'copy')
1254 * Compute the length of the Longest Common Subsequence (LCS).
1256 * This is mostly for diagnostic purposed.
1258 * @return int The length of the LCS.
1262 foreach ($this->edits
as $edit) {
1263 if ($edit->type
== 'copy')
1264 $lcs +
= sizeof($edit->orig
);
1270 * Get the original set of lines.
1272 * This reconstructs the $from_lines parameter passed to the
1275 * @return array The original sequence of strings.
1280 foreach ($this->edits
as $edit) {
1282 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1288 * Get the closing set of lines.
1290 * This reconstructs the $to_lines parameter passed to the
1293 * @return array The sequence of strings.
1295 function closing() {
1298 foreach ($this->edits
as $edit) {
1300 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1306 * Check a Diff for validity.
1308 * This is here only for debugging purposes.
1310 function _check ($from_lines, $to_lines) {
1311 $fname = 'Diff::_check';
1312 wfProfileIn( $fname );
1313 if (serialize($from_lines) != serialize($this->orig()))
1314 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1315 if (serialize($to_lines) != serialize($this->closing()))
1316 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1318 $rev = $this->reverse();
1319 if (serialize($to_lines) != serialize($rev->orig()))
1320 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1321 if (serialize($from_lines) != serialize($rev->closing()))
1322 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1326 foreach ($this->edits
as $edit) {
1327 if ( $prevtype == $edit->type
)
1328 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1329 $prevtype = $edit->type
;
1332 $lcs = $this->lcs();
1333 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1334 wfProfileOut( $fname );
1339 * @todo document, bad name.
1341 * @addtogroup DifferenceEngine
1343 class MappedDiff
extends Diff
1348 * Computes diff between sequences of strings.
1350 * This can be used to compute things like
1351 * case-insensitve diffs, or diffs which ignore
1352 * changes in white-space.
1354 * @param $from_lines array An array of strings.
1355 * (Typically these are lines from a file.)
1357 * @param $to_lines array An array of strings.
1359 * @param $mapped_from_lines array This array should
1360 * have the same size number of elements as $from_lines.
1361 * The elements in $mapped_from_lines and
1362 * $mapped_to_lines are what is actually compared
1363 * when computing the diff.
1365 * @param $mapped_to_lines array This array should
1366 * have the same number of elements as $to_lines.
1368 function MappedDiff($from_lines, $to_lines,
1369 $mapped_from_lines, $mapped_to_lines) {
1370 $fname = 'MappedDiff::MappedDiff';
1371 wfProfileIn( $fname );
1373 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1374 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1376 $this->Diff($mapped_from_lines, $mapped_to_lines);
1379 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1380 $orig = &$this->edits
[$i]->orig
;
1381 if (is_array($orig)) {
1382 $orig = array_slice($from_lines, $xi, sizeof($orig));
1383 $xi +
= sizeof($orig);
1386 $closing = &$this->edits
[$i]->closing
;
1387 if (is_array($closing)) {
1388 $closing = array_slice($to_lines, $yi, sizeof($closing));
1389 $yi +
= sizeof($closing);
1392 wfProfileOut( $fname );
1397 * A class to format Diffs
1399 * This class formats the diff in classic diff format.
1400 * It is intended that this class be customized via inheritance,
1401 * to obtain fancier outputs.
1404 * @addtogroup DifferenceEngine
1409 * Number of leading context "lines" to preserve.
1411 * This should be left at zero for this class, but subclasses
1412 * may want to set this to other values.
1414 var $leading_context_lines = 0;
1417 * Number of trailing context "lines" to preserve.
1419 * This should be left at zero for this class, but subclasses
1420 * may want to set this to other values.
1422 var $trailing_context_lines = 0;
1427 * @param $diff object A Diff object.
1428 * @return string The formatted output.
1430 function format($diff) {
1431 $fname = 'DiffFormatter::format';
1432 wfProfileIn( $fname );
1438 $nlead = $this->leading_context_lines
;
1439 $ntrail = $this->trailing_context_lines
;
1441 $this->_start_diff();
1443 foreach ($diff->edits
as $edit) {
1444 if ($edit->type
== 'copy') {
1445 if (is_array($block)) {
1446 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1451 $context = array_slice($edit->orig
, 0, $ntrail);
1452 $block[] = new _DiffOp_Copy($context);
1454 $this->_block($x0, $ntrail +
$xi - $x0,
1455 $y0, $ntrail +
$yi - $y0,
1460 $context = $edit->orig
;
1463 if (! is_array($block)) {
1464 $context = array_slice($context, sizeof($context) - $nlead);
1465 $x0 = $xi - sizeof($context);
1466 $y0 = $yi - sizeof($context);
1469 $block[] = new _DiffOp_Copy($context);
1475 $xi +
= sizeof($edit->orig
);
1477 $yi +
= sizeof($edit->closing
);
1480 if (is_array($block))
1481 $this->_block($x0, $xi - $x0,
1485 $end = $this->_end_diff();
1486 wfProfileOut( $fname );
1490 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1491 $fname = 'DiffFormatter::_block';
1492 wfProfileIn( $fname );
1493 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1494 foreach ($edits as $edit) {
1495 if ($edit->type
== 'copy')
1496 $this->_context($edit->orig
);
1497 elseif ($edit->type
== 'add')
1498 $this->_added($edit->closing
);
1499 elseif ($edit->type
== 'delete')
1500 $this->_deleted($edit->orig
);
1501 elseif ($edit->type
== 'change')
1502 $this->_changed($edit->orig
, $edit->closing
);
1504 trigger_error('Unknown edit type', E_USER_ERROR
);
1506 $this->_end_block();
1507 wfProfileOut( $fname );
1510 function _start_diff() {
1514 function _end_diff() {
1515 $val = ob_get_contents();
1520 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1522 $xbeg .= "," . ($xbeg +
$xlen - 1);
1524 $ybeg .= "," . ($ybeg +
$ylen - 1);
1526 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1529 function _start_block($header) {
1533 function _end_block() {
1536 function _lines($lines, $prefix = ' ') {
1537 foreach ($lines as $line)
1538 echo "$prefix $line\n";
1541 function _context($lines) {
1542 $this->_lines($lines);
1545 function _added($lines) {
1546 $this->_lines($lines, '>');
1548 function _deleted($lines) {
1549 $this->_lines($lines, '<');
1552 function _changed($orig, $closing) {
1553 $this->_deleted($orig);
1555 $this->_added($closing);
1561 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1565 define('NBSP', ' '); // iso-8859-x non-breaking space.
1570 * @addtogroup DifferenceEngine
1572 class _HWLDF_WordAccumulator
{
1573 function _HWLDF_WordAccumulator () {
1574 $this->_lines
= array();
1580 function _flushGroup ($new_tag) {
1581 if ($this->_group
!== '') {
1582 if ($this->_tag
== 'ins')
1583 $this->_line
.= '<ins class="diffchange">' .
1584 htmlspecialchars ( $this->_group
) . '</ins>';
1585 elseif ($this->_tag
== 'del')
1586 $this->_line
.= '<del class="diffchange">' .
1587 htmlspecialchars ( $this->_group
) . '</del>';
1589 $this->_line
.= htmlspecialchars ( $this->_group
);
1592 $this->_tag
= $new_tag;
1595 function _flushLine ($new_tag) {
1596 $this->_flushGroup($new_tag);
1597 if ($this->_line
!= '')
1598 array_push ( $this->_lines
, $this->_line
);
1600 # make empty lines visible by inserting an NBSP
1601 array_push ( $this->_lines
, NBSP
);
1605 function addWords ($words, $tag = '') {
1606 if ($tag != $this->_tag
)
1607 $this->_flushGroup($tag);
1609 foreach ($words as $word) {
1610 // new-line should only come as first char of word.
1613 if ($word[0] == "\n") {
1614 $this->_flushLine($tag);
1615 $word = substr($word, 1);
1617 assert(!strstr($word, "\n"));
1618 $this->_group
.= $word;
1622 function getLines() {
1623 $this->_flushLine('~done');
1624 return $this->_lines
;
1631 * @addtogroup DifferenceEngine
1633 class WordLevelDiff
extends MappedDiff
1635 const MAX_LINE_LENGTH
= 10000;
1637 function WordLevelDiff ($orig_lines, $closing_lines) {
1638 $fname = 'WordLevelDiff::WordLevelDiff';
1639 wfProfileIn( $fname );
1641 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1642 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1644 $this->MappedDiff($orig_words, $closing_words,
1645 $orig_stripped, $closing_stripped);
1646 wfProfileOut( $fname );
1649 function _split($lines) {
1650 $fname = 'WordLevelDiff::_split';
1651 wfProfileIn( $fname );
1654 $stripped = array();
1656 foreach ( $lines as $line ) {
1657 # If the line is too long, just pretend the entire line is one big word
1658 # This prevents resource exhaustion problems
1665 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1667 $stripped[] = $line;
1670 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1673 $words = array_merge( $words, $m[0] );
1674 $stripped = array_merge( $stripped, $m[1] );
1678 wfProfileOut( $fname );
1679 return array($words, $stripped);
1683 $fname = 'WordLevelDiff::orig';
1684 wfProfileIn( $fname );
1685 $orig = new _HWLDF_WordAccumulator
;
1687 foreach ($this->edits
as $edit) {
1688 if ($edit->type
== 'copy')
1689 $orig->addWords($edit->orig
);
1690 elseif ($edit->orig
)
1691 $orig->addWords($edit->orig
, 'del');
1693 $lines = $orig->getLines();
1694 wfProfileOut( $fname );
1698 function closing () {
1699 $fname = 'WordLevelDiff::closing';
1700 wfProfileIn( $fname );
1701 $closing = new _HWLDF_WordAccumulator
;
1703 foreach ($this->edits
as $edit) {
1704 if ($edit->type
== 'copy')
1705 $closing->addWords($edit->closing
);
1706 elseif ($edit->closing
)
1707 $closing->addWords($edit->closing
, 'ins');
1709 $lines = $closing->getLines();
1710 wfProfileOut( $fname );
1716 * Wikipedia Table style diff formatter.
1719 * @addtogroup DifferenceEngine
1721 class TableDiffFormatter
extends DiffFormatter
1723 function TableDiffFormatter() {
1724 $this->leading_context_lines
= 2;
1725 $this->trailing_context_lines
= 2;
1728 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1729 $r = '<tr><td colspan="2" align="left"><strong><!--LINE '.$xbeg."--></strong></td>\n" .
1730 '<td colspan="2" align="left"><strong><!--LINE '.$ybeg."--></strong></td></tr>\n";
1734 function _start_block( $header ) {
1738 function _end_block() {
1741 function _lines( $lines, $prefix=' ', $color='white' ) {
1744 # HTML-escape parameter before calling this
1745 function addedLine( $line ) {
1746 return $this->wrapLine( '+', 'diff-addedline', $line );
1749 # HTML-escape parameter before calling this
1750 function deletedLine( $line ) {
1751 return $this->wrapLine( '-', 'diff-deletedline', $line );
1754 # HTML-escape parameter before calling this
1755 function contextLine( $line ) {
1756 return $this->wrapLine( ' ', 'diff-context', $line );
1759 private function wrapLine( $marker, $class, $line ) {
1760 if( $line !== '' ) {
1761 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1762 $line = "<div>$line</div>";
1764 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1767 function emptyLine() {
1768 return '<td colspan="2"> </td>';
1771 function _added( $lines ) {
1772 foreach ($lines as $line) {
1773 echo '<tr>' . $this->emptyLine() .
1774 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1778 function _deleted($lines) {
1779 foreach ($lines as $line) {
1780 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1781 $this->emptyLine() . "</tr>\n";
1785 function _context( $lines ) {
1786 foreach ($lines as $line) {
1788 $this->contextLine( htmlspecialchars ( $line ) ) .
1789 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1793 function _changed( $orig, $closing ) {
1794 $fname = 'TableDiffFormatter::_changed';
1795 wfProfileIn( $fname );
1797 $diff = new WordLevelDiff( $orig, $closing );
1798 $del = $diff->orig();
1799 $add = $diff->closing();
1801 # Notice that WordLevelDiff returns HTML-escaped output.
1802 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1804 while ( $line = array_shift( $del ) ) {
1805 $aline = array_shift( $add );
1806 echo '<tr>' . $this->deletedLine( $line ) .
1807 $this->addedLine( $aline ) . "</tr>\n";
1809 foreach ($add as $line) { # If any leftovers
1810 echo '<tr>' . $this->emptyLine() .
1811 $this->addedLine( $line ) . "</tr>\n";
1813 wfProfileOut( $fname );