4 * @todo indicate where diff.doc can be found.
5 * @addtogroup DifferenceEngine
9 * Constant to indicate diff cache compatibility.
10 * Bump this when changing the diff formatting in a way that
11 * fixes important bugs or such to force cached diff views to
14 define( 'MW_DIFF_VERSION', '1.11a' );
19 * @addtogroup DifferenceEngine
21 class DifferenceEngine
{
25 var $mOldid, $mNewid, $mTitle;
26 var $mOldtitle, $mNewtitle, $mPagetitle;
27 var $mOldtext, $mNewtext;
28 var $mOldPage, $mNewPage;
29 var $mRcidMarkPatrolled;
30 var $mOldRev, $mNewRev;
31 var $mRevisionsLoaded = false; // Have the revisions been loaded
32 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
37 * @param $titleObj Title object that the diff is associated with
38 * @param $old Integer: old ID we want to show and diff with.
39 * @param $new String: either 'prev' or 'next'.
40 * @param $rcid Integer: ??? FIXME (default 0)
42 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
43 $this->mTitle
= $titleObj;
44 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
46 if ( 'prev' === $new ) {
47 # Show diff between revision $old and the previous one.
48 # Get previous one from DB.
50 $this->mNewid
= intval($old);
52 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
54 } elseif ( 'next' === $new ) {
55 # Show diff between revision $old and the previous one.
56 # Get previous one from DB.
58 $this->mOldid
= intval($old);
59 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
60 if ( false === $this->mNewid
) {
61 # if no result, NewId points to the newest old revision. The only newer
62 # revision is cur, which is "0".
67 $this->mOldid
= intval($old);
68 $this->mNewid
= intval($new);
70 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
73 function showDiffPage( $diffOnly = false ) {
74 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
75 $fname = 'DifferenceEngine::showDiffPage';
76 wfProfileIn( $fname );
78 # If external diffs are enabled both globally and for the user,
79 # we'll use the application/x-external-editor interface to call
80 # an external diff tool like kompare, kdiff3, etc.
81 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
82 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
84 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
85 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
86 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
87 $special=$wgLang->getNsText(NS_SPECIAL
);
92 Script={$wgServer}{$wgScript}
93 Special namespace={$special}
107 $wgOut->setArticleFlag( false );
108 if ( ! $this->loadRevisionData() ) {
109 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
110 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
111 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
112 $wgOut->addWikitext( $mtext );
113 wfProfileOut( $fname );
117 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
119 if ( $this->mNewRev
->isCurrent() ) {
120 $wgOut->setArticleFlag( true );
123 # mOldid is false if the difference engine is called with a "vague" query for
124 # a diff between a version V and its previous version V' AND the version V
125 # is the first version of that article. In that case, V' does not exist.
126 if ( $this->mOldid
=== false ) {
127 $this->showFirstRevision();
128 $this->renderNewRevision(); // should we respect $diffOnly here or not?
129 wfProfileOut( $fname );
133 $wgOut->suppressQuickbar();
135 $oldTitle = $this->mOldPage
->getPrefixedText();
136 $newTitle = $this->mNewPage
->getPrefixedText();
137 if( $oldTitle == $newTitle ) {
138 $wgOut->setPageTitle( $newTitle );
140 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
142 $wgOut->setSubtitle( wfMsg( 'difference' ) );
143 $wgOut->setRobotpolicy( 'noindex,nofollow' );
145 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
146 $wgOut->loginToUse();
148 wfProfileOut( $fname );
152 $sk = $wgUser->getSkin();
154 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
155 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
159 if( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isAllowed( 'patrol' ) ) {
160 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
165 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
166 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
167 if ( $this->mNewRev
->isCurrent() ) {
168 $nextlink = ' ';
170 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
171 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
177 if ($this->mOldRev
->mMinorEdit
== 1) {
178 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
179 wfMsg( 'minoreditletter') ) . ' ';
182 if ($this->mNewRev
->mMinorEdit
== 1) {
183 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
184 wfMsg( 'minoreditletter') ) . ' ';
187 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />" .
188 $sk->revUserTools( $this->mOldRev
) . "<br />" .
189 $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly ) . "<br />" .
191 $newHeader = "<strong>{$this->mNewtitle}</strong><br />" .
192 $sk->revUserTools( $this->mNewRev
) . " $rollback<br />" .
193 $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly ) . "<br />" .
196 $this->showDiff( $oldHeader, $newHeader );
199 $this->renderNewRevision();
201 wfProfileOut( $fname );
205 * Show the new revision of the page.
207 function renderNewRevision() {
209 $fname = 'DifferenceEngine::renderNewRevision';
210 wfProfileIn( $fname );
212 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
213 #add deleted rev tag if needed
214 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
215 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
218 if( !$this->mNewRev
->isCurrent() ) {
219 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
222 $this->loadNewText();
223 if( is_object( $this->mNewRev
) ) {
224 $wgOut->setRevisionId( $this->mNewRev
->getId() );
227 $wgOut->addWikiTextTidy( $this->mNewtext
);
229 if( !$this->mNewRev
->isCurrent() ) {
230 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
233 wfProfileOut( $fname );
237 * Show the first revision of an article. Uses normal diff headers in
238 * contrast to normal "old revision" display style.
240 function showFirstRevision() {
241 global $wgOut, $wgUser;
243 $fname = 'DifferenceEngine::showFirstRevision';
244 wfProfileIn( $fname );
246 # Get article text from the DB
248 if ( ! $this->loadNewText() ) {
249 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
251 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
252 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
253 $wgOut->addWikitext( $mtext );
254 wfProfileOut( $fname );
257 if ( $this->mNewRev
->isCurrent() ) {
258 $wgOut->setArticleFlag( true );
261 # Check if user is allowed to look at this page. If not, bail out.
263 if ( !( $this->mTitle
->userCanRead() ) ) {
264 $wgOut->loginToUse();
266 wfProfileOut( $fname );
270 # Prepare the header box
272 $sk = $wgUser->getSkin();
274 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
275 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
276 $sk->revUserTools( $this->mNewRev
) . "<br />" .
277 $sk->revComment( $this->mNewRev
) . "<br />" .
278 $nextlink . "</div>\n";
280 $wgOut->addHTML( $header );
282 $wgOut->setSubtitle( wfMsg( 'difference' ) );
283 $wgOut->setRobotpolicy( 'noindex,nofollow' );
285 wfProfileOut( $fname );
289 * Get the diff text, send it to $wgOut
290 * Returns false if the diff could not be generated, otherwise returns true
292 function showDiff( $otitle, $ntitle ) {
294 $diff = $this->getDiff( $otitle, $ntitle );
295 if ( $diff === false ) {
296 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
299 $this->showDiffStyle();
300 $wgOut->addHTML( $diff );
306 * Add style sheets and supporting JS for diff display.
308 function showDiffStyle() {
309 global $wgStylePath, $wgStyleVersion, $wgOut;
310 $wgOut->addStyle( 'common/diff.css' );
312 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
313 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
317 * Get diff table, including header
318 * Note that the interface has changed, it's no longer static.
319 * Returns false on error
321 function getDiff( $otitle, $ntitle ) {
322 $body = $this->getDiffBody();
323 if ( $body === false ) {
326 $multi = $this->getMultiNotice();
327 return $this->addHeader( $body, $otitle, $ntitle, $multi );
332 * Get the diff table body, without header
334 * Returns false on error
336 function getDiffBody() {
338 $fname = 'DifferenceEngine::getDiffBody';
339 wfProfileIn( $fname );
343 if ( $this->mOldid
&& $this->mNewid
) {
345 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
346 $difftext = $wgMemc->get( $key );
348 wfIncrStats( 'diff_cache_hit' );
349 $difftext = $this->localiseLineNumbers( $difftext );
350 $difftext .= "\n<!-- diff cache key $key -->\n";
351 wfProfileOut( $fname );
356 #loadtext is permission safe, this just clears out the diff
357 if ( !$this->loadText() ) {
358 wfProfileOut( $fname );
360 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
362 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
366 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
368 // Save to cache for 7 days
369 if ( $key !== false && $difftext !== false ) {
370 wfIncrStats( 'diff_cache_miss' );
371 $wgMemc->set( $key, $difftext, 7*86400 );
373 wfIncrStats( 'diff_uncacheable' );
375 // Replace line numbers with the text in the user's language
376 if ( $difftext !== false ) {
377 $difftext = $this->localiseLineNumbers( $difftext );
379 wfProfileOut( $fname );
384 * Generate a diff, no caching
385 * $otext and $ntext must be already segmented
387 function generateDiffBody( $otext, $ntext ) {
388 global $wgExternalDiffEngine, $wgContLang;
389 $fname = 'DifferenceEngine::generateDiffBody';
391 $otext = str_replace( "\r\n", "\n", $otext );
392 $ntext = str_replace( "\r\n", "\n", $ntext );
394 if ( $wgExternalDiffEngine == 'wikidiff' ) {
395 # For historical reasons, external diff engine expects
396 # input text to be HTML-escaped already
397 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
398 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
399 if( !function_exists( 'wikidiff_do_diff' ) ) {
400 dl('php_wikidiff.so');
402 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
405 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
406 # Better external diff engine, the 2 may some day be dropped
407 # This one does the escaping and segmenting itself
408 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
409 wfProfileIn( "$fname-dl" );
410 @dl
('php_wikidiff2.so');
411 wfProfileOut( "$fname-dl" );
413 if ( function_exists( 'wikidiff2_do_diff' ) ) {
414 wfProfileIn( 'wikidiff2_do_diff' );
415 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
416 wfProfileOut( 'wikidiff2_do_diff' );
420 if ( $wgExternalDiffEngine !== false ) {
422 global $wgTmpDirectory;
423 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
424 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
426 $tempFile1 = fopen( $tempName1, "w" );
428 wfProfileOut( $fname );
431 $tempFile2 = fopen( $tempName2, "w" );
433 wfProfileOut( $fname );
436 fwrite( $tempFile1, $otext );
437 fwrite( $tempFile2, $ntext );
438 fclose( $tempFile1 );
439 fclose( $tempFile2 );
440 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
441 wfProfileIn( "$fname-shellexec" );
442 $difftext = wfShellExec( $cmd );
443 wfProfileOut( "$fname-shellexec" );
444 unlink( $tempName1 );
445 unlink( $tempName2 );
450 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
451 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
452 $diffs = new Diff( $ota, $nta );
453 $formatter = new TableDiffFormatter();
454 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
459 * Replace line numbers with the text in the user's language
461 function localiseLineNumbers( $text ) {
462 return preg_replace_callback( '/<!--LINE (\d+)-->/',
463 array( &$this, 'localiseLineNumbersCb' ), $text );
466 function localiseLineNumbersCb( $matches ) {
468 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
473 * If there are revisions between the ones being compared, return a note saying so.
475 function getMultiNotice() {
476 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
479 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
480 // Comparing two different pages? Count would be meaningless.
484 $oldid = $this->mOldRev
->getId();
485 $newid = $this->mNewRev
->getId();
486 if ( $oldid > $newid ) {
487 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
490 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
494 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
499 * Add the header to a diff body
501 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
504 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
505 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
507 if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
508 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
512 <col class='diff-marker' />
513 <col class='diff-content' />
514 <col class='diff-marker' />
515 <col class='diff-content' />
517 <td colspan='2' class='diff-otitle'>{$otitle}</td>
518 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
523 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
525 return $header . $diff . "</table>";
529 * Use specified text instead of loading from the database
531 function setText( $oldText, $newText ) {
532 $this->mOldtext
= $oldText;
533 $this->mNewtext
= $newText;
534 $this->mTextLoaded
= 2;
538 * Load revision metadata for the specified articles. If newid is 0, then compare
539 * the old article in oldid to the current article; if oldid is 0, then
540 * compare the current article to the immediately previous one (ignoring the
543 * If oldid is false, leave the corresponding revision object set
544 * to false. This is impossible via ordinary user input, and is provided for
547 function loadRevisionData() {
549 if ( $this->mRevisionsLoaded
) {
552 // Whether it succeeds or fails, we don't want to try again
553 $this->mRevisionsLoaded
= true;
556 // Load the new revision object
557 if( $this->mNewid
) {
558 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
560 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
563 if( is_null( $this->mNewRev
) ) {
567 // Set assorted variables
568 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
569 $this->mNewPage
= $this->mNewRev
->getTitle();
570 if( $this->mNewRev
->isCurrent() ) {
571 $newLink = $this->mNewPage
->escapeLocalUrl();
572 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
573 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
575 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
576 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
579 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
580 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
581 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
583 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
584 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
587 // Load the old revision object
588 $this->mOldRev
= false;
589 if( $this->mOldid
) {
590 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
591 } elseif ( $this->mOldid
=== 0 ) {
592 $rev = $this->mNewRev
->getPrevious();
594 $this->mOldid
= $rev->getId();
595 $this->mOldRev
= $rev;
597 // No previous revision; mark to show as first-version only.
598 $this->mOldid
= false;
599 $this->mOldRev
= false;
601 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
603 if( is_null( $this->mOldRev
) ) {
607 if ( $this->mOldRev
) {
608 $this->mOldPage
= $this->mOldRev
->getTitle();
610 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
611 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
612 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
613 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
614 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
615 //now that we considered old rev, we can make undo link (bug 8133, multi-edit undo)
616 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
617 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
624 * Load the text of the revisions, as well as revision data.
626 function loadText() {
627 if ( $this->mTextLoaded
== 2 ) {
630 // Whether it succeeds or fails, we don't want to try again
631 $this->mTextLoaded
= 2;
634 if ( !$this->loadRevisionData() ) {
637 if ( $this->mOldRev
) {
638 // FIXME: permission tests
639 $this->mOldtext
= $this->mOldRev
->revText();
640 if ( $this->mOldtext
=== false ) {
644 if ( $this->mNewRev
) {
645 $this->mNewtext
= $this->mNewRev
->revText();
646 if ( $this->mNewtext
=== false ) {
654 * Load the text of the new revision, not the old one
656 function loadNewText() {
657 if ( $this->mTextLoaded
>= 1 ) {
660 $this->mTextLoaded
= 1;
662 if ( !$this->loadRevisionData() ) {
665 $this->mNewtext
= $this->mNewRev
->getText();
672 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
674 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
675 // You may copy this code freely under the conditions of the GPL.
678 define('USE_ASSERTS', function_exists('assert'));
683 * @addtogroup DifferenceEngine
691 trigger_error('pure virtual', E_USER_ERROR
);
695 return $this->orig ?
sizeof($this->orig
) : 0;
698 function nclosing() {
699 return $this->closing ?
sizeof($this->closing
) : 0;
706 * @addtogroup DifferenceEngine
708 class _DiffOp_Copy
extends _DiffOp
{
711 function _DiffOp_Copy ($orig, $closing = false) {
712 if (!is_array($closing))
715 $this->closing
= $closing;
719 return new _DiffOp_Copy($this->closing
, $this->orig
);
726 * @addtogroup DifferenceEngine
728 class _DiffOp_Delete
extends _DiffOp
{
729 var $type = 'delete';
731 function _DiffOp_Delete ($lines) {
732 $this->orig
= $lines;
733 $this->closing
= false;
737 return new _DiffOp_Add($this->orig
);
744 * @addtogroup DifferenceEngine
746 class _DiffOp_Add
extends _DiffOp
{
749 function _DiffOp_Add ($lines) {
750 $this->closing
= $lines;
755 return new _DiffOp_Delete($this->closing
);
762 * @addtogroup DifferenceEngine
764 class _DiffOp_Change
extends _DiffOp
{
765 var $type = 'change';
767 function _DiffOp_Change ($orig, $closing) {
769 $this->closing
= $closing;
773 return new _DiffOp_Change($this->closing
, $this->orig
);
779 * Class used internally by Diff to actually compute the diffs.
781 * The algorithm used here is mostly lifted from the perl module
782 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
783 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
785 * More ideas are taken from:
786 * http://www.ics.uci.edu/~eppstein/161/960229.html
788 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
789 * diffutils-2.7, which can be found at:
790 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
792 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
795 * Line length limits for robustness added by Tim Starling, 2005-08-31
797 * @author Geoffrey T. Dairiki, Tim Starling
799 * @addtogroup DifferenceEngine
803 const MAX_XREF_LENGTH
= 10000;
805 function diff ($from_lines, $to_lines) {
806 $fname = '_DiffEngine::diff';
807 wfProfileIn( $fname );
809 $n_from = sizeof($from_lines);
810 $n_to = sizeof($to_lines);
812 $this->xchanged
= $this->ychanged
= array();
813 $this->xv
= $this->yv
= array();
814 $this->xind
= $this->yind
= array();
816 unset($this->in_seq
);
819 // Skip leading common lines.
820 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
821 if ($from_lines[$skip] !== $to_lines[$skip])
823 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
825 // Skip trailing common lines.
826 $xi = $n_from; $yi = $n_to;
827 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
828 if ($from_lines[$xi] !== $to_lines[$yi])
830 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
833 // Ignore lines which do not exist in both files.
834 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
835 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
838 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
839 $line = $to_lines[$yi];
840 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
842 $yhash[$this->_line_hash($line)] = 1;
846 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
847 $line = $from_lines[$xi];
848 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
855 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
857 // Merge edits when possible
858 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
859 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
861 // Compute the edit operations.
864 while ($xi < $n_from ||
$yi < $n_to) {
865 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
866 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
868 // Skip matching "snake".
870 while ( $xi < $n_from && $yi < $n_to
871 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
872 $copy[] = $from_lines[$xi++
];
876 $edits[] = new _DiffOp_Copy($copy);
878 // Find deletes & adds.
880 while ($xi < $n_from && $this->xchanged
[$xi])
881 $delete[] = $from_lines[$xi++
];
884 while ($yi < $n_to && $this->ychanged
[$yi])
885 $add[] = $to_lines[$yi++
];
888 $edits[] = new _DiffOp_Change($delete, $add);
890 $edits[] = new _DiffOp_Delete($delete);
892 $edits[] = new _DiffOp_Add($add);
894 wfProfileOut( $fname );
899 * Returns the whole line if it's small enough, or the MD5 hash otherwise
901 function _line_hash( $line ) {
902 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
910 /* Divide the Largest Common Subsequence (LCS) of the sequences
911 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
914 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
915 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
916 * sub sequences. The first sub-sequence is contained in [X0, X1),
917 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
918 * that (X0, Y0) == (XOFF, YOFF) and
919 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
921 * This function assumes that the first lines of the specified portions
922 * of the two files do not match, and likewise that the last lines do not
923 * match. The caller must trim matching lines from the beginning and end
924 * of the portions it is going to specify.
926 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
927 $fname = '_DiffEngine::_diag';
928 wfProfileIn( $fname );
931 if ($xlim - $xoff > $ylim - $yoff) {
932 // Things seems faster (I'm not sure I understand why)
933 // when the shortest sequence in X.
935 list ($xoff, $xlim, $yoff, $ylim)
936 = array( $yoff, $ylim, $xoff, $xlim);
940 for ($i = $ylim - 1; $i >= $yoff; $i--)
941 $ymatches[$this->xv
[$i]][] = $i;
943 for ($i = $ylim - 1; $i >= $yoff; $i--)
944 $ymatches[$this->yv
[$i]][] = $i;
947 $this->seq
[0]= $yoff - 1;
948 $this->in_seq
= array();
951 $numer = $xlim - $xoff +
$nchunks - 1;
953 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
954 wfProfileIn( "$fname-chunk" );
956 for ($i = 0; $i <= $this->lcs
; $i++
)
957 $ymids[$i][$chunk-1] = $this->seq
[$i];
959 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
960 for ( ; $x < $x1; $x++
) {
961 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
962 if (empty($ymatches[$line]))
964 $matches = $ymatches[$line];
966 while (list ($junk, $y) = each($matches))
967 if (empty($this->in_seq
[$y])) {
968 $k = $this->_lcs_pos($y);
969 USE_ASSERTS
&& assert($k > 0);
970 $ymids[$k] = $ymids[$k-1];
973 while (list ( /* $junk */, $y) = each($matches)) {
974 if ($y > $this->seq
[$k-1]) {
975 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
976 // Optimization: this is a common case:
977 // next match is just replacing previous match.
978 $this->in_seq
[$this->seq
[$k]] = false;
980 $this->in_seq
[$y] = 1;
981 } else if (empty($this->in_seq
[$y])) {
982 $k = $this->_lcs_pos($y);
983 USE_ASSERTS
&& assert($k > 0);
984 $ymids[$k] = $ymids[$k-1];
988 wfProfileOut( "$fname-chunk" );
991 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
992 $ymid = $ymids[$this->lcs
];
993 for ($n = 0; $n < $nchunks - 1; $n++
) {
994 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
996 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
998 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1000 wfProfileOut( $fname );
1001 return array($this->lcs
, $seps);
1004 function _lcs_pos ($ypos) {
1005 $fname = '_DiffEngine::_lcs_pos';
1006 wfProfileIn( $fname );
1009 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1010 $this->seq
[++
$this->lcs
] = $ypos;
1011 $this->in_seq
[$ypos] = 1;
1012 wfProfileOut( $fname );
1017 while ($beg < $end) {
1018 $mid = (int)(($beg +
$end) / 2);
1019 if ( $ypos > $this->seq
[$mid] )
1025 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1027 $this->in_seq
[$this->seq
[$end]] = false;
1028 $this->seq
[$end] = $ypos;
1029 $this->in_seq
[$ypos] = 1;
1030 wfProfileOut( $fname );
1034 /* Find LCS of two sequences.
1036 * The results are recorded in the vectors $this->{x,y}changed[], by
1037 * storing a 1 in the element for each line that is an insertion
1038 * or deletion (ie. is not in the LCS).
1040 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1042 * Note that XLIM, YLIM are exclusive bounds.
1043 * All line numbers are origin-0 and discarded lines are not counted.
1045 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1046 $fname = '_DiffEngine::_compareseq';
1047 wfProfileIn( $fname );
1049 // Slide down the bottom initial diagonal.
1050 while ($xoff < $xlim && $yoff < $ylim
1051 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1056 // Slide up the top initial diagonal.
1057 while ($xlim > $xoff && $ylim > $yoff
1058 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1063 if ($xoff == $xlim ||
$yoff == $ylim)
1066 // This is ad hoc but seems to work well.
1067 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1068 //$nchunks = max(2,min(8,(int)$nchunks));
1069 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1071 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1075 // X and Y sequences have no common subsequence:
1076 // mark all changed.
1077 while ($yoff < $ylim)
1078 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1079 while ($xoff < $xlim)
1080 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1082 // Use the partitions to split this problem into subproblems.
1085 while ($pt2 = next($seps)) {
1086 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1090 wfProfileOut( $fname );
1093 /* Adjust inserts/deletes of identical lines to join changes
1094 * as much as possible.
1096 * We do something when a run of changed lines include a
1097 * line at one end and has an excluded, identical line at the other.
1098 * We are free to choose which identical line is included.
1099 * `compareseq' usually chooses the one at the beginning,
1100 * but usually it is cleaner to consider the following identical line
1101 * to be the "change".
1103 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1105 function _shift_boundaries ($lines, &$changed, $other_changed) {
1106 $fname = '_DiffEngine::_shift_boundaries';
1107 wfProfileIn( $fname );
1111 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1112 $len = sizeof($lines);
1113 $other_len = sizeof($other_changed);
1117 * Scan forwards to find beginning of another run of changes.
1118 * Also keep track of the corresponding point in the other file.
1120 * Throughout this code, $i and $j are adjusted together so that
1121 * the first $i elements of $changed and the first $j elements
1122 * of $other_changed both contain the same number of zeros
1123 * (unchanged lines).
1124 * Furthermore, $j is always kept so that $j == $other_len or
1125 * $other_changed[$j] == false.
1127 while ($j < $other_len && $other_changed[$j])
1130 while ($i < $len && ! $changed[$i]) {
1131 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1133 while ($j < $other_len && $other_changed[$j])
1142 // Find the end of this run of changes.
1143 while (++
$i < $len && $changed[$i])
1148 * Record the length of this run of changes, so that
1149 * we can later determine whether the run has grown.
1151 $runlength = $i - $start;
1154 * Move the changed region back, so long as the
1155 * previous unchanged line matches the last changed one.
1156 * This merges with previous changed regions.
1158 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1159 $changed[--$start] = 1;
1160 $changed[--$i] = false;
1161 while ($start > 0 && $changed[$start - 1])
1163 USE_ASSERTS
&& assert('$j > 0');
1164 while ($other_changed[--$j])
1166 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1170 * Set CORRESPONDING to the end of the changed run, at the last
1171 * point where it corresponds to a changed run in the other file.
1172 * CORRESPONDING == LEN means no such point has been found.
1174 $corresponding = $j < $other_len ?
$i : $len;
1177 * Move the changed region forward, so long as the
1178 * first changed line matches the following unchanged one.
1179 * This merges with following changed regions.
1180 * Do this second, so that if there are no merges,
1181 * the changed region is moved forward as far as possible.
1183 while ($i < $len && $lines[$start] == $lines[$i]) {
1184 $changed[$start++
] = false;
1186 while ($i < $len && $changed[$i])
1189 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1191 if ($j < $other_len && $other_changed[$j]) {
1192 $corresponding = $i;
1193 while ($j < $other_len && $other_changed[$j])
1197 } while ($runlength != $i - $start);
1200 * If possible, move the fully-merged run of changes
1201 * back to a corresponding run in the other file.
1203 while ($corresponding < $i) {
1204 $changed[--$start] = 1;
1206 USE_ASSERTS
&& assert('$j > 0');
1207 while ($other_changed[--$j])
1209 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1212 wfProfileOut( $fname );
1217 * Class representing a 'diff' between two sequences of strings.
1220 * @addtogroup DifferenceEngine
1228 * Computes diff between sequences of strings.
1230 * @param $from_lines array An array of strings.
1231 * (Typically these are lines from a file.)
1232 * @param $to_lines array An array of strings.
1234 function Diff($from_lines, $to_lines) {
1235 $eng = new _DiffEngine
;
1236 $this->edits
= $eng->diff($from_lines, $to_lines);
1237 //$this->_check($from_lines, $to_lines);
1241 * Compute reversed Diff.
1245 * $diff = new Diff($lines1, $lines2);
1246 * $rev = $diff->reverse();
1247 * @return object A Diff object representing the inverse of the
1250 function reverse () {
1252 $rev->edits
= array();
1253 foreach ($this->edits
as $edit) {
1254 $rev->edits
[] = $edit->reverse();
1260 * Check for empty diff.
1262 * @return bool True iff two sequences were identical.
1264 function isEmpty () {
1265 foreach ($this->edits
as $edit) {
1266 if ($edit->type
!= 'copy')
1273 * Compute the length of the Longest Common Subsequence (LCS).
1275 * This is mostly for diagnostic purposed.
1277 * @return int The length of the LCS.
1281 foreach ($this->edits
as $edit) {
1282 if ($edit->type
== 'copy')
1283 $lcs +
= sizeof($edit->orig
);
1289 * Get the original set of lines.
1291 * This reconstructs the $from_lines parameter passed to the
1294 * @return array The original sequence of strings.
1299 foreach ($this->edits
as $edit) {
1301 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1307 * Get the closing set of lines.
1309 * This reconstructs the $to_lines parameter passed to the
1312 * @return array The sequence of strings.
1314 function closing() {
1317 foreach ($this->edits
as $edit) {
1319 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1325 * Check a Diff for validity.
1327 * This is here only for debugging purposes.
1329 function _check ($from_lines, $to_lines) {
1330 $fname = 'Diff::_check';
1331 wfProfileIn( $fname );
1332 if (serialize($from_lines) != serialize($this->orig()))
1333 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1334 if (serialize($to_lines) != serialize($this->closing()))
1335 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1337 $rev = $this->reverse();
1338 if (serialize($to_lines) != serialize($rev->orig()))
1339 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1340 if (serialize($from_lines) != serialize($rev->closing()))
1341 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1345 foreach ($this->edits
as $edit) {
1346 if ( $prevtype == $edit->type
)
1347 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1348 $prevtype = $edit->type
;
1351 $lcs = $this->lcs();
1352 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1353 wfProfileOut( $fname );
1358 * @todo document, bad name.
1360 * @addtogroup DifferenceEngine
1362 class MappedDiff
extends Diff
1367 * Computes diff between sequences of strings.
1369 * This can be used to compute things like
1370 * case-insensitve diffs, or diffs which ignore
1371 * changes in white-space.
1373 * @param $from_lines array An array of strings.
1374 * (Typically these are lines from a file.)
1376 * @param $to_lines array An array of strings.
1378 * @param $mapped_from_lines array This array should
1379 * have the same size number of elements as $from_lines.
1380 * The elements in $mapped_from_lines and
1381 * $mapped_to_lines are what is actually compared
1382 * when computing the diff.
1384 * @param $mapped_to_lines array This array should
1385 * have the same number of elements as $to_lines.
1387 function MappedDiff($from_lines, $to_lines,
1388 $mapped_from_lines, $mapped_to_lines) {
1389 $fname = 'MappedDiff::MappedDiff';
1390 wfProfileIn( $fname );
1392 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1393 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1395 $this->Diff($mapped_from_lines, $mapped_to_lines);
1398 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1399 $orig = &$this->edits
[$i]->orig
;
1400 if (is_array($orig)) {
1401 $orig = array_slice($from_lines, $xi, sizeof($orig));
1402 $xi +
= sizeof($orig);
1405 $closing = &$this->edits
[$i]->closing
;
1406 if (is_array($closing)) {
1407 $closing = array_slice($to_lines, $yi, sizeof($closing));
1408 $yi +
= sizeof($closing);
1411 wfProfileOut( $fname );
1416 * A class to format Diffs
1418 * This class formats the diff in classic diff format.
1419 * It is intended that this class be customized via inheritance,
1420 * to obtain fancier outputs.
1423 * @addtogroup DifferenceEngine
1428 * Number of leading context "lines" to preserve.
1430 * This should be left at zero for this class, but subclasses
1431 * may want to set this to other values.
1433 var $leading_context_lines = 0;
1436 * Number of trailing context "lines" to preserve.
1438 * This should be left at zero for this class, but subclasses
1439 * may want to set this to other values.
1441 var $trailing_context_lines = 0;
1446 * @param $diff object A Diff object.
1447 * @return string The formatted output.
1449 function format($diff) {
1450 $fname = 'DiffFormatter::format';
1451 wfProfileIn( $fname );
1457 $nlead = $this->leading_context_lines
;
1458 $ntrail = $this->trailing_context_lines
;
1460 $this->_start_diff();
1462 foreach ($diff->edits
as $edit) {
1463 if ($edit->type
== 'copy') {
1464 if (is_array($block)) {
1465 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1470 $context = array_slice($edit->orig
, 0, $ntrail);
1471 $block[] = new _DiffOp_Copy($context);
1473 $this->_block($x0, $ntrail +
$xi - $x0,
1474 $y0, $ntrail +
$yi - $y0,
1479 $context = $edit->orig
;
1482 if (! is_array($block)) {
1483 $context = array_slice($context, sizeof($context) - $nlead);
1484 $x0 = $xi - sizeof($context);
1485 $y0 = $yi - sizeof($context);
1488 $block[] = new _DiffOp_Copy($context);
1494 $xi +
= sizeof($edit->orig
);
1496 $yi +
= sizeof($edit->closing
);
1499 if (is_array($block))
1500 $this->_block($x0, $xi - $x0,
1504 $end = $this->_end_diff();
1505 wfProfileOut( $fname );
1509 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1510 $fname = 'DiffFormatter::_block';
1511 wfProfileIn( $fname );
1512 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1513 foreach ($edits as $edit) {
1514 if ($edit->type
== 'copy')
1515 $this->_context($edit->orig
);
1516 elseif ($edit->type
== 'add')
1517 $this->_added($edit->closing
);
1518 elseif ($edit->type
== 'delete')
1519 $this->_deleted($edit->orig
);
1520 elseif ($edit->type
== 'change')
1521 $this->_changed($edit->orig
, $edit->closing
);
1523 trigger_error('Unknown edit type', E_USER_ERROR
);
1525 $this->_end_block();
1526 wfProfileOut( $fname );
1529 function _start_diff() {
1533 function _end_diff() {
1534 $val = ob_get_contents();
1539 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1541 $xbeg .= "," . ($xbeg +
$xlen - 1);
1543 $ybeg .= "," . ($ybeg +
$ylen - 1);
1545 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1548 function _start_block($header) {
1552 function _end_block() {
1555 function _lines($lines, $prefix = ' ') {
1556 foreach ($lines as $line)
1557 echo "$prefix $line\n";
1560 function _context($lines) {
1561 $this->_lines($lines);
1564 function _added($lines) {
1565 $this->_lines($lines, '>');
1567 function _deleted($lines) {
1568 $this->_lines($lines, '<');
1571 function _changed($orig, $closing) {
1572 $this->_deleted($orig);
1574 $this->_added($closing);
1580 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1584 define('NBSP', ' '); // iso-8859-x non-breaking space.
1589 * @addtogroup DifferenceEngine
1591 class _HWLDF_WordAccumulator
{
1592 function _HWLDF_WordAccumulator () {
1593 $this->_lines
= array();
1599 function _flushGroup ($new_tag) {
1600 if ($this->_group
!== '') {
1601 if ($this->_tag
== 'ins')
1602 $this->_line
.= '<ins class="diffchange">' .
1603 htmlspecialchars ( $this->_group
) . '</ins>';
1604 elseif ($this->_tag
== 'del')
1605 $this->_line
.= '<del class="diffchange">' .
1606 htmlspecialchars ( $this->_group
) . '</del>';
1608 $this->_line
.= htmlspecialchars ( $this->_group
);
1611 $this->_tag
= $new_tag;
1614 function _flushLine ($new_tag) {
1615 $this->_flushGroup($new_tag);
1616 if ($this->_line
!= '')
1617 array_push ( $this->_lines
, $this->_line
);
1619 # make empty lines visible by inserting an NBSP
1620 array_push ( $this->_lines
, NBSP
);
1624 function addWords ($words, $tag = '') {
1625 if ($tag != $this->_tag
)
1626 $this->_flushGroup($tag);
1628 foreach ($words as $word) {
1629 // new-line should only come as first char of word.
1632 if ($word[0] == "\n") {
1633 $this->_flushLine($tag);
1634 $word = substr($word, 1);
1636 assert(!strstr($word, "\n"));
1637 $this->_group
.= $word;
1641 function getLines() {
1642 $this->_flushLine('~done');
1643 return $this->_lines
;
1650 * @addtogroup DifferenceEngine
1652 class WordLevelDiff
extends MappedDiff
1654 const MAX_LINE_LENGTH
= 10000;
1656 function WordLevelDiff ($orig_lines, $closing_lines) {
1657 $fname = 'WordLevelDiff::WordLevelDiff';
1658 wfProfileIn( $fname );
1660 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1661 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1663 $this->MappedDiff($orig_words, $closing_words,
1664 $orig_stripped, $closing_stripped);
1665 wfProfileOut( $fname );
1668 function _split($lines) {
1669 $fname = 'WordLevelDiff::_split';
1670 wfProfileIn( $fname );
1673 $stripped = array();
1675 foreach ( $lines as $line ) {
1676 # If the line is too long, just pretend the entire line is one big word
1677 # This prevents resource exhaustion problems
1684 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1686 $stripped[] = $line;
1689 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1692 $words = array_merge( $words, $m[0] );
1693 $stripped = array_merge( $stripped, $m[1] );
1697 wfProfileOut( $fname );
1698 return array($words, $stripped);
1702 $fname = 'WordLevelDiff::orig';
1703 wfProfileIn( $fname );
1704 $orig = new _HWLDF_WordAccumulator
;
1706 foreach ($this->edits
as $edit) {
1707 if ($edit->type
== 'copy')
1708 $orig->addWords($edit->orig
);
1709 elseif ($edit->orig
)
1710 $orig->addWords($edit->orig
, 'del');
1712 $lines = $orig->getLines();
1713 wfProfileOut( $fname );
1717 function closing () {
1718 $fname = 'WordLevelDiff::closing';
1719 wfProfileIn( $fname );
1720 $closing = new _HWLDF_WordAccumulator
;
1722 foreach ($this->edits
as $edit) {
1723 if ($edit->type
== 'copy')
1724 $closing->addWords($edit->closing
);
1725 elseif ($edit->closing
)
1726 $closing->addWords($edit->closing
, 'ins');
1728 $lines = $closing->getLines();
1729 wfProfileOut( $fname );
1735 * Wikipedia Table style diff formatter.
1738 * @addtogroup DifferenceEngine
1740 class TableDiffFormatter
extends DiffFormatter
1742 function TableDiffFormatter() {
1743 $this->leading_context_lines
= 2;
1744 $this->trailing_context_lines
= 2;
1747 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1748 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1749 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1753 function _start_block( $header ) {
1757 function _end_block() {
1760 function _lines( $lines, $prefix=' ', $color='white' ) {
1763 # HTML-escape parameter before calling this
1764 function addedLine( $line ) {
1765 return $this->wrapLine( '+', 'diff-addedline', $line );
1768 # HTML-escape parameter before calling this
1769 function deletedLine( $line ) {
1770 return $this->wrapLine( '-', 'diff-deletedline', $line );
1773 # HTML-escape parameter before calling this
1774 function contextLine( $line ) {
1775 return $this->wrapLine( ' ', 'diff-context', $line );
1778 private function wrapLine( $marker, $class, $line ) {
1779 if( $line !== '' ) {
1780 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1781 $line = "<div>$line</div>";
1783 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1786 function emptyLine() {
1787 return '<td colspan="2"> </td>';
1790 function _added( $lines ) {
1791 foreach ($lines as $line) {
1792 echo '<tr>' . $this->emptyLine() .
1793 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1797 function _deleted($lines) {
1798 foreach ($lines as $line) {
1799 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1800 $this->emptyLine() . "</tr>\n";
1804 function _context( $lines ) {
1805 foreach ($lines as $line) {
1807 $this->contextLine( htmlspecialchars ( $line ) ) .
1808 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1812 function _changed( $orig, $closing ) {
1813 $fname = 'TableDiffFormatter::_changed';
1814 wfProfileIn( $fname );
1816 $diff = new WordLevelDiff( $orig, $closing );
1817 $del = $diff->orig();
1818 $add = $diff->closing();
1820 # Notice that WordLevelDiff returns HTML-escaped output.
1821 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1823 while ( $line = array_shift( $del ) ) {
1824 $aline = array_shift( $add );
1825 echo '<tr>' . $this->deletedLine( $line ) .
1826 $this->addedLine( $aline ) . "</tr>\n";
1828 foreach ($add as $line) { # If any leftovers
1829 echo '<tr>' . $this->emptyLine() .
1830 $this->addedLine( $line ) . "</tr>\n";
1832 wfProfileOut( $fname );