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 ) {
293 global $wgOut, $wgRequest;
294 $diff = $this->getDiff( $otitle, $ntitle, $wgRequest->getVal( 'action' ) == 'purge' );
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 complete diff table, including header
319 * @param Title $otitle Old title
320 * @param Title $ntitle New title
321 * @param bool $skipCache Skip the diff cache for this request?
324 function getDiff( $otitle, $ntitle, $skipCache = false ) {
325 $body = $this->getDiffBody( $skipCache );
326 if ( $body === false ) {
329 $multi = $this->getMultiNotice();
330 return $this->addHeader( $body, $otitle, $ntitle, $multi );
335 * Get the diff table body, without header
337 * @param bool $skipCache Skip cache for this request?
340 function getDiffBody( $skipCache = false ) {
342 $fname = 'DifferenceEngine::getDiffBody';
343 wfProfileIn( $fname );
347 if ( $this->mOldid
&& $this->mNewid
&& !$skipCache ) {
349 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
350 $difftext = $wgMemc->get( $key );
352 wfIncrStats( 'diff_cache_hit' );
353 $difftext = $this->localiseLineNumbers( $difftext );
354 $difftext .= "\n<!-- diff cache key $key -->\n";
355 wfProfileOut( $fname );
360 #loadtext is permission safe, this just clears out the diff
361 if ( !$this->loadText() ) {
362 wfProfileOut( $fname );
364 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
366 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
370 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
372 // Save to cache for 7 days
373 if ( $key !== false && $difftext !== false ) {
374 wfIncrStats( 'diff_cache_miss' );
375 $wgMemc->set( $key, $difftext, 7*86400 );
377 wfIncrStats( 'diff_uncacheable' );
379 // Replace line numbers with the text in the user's language
380 if ( $difftext !== false ) {
381 $difftext = $this->localiseLineNumbers( $difftext );
383 wfProfileOut( $fname );
388 * Generate a diff, no caching
389 * $otext and $ntext must be already segmented
391 function generateDiffBody( $otext, $ntext ) {
392 global $wgExternalDiffEngine, $wgContLang;
393 $fname = 'DifferenceEngine::generateDiffBody';
395 $otext = str_replace( "\r\n", "\n", $otext );
396 $ntext = str_replace( "\r\n", "\n", $ntext );
398 if ( $wgExternalDiffEngine == 'wikidiff' ) {
399 # For historical reasons, external diff engine expects
400 # input text to be HTML-escaped already
401 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
402 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
403 if( !function_exists( 'wikidiff_do_diff' ) ) {
404 dl('php_wikidiff.so');
406 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
409 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
410 # Better external diff engine, the 2 may some day be dropped
411 # This one does the escaping and segmenting itself
412 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
413 wfProfileIn( "$fname-dl" );
414 @dl
('php_wikidiff2.so');
415 wfProfileOut( "$fname-dl" );
417 if ( function_exists( 'wikidiff2_do_diff' ) ) {
418 wfProfileIn( 'wikidiff2_do_diff' );
419 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
420 wfProfileOut( 'wikidiff2_do_diff' );
424 if ( $wgExternalDiffEngine !== false ) {
426 global $wgTmpDirectory;
427 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
428 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
430 $tempFile1 = fopen( $tempName1, "w" );
432 wfProfileOut( $fname );
435 $tempFile2 = fopen( $tempName2, "w" );
437 wfProfileOut( $fname );
440 fwrite( $tempFile1, $otext );
441 fwrite( $tempFile2, $ntext );
442 fclose( $tempFile1 );
443 fclose( $tempFile2 );
444 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
445 wfProfileIn( "$fname-shellexec" );
446 $difftext = wfShellExec( $cmd );
447 wfProfileOut( "$fname-shellexec" );
448 unlink( $tempName1 );
449 unlink( $tempName2 );
454 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
455 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
456 $diffs = new Diff( $ota, $nta );
457 $formatter = new TableDiffFormatter();
458 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
463 * Replace line numbers with the text in the user's language
465 function localiseLineNumbers( $text ) {
466 return preg_replace_callback( '/<!--LINE (\d+)-->/',
467 array( &$this, 'localiseLineNumbersCb' ), $text );
470 function localiseLineNumbersCb( $matches ) {
472 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
477 * If there are revisions between the ones being compared, return a note saying so.
479 function getMultiNotice() {
480 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
483 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
484 // Comparing two different pages? Count would be meaningless.
488 $oldid = $this->mOldRev
->getId();
489 $newid = $this->mNewRev
->getId();
490 if ( $oldid > $newid ) {
491 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
494 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
498 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
503 * Add the header to a diff body
505 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
508 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
509 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
511 if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
512 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
516 <col class='diff-marker' />
517 <col class='diff-content' />
518 <col class='diff-marker' />
519 <col class='diff-content' />
521 <td colspan='2' class='diff-otitle'>{$otitle}</td>
522 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
527 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
529 return $header . $diff . "</table>";
533 * Use specified text instead of loading from the database
535 function setText( $oldText, $newText ) {
536 $this->mOldtext
= $oldText;
537 $this->mNewtext
= $newText;
538 $this->mTextLoaded
= 2;
542 * Load revision metadata for the specified articles. If newid is 0, then compare
543 * the old article in oldid to the current article; if oldid is 0, then
544 * compare the current article to the immediately previous one (ignoring the
547 * If oldid is false, leave the corresponding revision object set
548 * to false. This is impossible via ordinary user input, and is provided for
551 function loadRevisionData() {
553 if ( $this->mRevisionsLoaded
) {
556 // Whether it succeeds or fails, we don't want to try again
557 $this->mRevisionsLoaded
= true;
560 // Load the new revision object
561 $this->mNewRev
= $this->mNewid
562 ? Revision
::newFromId( $this->mNewid
)
563 : Revision
::newFromTitle( $this->mTitle
);
564 if( !$this->mNewRev
instanceof Revision
)
567 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
568 $this->mNewid
= $this->mNewRev
->getId();
570 // Set assorted variables
571 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
572 $this->mNewPage
= $this->mNewRev
->getTitle();
573 if( $this->mNewRev
->isCurrent() ) {
574 $newLink = $this->mNewPage
->escapeLocalUrl();
575 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
576 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
578 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
579 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
582 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
583 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
584 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
586 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
587 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
590 // Load the old revision object
591 $this->mOldRev
= false;
592 if( $this->mOldid
) {
593 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
594 } elseif ( $this->mOldid
=== 0 ) {
595 $rev = $this->mNewRev
->getPrevious();
597 $this->mOldid
= $rev->getId();
598 $this->mOldRev
= $rev;
600 // No previous revision; mark to show as first-version only.
601 $this->mOldid
= false;
602 $this->mOldRev
= false;
604 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
606 if( is_null( $this->mOldRev
) ) {
610 if ( $this->mOldRev
) {
611 $this->mOldPage
= $this->mOldRev
->getTitle();
613 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
614 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
615 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
616 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
617 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
619 // Add an "undo" link
620 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
621 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
628 * Load the text of the revisions, as well as revision data.
630 function loadText() {
631 if ( $this->mTextLoaded
== 2 ) {
634 // Whether it succeeds or fails, we don't want to try again
635 $this->mTextLoaded
= 2;
638 if ( !$this->loadRevisionData() ) {
641 if ( $this->mOldRev
) {
642 // FIXME: permission tests
643 $this->mOldtext
= $this->mOldRev
->revText();
644 if ( $this->mOldtext
=== false ) {
648 if ( $this->mNewRev
) {
649 $this->mNewtext
= $this->mNewRev
->revText();
650 if ( $this->mNewtext
=== false ) {
658 * Load the text of the new revision, not the old one
660 function loadNewText() {
661 if ( $this->mTextLoaded
>= 1 ) {
664 $this->mTextLoaded
= 1;
666 if ( !$this->loadRevisionData() ) {
669 $this->mNewtext
= $this->mNewRev
->getText();
676 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
678 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
679 // You may copy this code freely under the conditions of the GPL.
682 define('USE_ASSERTS', function_exists('assert'));
687 * @addtogroup DifferenceEngine
695 trigger_error('pure virtual', E_USER_ERROR
);
699 return $this->orig ?
sizeof($this->orig
) : 0;
702 function nclosing() {
703 return $this->closing ?
sizeof($this->closing
) : 0;
710 * @addtogroup DifferenceEngine
712 class _DiffOp_Copy
extends _DiffOp
{
715 function _DiffOp_Copy ($orig, $closing = false) {
716 if (!is_array($closing))
719 $this->closing
= $closing;
723 return new _DiffOp_Copy($this->closing
, $this->orig
);
730 * @addtogroup DifferenceEngine
732 class _DiffOp_Delete
extends _DiffOp
{
733 var $type = 'delete';
735 function _DiffOp_Delete ($lines) {
736 $this->orig
= $lines;
737 $this->closing
= false;
741 return new _DiffOp_Add($this->orig
);
748 * @addtogroup DifferenceEngine
750 class _DiffOp_Add
extends _DiffOp
{
753 function _DiffOp_Add ($lines) {
754 $this->closing
= $lines;
759 return new _DiffOp_Delete($this->closing
);
766 * @addtogroup DifferenceEngine
768 class _DiffOp_Change
extends _DiffOp
{
769 var $type = 'change';
771 function _DiffOp_Change ($orig, $closing) {
773 $this->closing
= $closing;
777 return new _DiffOp_Change($this->closing
, $this->orig
);
783 * Class used internally by Diff to actually compute the diffs.
785 * The algorithm used here is mostly lifted from the perl module
786 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
787 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
789 * More ideas are taken from:
790 * http://www.ics.uci.edu/~eppstein/161/960229.html
792 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
793 * diffutils-2.7, which can be found at:
794 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
796 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
799 * Line length limits for robustness added by Tim Starling, 2005-08-31
801 * @author Geoffrey T. Dairiki, Tim Starling
803 * @addtogroup DifferenceEngine
807 const MAX_XREF_LENGTH
= 10000;
809 function diff ($from_lines, $to_lines) {
810 $fname = '_DiffEngine::diff';
811 wfProfileIn( $fname );
813 $n_from = sizeof($from_lines);
814 $n_to = sizeof($to_lines);
816 $this->xchanged
= $this->ychanged
= array();
817 $this->xv
= $this->yv
= array();
818 $this->xind
= $this->yind
= array();
820 unset($this->in_seq
);
823 // Skip leading common lines.
824 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
825 if ($from_lines[$skip] !== $to_lines[$skip])
827 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
829 // Skip trailing common lines.
830 $xi = $n_from; $yi = $n_to;
831 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
832 if ($from_lines[$xi] !== $to_lines[$yi])
834 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
837 // Ignore lines which do not exist in both files.
838 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
839 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
842 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
843 $line = $to_lines[$yi];
844 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
846 $yhash[$this->_line_hash($line)] = 1;
850 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
851 $line = $from_lines[$xi];
852 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
859 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
861 // Merge edits when possible
862 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
863 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
865 // Compute the edit operations.
868 while ($xi < $n_from ||
$yi < $n_to) {
869 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
870 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
872 // Skip matching "snake".
874 while ( $xi < $n_from && $yi < $n_to
875 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
876 $copy[] = $from_lines[$xi++
];
880 $edits[] = new _DiffOp_Copy($copy);
882 // Find deletes & adds.
884 while ($xi < $n_from && $this->xchanged
[$xi])
885 $delete[] = $from_lines[$xi++
];
888 while ($yi < $n_to && $this->ychanged
[$yi])
889 $add[] = $to_lines[$yi++
];
892 $edits[] = new _DiffOp_Change($delete, $add);
894 $edits[] = new _DiffOp_Delete($delete);
896 $edits[] = new _DiffOp_Add($add);
898 wfProfileOut( $fname );
903 * Returns the whole line if it's small enough, or the MD5 hash otherwise
905 function _line_hash( $line ) {
906 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
914 /* Divide the Largest Common Subsequence (LCS) of the sequences
915 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
918 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
919 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
920 * sub sequences. The first sub-sequence is contained in [X0, X1),
921 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
922 * that (X0, Y0) == (XOFF, YOFF) and
923 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
925 * This function assumes that the first lines of the specified portions
926 * of the two files do not match, and likewise that the last lines do not
927 * match. The caller must trim matching lines from the beginning and end
928 * of the portions it is going to specify.
930 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
931 $fname = '_DiffEngine::_diag';
932 wfProfileIn( $fname );
935 if ($xlim - $xoff > $ylim - $yoff) {
936 // Things seems faster (I'm not sure I understand why)
937 // when the shortest sequence in X.
939 list ($xoff, $xlim, $yoff, $ylim)
940 = array( $yoff, $ylim, $xoff, $xlim);
944 for ($i = $ylim - 1; $i >= $yoff; $i--)
945 $ymatches[$this->xv
[$i]][] = $i;
947 for ($i = $ylim - 1; $i >= $yoff; $i--)
948 $ymatches[$this->yv
[$i]][] = $i;
951 $this->seq
[0]= $yoff - 1;
952 $this->in_seq
= array();
955 $numer = $xlim - $xoff +
$nchunks - 1;
957 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
958 wfProfileIn( "$fname-chunk" );
960 for ($i = 0; $i <= $this->lcs
; $i++
)
961 $ymids[$i][$chunk-1] = $this->seq
[$i];
963 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
964 for ( ; $x < $x1; $x++
) {
965 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
966 if (empty($ymatches[$line]))
968 $matches = $ymatches[$line];
970 while (list ($junk, $y) = each($matches))
971 if (empty($this->in_seq
[$y])) {
972 $k = $this->_lcs_pos($y);
973 USE_ASSERTS
&& assert($k > 0);
974 $ymids[$k] = $ymids[$k-1];
977 while (list ( /* $junk */, $y) = each($matches)) {
978 if ($y > $this->seq
[$k-1]) {
979 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
980 // Optimization: this is a common case:
981 // next match is just replacing previous match.
982 $this->in_seq
[$this->seq
[$k]] = false;
984 $this->in_seq
[$y] = 1;
985 } else if (empty($this->in_seq
[$y])) {
986 $k = $this->_lcs_pos($y);
987 USE_ASSERTS
&& assert($k > 0);
988 $ymids[$k] = $ymids[$k-1];
992 wfProfileOut( "$fname-chunk" );
995 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
996 $ymid = $ymids[$this->lcs
];
997 for ($n = 0; $n < $nchunks - 1; $n++
) {
998 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1000 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1002 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1004 wfProfileOut( $fname );
1005 return array($this->lcs
, $seps);
1008 function _lcs_pos ($ypos) {
1009 $fname = '_DiffEngine::_lcs_pos';
1010 wfProfileIn( $fname );
1013 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1014 $this->seq
[++
$this->lcs
] = $ypos;
1015 $this->in_seq
[$ypos] = 1;
1016 wfProfileOut( $fname );
1021 while ($beg < $end) {
1022 $mid = (int)(($beg +
$end) / 2);
1023 if ( $ypos > $this->seq
[$mid] )
1029 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1031 $this->in_seq
[$this->seq
[$end]] = false;
1032 $this->seq
[$end] = $ypos;
1033 $this->in_seq
[$ypos] = 1;
1034 wfProfileOut( $fname );
1038 /* Find LCS of two sequences.
1040 * The results are recorded in the vectors $this->{x,y}changed[], by
1041 * storing a 1 in the element for each line that is an insertion
1042 * or deletion (ie. is not in the LCS).
1044 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1046 * Note that XLIM, YLIM are exclusive bounds.
1047 * All line numbers are origin-0 and discarded lines are not counted.
1049 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1050 $fname = '_DiffEngine::_compareseq';
1051 wfProfileIn( $fname );
1053 // Slide down the bottom initial diagonal.
1054 while ($xoff < $xlim && $yoff < $ylim
1055 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1060 // Slide up the top initial diagonal.
1061 while ($xlim > $xoff && $ylim > $yoff
1062 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1067 if ($xoff == $xlim ||
$yoff == $ylim)
1070 // This is ad hoc but seems to work well.
1071 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1072 //$nchunks = max(2,min(8,(int)$nchunks));
1073 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1075 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1079 // X and Y sequences have no common subsequence:
1080 // mark all changed.
1081 while ($yoff < $ylim)
1082 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1083 while ($xoff < $xlim)
1084 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1086 // Use the partitions to split this problem into subproblems.
1089 while ($pt2 = next($seps)) {
1090 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1094 wfProfileOut( $fname );
1097 /* Adjust inserts/deletes of identical lines to join changes
1098 * as much as possible.
1100 * We do something when a run of changed lines include a
1101 * line at one end and has an excluded, identical line at the other.
1102 * We are free to choose which identical line is included.
1103 * `compareseq' usually chooses the one at the beginning,
1104 * but usually it is cleaner to consider the following identical line
1105 * to be the "change".
1107 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1109 function _shift_boundaries ($lines, &$changed, $other_changed) {
1110 $fname = '_DiffEngine::_shift_boundaries';
1111 wfProfileIn( $fname );
1115 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1116 $len = sizeof($lines);
1117 $other_len = sizeof($other_changed);
1121 * Scan forwards to find beginning of another run of changes.
1122 * Also keep track of the corresponding point in the other file.
1124 * Throughout this code, $i and $j are adjusted together so that
1125 * the first $i elements of $changed and the first $j elements
1126 * of $other_changed both contain the same number of zeros
1127 * (unchanged lines).
1128 * Furthermore, $j is always kept so that $j == $other_len or
1129 * $other_changed[$j] == false.
1131 while ($j < $other_len && $other_changed[$j])
1134 while ($i < $len && ! $changed[$i]) {
1135 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1137 while ($j < $other_len && $other_changed[$j])
1146 // Find the end of this run of changes.
1147 while (++
$i < $len && $changed[$i])
1152 * Record the length of this run of changes, so that
1153 * we can later determine whether the run has grown.
1155 $runlength = $i - $start;
1158 * Move the changed region back, so long as the
1159 * previous unchanged line matches the last changed one.
1160 * This merges with previous changed regions.
1162 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1163 $changed[--$start] = 1;
1164 $changed[--$i] = false;
1165 while ($start > 0 && $changed[$start - 1])
1167 USE_ASSERTS
&& assert('$j > 0');
1168 while ($other_changed[--$j])
1170 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1174 * Set CORRESPONDING to the end of the changed run, at the last
1175 * point where it corresponds to a changed run in the other file.
1176 * CORRESPONDING == LEN means no such point has been found.
1178 $corresponding = $j < $other_len ?
$i : $len;
1181 * Move the changed region forward, so long as the
1182 * first changed line matches the following unchanged one.
1183 * This merges with following changed regions.
1184 * Do this second, so that if there are no merges,
1185 * the changed region is moved forward as far as possible.
1187 while ($i < $len && $lines[$start] == $lines[$i]) {
1188 $changed[$start++
] = false;
1190 while ($i < $len && $changed[$i])
1193 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1195 if ($j < $other_len && $other_changed[$j]) {
1196 $corresponding = $i;
1197 while ($j < $other_len && $other_changed[$j])
1201 } while ($runlength != $i - $start);
1204 * If possible, move the fully-merged run of changes
1205 * back to a corresponding run in the other file.
1207 while ($corresponding < $i) {
1208 $changed[--$start] = 1;
1210 USE_ASSERTS
&& assert('$j > 0');
1211 while ($other_changed[--$j])
1213 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1216 wfProfileOut( $fname );
1221 * Class representing a 'diff' between two sequences of strings.
1224 * @addtogroup DifferenceEngine
1232 * Computes diff between sequences of strings.
1234 * @param $from_lines array An array of strings.
1235 * (Typically these are lines from a file.)
1236 * @param $to_lines array An array of strings.
1238 function Diff($from_lines, $to_lines) {
1239 $eng = new _DiffEngine
;
1240 $this->edits
= $eng->diff($from_lines, $to_lines);
1241 //$this->_check($from_lines, $to_lines);
1245 * Compute reversed Diff.
1249 * $diff = new Diff($lines1, $lines2);
1250 * $rev = $diff->reverse();
1251 * @return object A Diff object representing the inverse of the
1254 function reverse () {
1256 $rev->edits
= array();
1257 foreach ($this->edits
as $edit) {
1258 $rev->edits
[] = $edit->reverse();
1264 * Check for empty diff.
1266 * @return bool True iff two sequences were identical.
1268 function isEmpty () {
1269 foreach ($this->edits
as $edit) {
1270 if ($edit->type
!= 'copy')
1277 * Compute the length of the Longest Common Subsequence (LCS).
1279 * This is mostly for diagnostic purposed.
1281 * @return int The length of the LCS.
1285 foreach ($this->edits
as $edit) {
1286 if ($edit->type
== 'copy')
1287 $lcs +
= sizeof($edit->orig
);
1293 * Get the original set of lines.
1295 * This reconstructs the $from_lines parameter passed to the
1298 * @return array The original sequence of strings.
1303 foreach ($this->edits
as $edit) {
1305 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1311 * Get the closing set of lines.
1313 * This reconstructs the $to_lines parameter passed to the
1316 * @return array The sequence of strings.
1318 function closing() {
1321 foreach ($this->edits
as $edit) {
1323 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1329 * Check a Diff for validity.
1331 * This is here only for debugging purposes.
1333 function _check ($from_lines, $to_lines) {
1334 $fname = 'Diff::_check';
1335 wfProfileIn( $fname );
1336 if (serialize($from_lines) != serialize($this->orig()))
1337 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1338 if (serialize($to_lines) != serialize($this->closing()))
1339 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1341 $rev = $this->reverse();
1342 if (serialize($to_lines) != serialize($rev->orig()))
1343 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1344 if (serialize($from_lines) != serialize($rev->closing()))
1345 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1349 foreach ($this->edits
as $edit) {
1350 if ( $prevtype == $edit->type
)
1351 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1352 $prevtype = $edit->type
;
1355 $lcs = $this->lcs();
1356 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1357 wfProfileOut( $fname );
1362 * @todo document, bad name.
1364 * @addtogroup DifferenceEngine
1366 class MappedDiff
extends Diff
1371 * Computes diff between sequences of strings.
1373 * This can be used to compute things like
1374 * case-insensitve diffs, or diffs which ignore
1375 * changes in white-space.
1377 * @param $from_lines array An array of strings.
1378 * (Typically these are lines from a file.)
1380 * @param $to_lines array An array of strings.
1382 * @param $mapped_from_lines array This array should
1383 * have the same size number of elements as $from_lines.
1384 * The elements in $mapped_from_lines and
1385 * $mapped_to_lines are what is actually compared
1386 * when computing the diff.
1388 * @param $mapped_to_lines array This array should
1389 * have the same number of elements as $to_lines.
1391 function MappedDiff($from_lines, $to_lines,
1392 $mapped_from_lines, $mapped_to_lines) {
1393 $fname = 'MappedDiff::MappedDiff';
1394 wfProfileIn( $fname );
1396 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1397 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1399 $this->Diff($mapped_from_lines, $mapped_to_lines);
1402 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1403 $orig = &$this->edits
[$i]->orig
;
1404 if (is_array($orig)) {
1405 $orig = array_slice($from_lines, $xi, sizeof($orig));
1406 $xi +
= sizeof($orig);
1409 $closing = &$this->edits
[$i]->closing
;
1410 if (is_array($closing)) {
1411 $closing = array_slice($to_lines, $yi, sizeof($closing));
1412 $yi +
= sizeof($closing);
1415 wfProfileOut( $fname );
1420 * A class to format Diffs
1422 * This class formats the diff in classic diff format.
1423 * It is intended that this class be customized via inheritance,
1424 * to obtain fancier outputs.
1427 * @addtogroup DifferenceEngine
1432 * Number of leading context "lines" to preserve.
1434 * This should be left at zero for this class, but subclasses
1435 * may want to set this to other values.
1437 var $leading_context_lines = 0;
1440 * Number of trailing context "lines" to preserve.
1442 * This should be left at zero for this class, but subclasses
1443 * may want to set this to other values.
1445 var $trailing_context_lines = 0;
1450 * @param $diff object A Diff object.
1451 * @return string The formatted output.
1453 function format($diff) {
1454 $fname = 'DiffFormatter::format';
1455 wfProfileIn( $fname );
1461 $nlead = $this->leading_context_lines
;
1462 $ntrail = $this->trailing_context_lines
;
1464 $this->_start_diff();
1466 foreach ($diff->edits
as $edit) {
1467 if ($edit->type
== 'copy') {
1468 if (is_array($block)) {
1469 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1474 $context = array_slice($edit->orig
, 0, $ntrail);
1475 $block[] = new _DiffOp_Copy($context);
1477 $this->_block($x0, $ntrail +
$xi - $x0,
1478 $y0, $ntrail +
$yi - $y0,
1483 $context = $edit->orig
;
1486 if (! is_array($block)) {
1487 $context = array_slice($context, sizeof($context) - $nlead);
1488 $x0 = $xi - sizeof($context);
1489 $y0 = $yi - sizeof($context);
1492 $block[] = new _DiffOp_Copy($context);
1498 $xi +
= sizeof($edit->orig
);
1500 $yi +
= sizeof($edit->closing
);
1503 if (is_array($block))
1504 $this->_block($x0, $xi - $x0,
1508 $end = $this->_end_diff();
1509 wfProfileOut( $fname );
1513 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1514 $fname = 'DiffFormatter::_block';
1515 wfProfileIn( $fname );
1516 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1517 foreach ($edits as $edit) {
1518 if ($edit->type
== 'copy')
1519 $this->_context($edit->orig
);
1520 elseif ($edit->type
== 'add')
1521 $this->_added($edit->closing
);
1522 elseif ($edit->type
== 'delete')
1523 $this->_deleted($edit->orig
);
1524 elseif ($edit->type
== 'change')
1525 $this->_changed($edit->orig
, $edit->closing
);
1527 trigger_error('Unknown edit type', E_USER_ERROR
);
1529 $this->_end_block();
1530 wfProfileOut( $fname );
1533 function _start_diff() {
1537 function _end_diff() {
1538 $val = ob_get_contents();
1543 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1545 $xbeg .= "," . ($xbeg +
$xlen - 1);
1547 $ybeg .= "," . ($ybeg +
$ylen - 1);
1549 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1552 function _start_block($header) {
1556 function _end_block() {
1559 function _lines($lines, $prefix = ' ') {
1560 foreach ($lines as $line)
1561 echo "$prefix $line\n";
1564 function _context($lines) {
1565 $this->_lines($lines);
1568 function _added($lines) {
1569 $this->_lines($lines, '>');
1571 function _deleted($lines) {
1572 $this->_lines($lines, '<');
1575 function _changed($orig, $closing) {
1576 $this->_deleted($orig);
1578 $this->_added($closing);
1584 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1588 define('NBSP', ' '); // iso-8859-x non-breaking space.
1593 * @addtogroup DifferenceEngine
1595 class _HWLDF_WordAccumulator
{
1596 function _HWLDF_WordAccumulator () {
1597 $this->_lines
= array();
1603 function _flushGroup ($new_tag) {
1604 if ($this->_group
!== '') {
1605 if ($this->_tag
== 'ins')
1606 $this->_line
.= '<ins class="diffchange">' .
1607 htmlspecialchars ( $this->_group
) . '</ins>';
1608 elseif ($this->_tag
== 'del')
1609 $this->_line
.= '<del class="diffchange">' .
1610 htmlspecialchars ( $this->_group
) . '</del>';
1612 $this->_line
.= htmlspecialchars ( $this->_group
);
1615 $this->_tag
= $new_tag;
1618 function _flushLine ($new_tag) {
1619 $this->_flushGroup($new_tag);
1620 if ($this->_line
!= '')
1621 array_push ( $this->_lines
, $this->_line
);
1623 # make empty lines visible by inserting an NBSP
1624 array_push ( $this->_lines
, NBSP
);
1628 function addWords ($words, $tag = '') {
1629 if ($tag != $this->_tag
)
1630 $this->_flushGroup($tag);
1632 foreach ($words as $word) {
1633 // new-line should only come as first char of word.
1636 if ($word[0] == "\n") {
1637 $this->_flushLine($tag);
1638 $word = substr($word, 1);
1640 assert(!strstr($word, "\n"));
1641 $this->_group
.= $word;
1645 function getLines() {
1646 $this->_flushLine('~done');
1647 return $this->_lines
;
1654 * @addtogroup DifferenceEngine
1656 class WordLevelDiff
extends MappedDiff
1658 const MAX_LINE_LENGTH
= 10000;
1660 function WordLevelDiff ($orig_lines, $closing_lines) {
1661 $fname = 'WordLevelDiff::WordLevelDiff';
1662 wfProfileIn( $fname );
1664 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1665 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1667 $this->MappedDiff($orig_words, $closing_words,
1668 $orig_stripped, $closing_stripped);
1669 wfProfileOut( $fname );
1672 function _split($lines) {
1673 $fname = 'WordLevelDiff::_split';
1674 wfProfileIn( $fname );
1677 $stripped = array();
1679 foreach ( $lines as $line ) {
1680 # If the line is too long, just pretend the entire line is one big word
1681 # This prevents resource exhaustion problems
1688 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1690 $stripped[] = $line;
1693 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1696 $words = array_merge( $words, $m[0] );
1697 $stripped = array_merge( $stripped, $m[1] );
1701 wfProfileOut( $fname );
1702 return array($words, $stripped);
1706 $fname = 'WordLevelDiff::orig';
1707 wfProfileIn( $fname );
1708 $orig = new _HWLDF_WordAccumulator
;
1710 foreach ($this->edits
as $edit) {
1711 if ($edit->type
== 'copy')
1712 $orig->addWords($edit->orig
);
1713 elseif ($edit->orig
)
1714 $orig->addWords($edit->orig
, 'del');
1716 $lines = $orig->getLines();
1717 wfProfileOut( $fname );
1721 function closing () {
1722 $fname = 'WordLevelDiff::closing';
1723 wfProfileIn( $fname );
1724 $closing = new _HWLDF_WordAccumulator
;
1726 foreach ($this->edits
as $edit) {
1727 if ($edit->type
== 'copy')
1728 $closing->addWords($edit->closing
);
1729 elseif ($edit->closing
)
1730 $closing->addWords($edit->closing
, 'ins');
1732 $lines = $closing->getLines();
1733 wfProfileOut( $fname );
1739 * Wikipedia Table style diff formatter.
1742 * @addtogroup DifferenceEngine
1744 class TableDiffFormatter
extends DiffFormatter
1746 function TableDiffFormatter() {
1747 $this->leading_context_lines
= 2;
1748 $this->trailing_context_lines
= 2;
1751 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1752 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1753 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1757 function _start_block( $header ) {
1761 function _end_block() {
1764 function _lines( $lines, $prefix=' ', $color='white' ) {
1767 # HTML-escape parameter before calling this
1768 function addedLine( $line ) {
1769 return $this->wrapLine( '+', 'diff-addedline', $line );
1772 # HTML-escape parameter before calling this
1773 function deletedLine( $line ) {
1774 return $this->wrapLine( '-', 'diff-deletedline', $line );
1777 # HTML-escape parameter before calling this
1778 function contextLine( $line ) {
1779 return $this->wrapLine( ' ', 'diff-context', $line );
1782 private function wrapLine( $marker, $class, $line ) {
1783 if( $line !== '' ) {
1784 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1785 $line = "<div>$line</div>";
1787 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1790 function emptyLine() {
1791 return '<td colspan="2"> </td>';
1794 function _added( $lines ) {
1795 foreach ($lines as $line) {
1796 echo '<tr>' . $this->emptyLine() .
1797 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1801 function _deleted($lines) {
1802 foreach ($lines as $line) {
1803 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1804 $this->emptyLine() . "</tr>\n";
1808 function _context( $lines ) {
1809 foreach ($lines as $line) {
1811 $this->contextLine( htmlspecialchars ( $line ) ) .
1812 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1816 function _changed( $orig, $closing ) {
1817 $fname = 'TableDiffFormatter::_changed';
1818 wfProfileIn( $fname );
1820 $diff = new WordLevelDiff( $orig, $closing );
1821 $del = $diff->orig();
1822 $add = $diff->closing();
1824 # Notice that WordLevelDiff returns HTML-escaped output.
1825 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1827 while ( $line = array_shift( $del ) ) {
1828 $aline = array_shift( $add );
1829 echo '<tr>' . $this->deletedLine( $line ) .
1830 $this->addedLine( $aline ) . "</tr>\n";
1832 foreach ($add as $line) { # If any leftovers
1833 echo '<tr>' . $this->emptyLine() .
1834 $this->addedLine( $line ) . "</tr>\n";
1836 wfProfileOut( $fname );