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.11' );
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 $wgOut->addStyle( 'common/diff.css' );
300 $wgOut->addHTML( $diff );
306 * Get diff table, including header
307 * Note that the interface has changed, it's no longer static.
308 * Returns false on error
310 function getDiff( $otitle, $ntitle ) {
311 $body = $this->getDiffBody();
312 if ( $body === false ) {
315 $multi = $this->getMultiNotice();
316 return $this->addHeader( $body, $otitle, $ntitle, $multi );
321 * Get the diff table body, without header
323 * Returns false on error
325 function getDiffBody() {
327 $fname = 'DifferenceEngine::getDiffBody';
328 wfProfileIn( $fname );
332 if ( $this->mOldid
&& $this->mNewid
) {
334 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
335 $difftext = $wgMemc->get( $key );
337 wfIncrStats( 'diff_cache_hit' );
338 $difftext = $this->localiseLineNumbers( $difftext );
339 $difftext .= "\n<!-- diff cache key $key -->\n";
340 wfProfileOut( $fname );
345 #loadtext is permission safe, this just clears out the diff
346 if ( !$this->loadText() ) {
347 wfProfileOut( $fname );
349 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
351 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
355 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
357 // Save to cache for 7 days
358 if ( $key !== false && $difftext !== false ) {
359 wfIncrStats( 'diff_cache_miss' );
360 $wgMemc->set( $key, $difftext, 7*86400 );
362 wfIncrStats( 'diff_uncacheable' );
364 // Replace line numbers with the text in the user's language
365 if ( $difftext !== false ) {
366 $difftext = $this->localiseLineNumbers( $difftext );
368 wfProfileOut( $fname );
373 * Generate a diff, no caching
374 * $otext and $ntext must be already segmented
376 function generateDiffBody( $otext, $ntext ) {
377 global $wgExternalDiffEngine, $wgContLang;
378 $fname = 'DifferenceEngine::generateDiffBody';
380 $otext = str_replace( "\r\n", "\n", $otext );
381 $ntext = str_replace( "\r\n", "\n", $ntext );
383 if ( $wgExternalDiffEngine == 'wikidiff' ) {
384 # For historical reasons, external diff engine expects
385 # input text to be HTML-escaped already
386 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
387 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
388 if( !function_exists( 'wikidiff_do_diff' ) ) {
389 dl('php_wikidiff.so');
391 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
394 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
395 # Better external diff engine, the 2 may some day be dropped
396 # This one does the escaping and segmenting itself
397 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
398 wfProfileIn( "$fname-dl" );
399 @dl
('php_wikidiff2.so');
400 wfProfileOut( "$fname-dl" );
402 if ( function_exists( 'wikidiff2_do_diff' ) ) {
403 wfProfileIn( 'wikidiff2_do_diff' );
404 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
405 wfProfileOut( 'wikidiff2_do_diff' );
409 if ( $wgExternalDiffEngine !== false ) {
411 global $wgTmpDirectory;
412 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
413 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
415 $tempFile1 = fopen( $tempName1, "w" );
417 wfProfileOut( $fname );
420 $tempFile2 = fopen( $tempName2, "w" );
422 wfProfileOut( $fname );
425 fwrite( $tempFile1, $otext );
426 fwrite( $tempFile2, $ntext );
427 fclose( $tempFile1 );
428 fclose( $tempFile2 );
429 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
430 wfProfileIn( "$fname-shellexec" );
431 $difftext = wfShellExec( $cmd );
432 wfProfileOut( "$fname-shellexec" );
433 unlink( $tempName1 );
434 unlink( $tempName2 );
439 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
440 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
441 $diffs = new Diff( $ota, $nta );
442 $formatter = new TableDiffFormatter();
443 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
448 * Replace line numbers with the text in the user's language
450 function localiseLineNumbers( $text ) {
451 return preg_replace_callback( '/<!--LINE (\d+)-->/',
452 array( &$this, 'localiseLineNumbersCb' ), $text );
455 function localiseLineNumbersCb( $matches ) {
457 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
462 * If there are revisions between the ones being compared, return a note saying so.
464 function getMultiNotice() {
465 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
468 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
469 // Comparing two different pages? Count would be meaningless.
473 $oldid = $this->mOldRev
->getId();
474 $newid = $this->mNewRev
->getId();
475 if ( $oldid > $newid ) {
476 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
479 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
483 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
488 * Add the header to a diff body
490 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
493 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
494 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
496 if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
497 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
501 <col class='diff-marker' />
502 <col class='diff-content' />
503 <col class='diff-marker' />
504 <col class='diff-content' />
506 <td colspan='2' class='diff-otitle'>{$otitle}</td>
507 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
512 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
514 return $header . $diff . "</table>";
518 * Use specified text instead of loading from the database
520 function setText( $oldText, $newText ) {
521 $this->mOldtext
= $oldText;
522 $this->mNewtext
= $newText;
523 $this->mTextLoaded
= 2;
527 * Load revision metadata for the specified articles. If newid is 0, then compare
528 * the old article in oldid to the current article; if oldid is 0, then
529 * compare the current article to the immediately previous one (ignoring the
532 * If oldid is false, leave the corresponding revision object set
533 * to false. This is impossible via ordinary user input, and is provided for
536 function loadRevisionData() {
538 if ( $this->mRevisionsLoaded
) {
541 // Whether it succeeds or fails, we don't want to try again
542 $this->mRevisionsLoaded
= true;
545 // Load the new revision object
546 if( $this->mNewid
) {
547 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
549 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
552 if( is_null( $this->mNewRev
) ) {
556 // Set assorted variables
557 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
558 $this->mNewPage
= $this->mNewRev
->getTitle();
559 if( $this->mNewRev
->isCurrent() ) {
560 $newLink = $this->mNewPage
->escapeLocalUrl();
561 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
562 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
564 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
565 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
568 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
569 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
570 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
572 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
573 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
576 // Load the old revision object
577 $this->mOldRev
= false;
578 if( $this->mOldid
) {
579 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
580 } elseif ( $this->mOldid
=== 0 ) {
581 $rev = $this->mNewRev
->getPrevious();
583 $this->mOldid
= $rev->getId();
584 $this->mOldRev
= $rev;
586 // No previous revision; mark to show as first-version only.
587 $this->mOldid
= false;
588 $this->mOldRev
= false;
590 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
592 if( is_null( $this->mOldRev
) ) {
596 if ( $this->mOldRev
) {
597 $this->mOldPage
= $this->mOldRev
->getTitle();
599 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
600 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
601 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
602 $this->mOldtitle
= "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
603 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
604 //now that we considered old rev, we can make undo link (bug 8133, multi-edit undo)
605 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
606 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
613 * Load the text of the revisions, as well as revision data.
615 function loadText() {
616 if ( $this->mTextLoaded
== 2 ) {
619 // Whether it succeeds or fails, we don't want to try again
620 $this->mTextLoaded
= 2;
623 if ( !$this->loadRevisionData() ) {
626 if ( $this->mOldRev
) {
627 // FIXME: permission tests
628 $this->mOldtext
= $this->mOldRev
->revText();
629 if ( $this->mOldtext
=== false ) {
633 if ( $this->mNewRev
) {
634 $this->mNewtext
= $this->mNewRev
->revText();
635 if ( $this->mNewtext
=== false ) {
643 * Load the text of the new revision, not the old one
645 function loadNewText() {
646 if ( $this->mTextLoaded
>= 1 ) {
649 $this->mTextLoaded
= 1;
651 if ( !$this->loadRevisionData() ) {
654 $this->mNewtext
= $this->mNewRev
->getText();
661 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
663 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
664 // You may copy this code freely under the conditions of the GPL.
667 define('USE_ASSERTS', function_exists('assert'));
672 * @addtogroup DifferenceEngine
680 trigger_error('pure virtual', E_USER_ERROR
);
684 return $this->orig ?
sizeof($this->orig
) : 0;
687 function nclosing() {
688 return $this->closing ?
sizeof($this->closing
) : 0;
695 * @addtogroup DifferenceEngine
697 class _DiffOp_Copy
extends _DiffOp
{
700 function _DiffOp_Copy ($orig, $closing = false) {
701 if (!is_array($closing))
704 $this->closing
= $closing;
708 return new _DiffOp_Copy($this->closing
, $this->orig
);
715 * @addtogroup DifferenceEngine
717 class _DiffOp_Delete
extends _DiffOp
{
718 var $type = 'delete';
720 function _DiffOp_Delete ($lines) {
721 $this->orig
= $lines;
722 $this->closing
= false;
726 return new _DiffOp_Add($this->orig
);
733 * @addtogroup DifferenceEngine
735 class _DiffOp_Add
extends _DiffOp
{
738 function _DiffOp_Add ($lines) {
739 $this->closing
= $lines;
744 return new _DiffOp_Delete($this->closing
);
751 * @addtogroup DifferenceEngine
753 class _DiffOp_Change
extends _DiffOp
{
754 var $type = 'change';
756 function _DiffOp_Change ($orig, $closing) {
758 $this->closing
= $closing;
762 return new _DiffOp_Change($this->closing
, $this->orig
);
768 * Class used internally by Diff to actually compute the diffs.
770 * The algorithm used here is mostly lifted from the perl module
771 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
772 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
774 * More ideas are taken from:
775 * http://www.ics.uci.edu/~eppstein/161/960229.html
777 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
778 * diffutils-2.7, which can be found at:
779 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
781 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
784 * Line length limits for robustness added by Tim Starling, 2005-08-31
786 * @author Geoffrey T. Dairiki, Tim Starling
788 * @addtogroup DifferenceEngine
792 const MAX_XREF_LENGTH
= 10000;
794 function diff ($from_lines, $to_lines) {
795 $fname = '_DiffEngine::diff';
796 wfProfileIn( $fname );
798 $n_from = sizeof($from_lines);
799 $n_to = sizeof($to_lines);
801 $this->xchanged
= $this->ychanged
= array();
802 $this->xv
= $this->yv
= array();
803 $this->xind
= $this->yind
= array();
805 unset($this->in_seq
);
808 // Skip leading common lines.
809 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
810 if ($from_lines[$skip] !== $to_lines[$skip])
812 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
814 // Skip trailing common lines.
815 $xi = $n_from; $yi = $n_to;
816 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
817 if ($from_lines[$xi] !== $to_lines[$yi])
819 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
822 // Ignore lines which do not exist in both files.
823 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
824 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
827 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
828 $line = $to_lines[$yi];
829 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
831 $yhash[$this->_line_hash($line)] = 1;
835 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
836 $line = $from_lines[$xi];
837 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
844 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
846 // Merge edits when possible
847 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
848 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
850 // Compute the edit operations.
853 while ($xi < $n_from ||
$yi < $n_to) {
854 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
855 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
857 // Skip matching "snake".
859 while ( $xi < $n_from && $yi < $n_to
860 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
861 $copy[] = $from_lines[$xi++
];
865 $edits[] = new _DiffOp_Copy($copy);
867 // Find deletes & adds.
869 while ($xi < $n_from && $this->xchanged
[$xi])
870 $delete[] = $from_lines[$xi++
];
873 while ($yi < $n_to && $this->ychanged
[$yi])
874 $add[] = $to_lines[$yi++
];
877 $edits[] = new _DiffOp_Change($delete, $add);
879 $edits[] = new _DiffOp_Delete($delete);
881 $edits[] = new _DiffOp_Add($add);
883 wfProfileOut( $fname );
888 * Returns the whole line if it's small enough, or the MD5 hash otherwise
890 function _line_hash( $line ) {
891 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
899 /* Divide the Largest Common Subsequence (LCS) of the sequences
900 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
903 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
904 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
905 * sub sequences. The first sub-sequence is contained in [X0, X1),
906 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
907 * that (X0, Y0) == (XOFF, YOFF) and
908 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
910 * This function assumes that the first lines of the specified portions
911 * of the two files do not match, and likewise that the last lines do not
912 * match. The caller must trim matching lines from the beginning and end
913 * of the portions it is going to specify.
915 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
916 $fname = '_DiffEngine::_diag';
917 wfProfileIn( $fname );
920 if ($xlim - $xoff > $ylim - $yoff) {
921 // Things seems faster (I'm not sure I understand why)
922 // when the shortest sequence in X.
924 list ($xoff, $xlim, $yoff, $ylim)
925 = array( $yoff, $ylim, $xoff, $xlim);
929 for ($i = $ylim - 1; $i >= $yoff; $i--)
930 $ymatches[$this->xv
[$i]][] = $i;
932 for ($i = $ylim - 1; $i >= $yoff; $i--)
933 $ymatches[$this->yv
[$i]][] = $i;
936 $this->seq
[0]= $yoff - 1;
937 $this->in_seq
= array();
940 $numer = $xlim - $xoff +
$nchunks - 1;
942 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
943 wfProfileIn( "$fname-chunk" );
945 for ($i = 0; $i <= $this->lcs
; $i++
)
946 $ymids[$i][$chunk-1] = $this->seq
[$i];
948 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
949 for ( ; $x < $x1; $x++
) {
950 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
951 if (empty($ymatches[$line]))
953 $matches = $ymatches[$line];
955 while (list ($junk, $y) = each($matches))
956 if (empty($this->in_seq
[$y])) {
957 $k = $this->_lcs_pos($y);
958 USE_ASSERTS
&& assert($k > 0);
959 $ymids[$k] = $ymids[$k-1];
962 while (list ( /* $junk */, $y) = each($matches)) {
963 if ($y > $this->seq
[$k-1]) {
964 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
965 // Optimization: this is a common case:
966 // next match is just replacing previous match.
967 $this->in_seq
[$this->seq
[$k]] = false;
969 $this->in_seq
[$y] = 1;
970 } else if (empty($this->in_seq
[$y])) {
971 $k = $this->_lcs_pos($y);
972 USE_ASSERTS
&& assert($k > 0);
973 $ymids[$k] = $ymids[$k-1];
977 wfProfileOut( "$fname-chunk" );
980 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
981 $ymid = $ymids[$this->lcs
];
982 for ($n = 0; $n < $nchunks - 1; $n++
) {
983 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
985 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
987 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
989 wfProfileOut( $fname );
990 return array($this->lcs
, $seps);
993 function _lcs_pos ($ypos) {
994 $fname = '_DiffEngine::_lcs_pos';
995 wfProfileIn( $fname );
998 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
999 $this->seq
[++
$this->lcs
] = $ypos;
1000 $this->in_seq
[$ypos] = 1;
1001 wfProfileOut( $fname );
1006 while ($beg < $end) {
1007 $mid = (int)(($beg +
$end) / 2);
1008 if ( $ypos > $this->seq
[$mid] )
1014 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1016 $this->in_seq
[$this->seq
[$end]] = false;
1017 $this->seq
[$end] = $ypos;
1018 $this->in_seq
[$ypos] = 1;
1019 wfProfileOut( $fname );
1023 /* Find LCS of two sequences.
1025 * The results are recorded in the vectors $this->{x,y}changed[], by
1026 * storing a 1 in the element for each line that is an insertion
1027 * or deletion (ie. is not in the LCS).
1029 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1031 * Note that XLIM, YLIM are exclusive bounds.
1032 * All line numbers are origin-0 and discarded lines are not counted.
1034 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1035 $fname = '_DiffEngine::_compareseq';
1036 wfProfileIn( $fname );
1038 // Slide down the bottom initial diagonal.
1039 while ($xoff < $xlim && $yoff < $ylim
1040 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1045 // Slide up the top initial diagonal.
1046 while ($xlim > $xoff && $ylim > $yoff
1047 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1052 if ($xoff == $xlim ||
$yoff == $ylim)
1055 // This is ad hoc but seems to work well.
1056 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1057 //$nchunks = max(2,min(8,(int)$nchunks));
1058 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1060 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1064 // X and Y sequences have no common subsequence:
1065 // mark all changed.
1066 while ($yoff < $ylim)
1067 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1068 while ($xoff < $xlim)
1069 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1071 // Use the partitions to split this problem into subproblems.
1074 while ($pt2 = next($seps)) {
1075 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1079 wfProfileOut( $fname );
1082 /* Adjust inserts/deletes of identical lines to join changes
1083 * as much as possible.
1085 * We do something when a run of changed lines include a
1086 * line at one end and has an excluded, identical line at the other.
1087 * We are free to choose which identical line is included.
1088 * `compareseq' usually chooses the one at the beginning,
1089 * but usually it is cleaner to consider the following identical line
1090 * to be the "change".
1092 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1094 function _shift_boundaries ($lines, &$changed, $other_changed) {
1095 $fname = '_DiffEngine::_shift_boundaries';
1096 wfProfileIn( $fname );
1100 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1101 $len = sizeof($lines);
1102 $other_len = sizeof($other_changed);
1106 * Scan forwards to find beginning of another run of changes.
1107 * Also keep track of the corresponding point in the other file.
1109 * Throughout this code, $i and $j are adjusted together so that
1110 * the first $i elements of $changed and the first $j elements
1111 * of $other_changed both contain the same number of zeros
1112 * (unchanged lines).
1113 * Furthermore, $j is always kept so that $j == $other_len or
1114 * $other_changed[$j] == false.
1116 while ($j < $other_len && $other_changed[$j])
1119 while ($i < $len && ! $changed[$i]) {
1120 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1122 while ($j < $other_len && $other_changed[$j])
1131 // Find the end of this run of changes.
1132 while (++
$i < $len && $changed[$i])
1137 * Record the length of this run of changes, so that
1138 * we can later determine whether the run has grown.
1140 $runlength = $i - $start;
1143 * Move the changed region back, so long as the
1144 * previous unchanged line matches the last changed one.
1145 * This merges with previous changed regions.
1147 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1148 $changed[--$start] = 1;
1149 $changed[--$i] = false;
1150 while ($start > 0 && $changed[$start - 1])
1152 USE_ASSERTS
&& assert('$j > 0');
1153 while ($other_changed[--$j])
1155 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1159 * Set CORRESPONDING to the end of the changed run, at the last
1160 * point where it corresponds to a changed run in the other file.
1161 * CORRESPONDING == LEN means no such point has been found.
1163 $corresponding = $j < $other_len ?
$i : $len;
1166 * Move the changed region forward, so long as the
1167 * first changed line matches the following unchanged one.
1168 * This merges with following changed regions.
1169 * Do this second, so that if there are no merges,
1170 * the changed region is moved forward as far as possible.
1172 while ($i < $len && $lines[$start] == $lines[$i]) {
1173 $changed[$start++
] = false;
1175 while ($i < $len && $changed[$i])
1178 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1180 if ($j < $other_len && $other_changed[$j]) {
1181 $corresponding = $i;
1182 while ($j < $other_len && $other_changed[$j])
1186 } while ($runlength != $i - $start);
1189 * If possible, move the fully-merged run of changes
1190 * back to a corresponding run in the other file.
1192 while ($corresponding < $i) {
1193 $changed[--$start] = 1;
1195 USE_ASSERTS
&& assert('$j > 0');
1196 while ($other_changed[--$j])
1198 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1201 wfProfileOut( $fname );
1206 * Class representing a 'diff' between two sequences of strings.
1209 * @addtogroup DifferenceEngine
1217 * Computes diff between sequences of strings.
1219 * @param $from_lines array An array of strings.
1220 * (Typically these are lines from a file.)
1221 * @param $to_lines array An array of strings.
1223 function Diff($from_lines, $to_lines) {
1224 $eng = new _DiffEngine
;
1225 $this->edits
= $eng->diff($from_lines, $to_lines);
1226 //$this->_check($from_lines, $to_lines);
1230 * Compute reversed Diff.
1234 * $diff = new Diff($lines1, $lines2);
1235 * $rev = $diff->reverse();
1236 * @return object A Diff object representing the inverse of the
1239 function reverse () {
1241 $rev->edits
= array();
1242 foreach ($this->edits
as $edit) {
1243 $rev->edits
[] = $edit->reverse();
1249 * Check for empty diff.
1251 * @return bool True iff two sequences were identical.
1253 function isEmpty () {
1254 foreach ($this->edits
as $edit) {
1255 if ($edit->type
!= 'copy')
1262 * Compute the length of the Longest Common Subsequence (LCS).
1264 * This is mostly for diagnostic purposed.
1266 * @return int The length of the LCS.
1270 foreach ($this->edits
as $edit) {
1271 if ($edit->type
== 'copy')
1272 $lcs +
= sizeof($edit->orig
);
1278 * Get the original set of lines.
1280 * This reconstructs the $from_lines parameter passed to the
1283 * @return array The original sequence of strings.
1288 foreach ($this->edits
as $edit) {
1290 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1296 * Get the closing set of lines.
1298 * This reconstructs the $to_lines parameter passed to the
1301 * @return array The sequence of strings.
1303 function closing() {
1306 foreach ($this->edits
as $edit) {
1308 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1314 * Check a Diff for validity.
1316 * This is here only for debugging purposes.
1318 function _check ($from_lines, $to_lines) {
1319 $fname = 'Diff::_check';
1320 wfProfileIn( $fname );
1321 if (serialize($from_lines) != serialize($this->orig()))
1322 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1323 if (serialize($to_lines) != serialize($this->closing()))
1324 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1326 $rev = $this->reverse();
1327 if (serialize($to_lines) != serialize($rev->orig()))
1328 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1329 if (serialize($from_lines) != serialize($rev->closing()))
1330 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1334 foreach ($this->edits
as $edit) {
1335 if ( $prevtype == $edit->type
)
1336 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1337 $prevtype = $edit->type
;
1340 $lcs = $this->lcs();
1341 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1342 wfProfileOut( $fname );
1347 * @todo document, bad name.
1349 * @addtogroup DifferenceEngine
1351 class MappedDiff
extends Diff
1356 * Computes diff between sequences of strings.
1358 * This can be used to compute things like
1359 * case-insensitve diffs, or diffs which ignore
1360 * changes in white-space.
1362 * @param $from_lines array An array of strings.
1363 * (Typically these are lines from a file.)
1365 * @param $to_lines array An array of strings.
1367 * @param $mapped_from_lines array This array should
1368 * have the same size number of elements as $from_lines.
1369 * The elements in $mapped_from_lines and
1370 * $mapped_to_lines are what is actually compared
1371 * when computing the diff.
1373 * @param $mapped_to_lines array This array should
1374 * have the same number of elements as $to_lines.
1376 function MappedDiff($from_lines, $to_lines,
1377 $mapped_from_lines, $mapped_to_lines) {
1378 $fname = 'MappedDiff::MappedDiff';
1379 wfProfileIn( $fname );
1381 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1382 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1384 $this->Diff($mapped_from_lines, $mapped_to_lines);
1387 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1388 $orig = &$this->edits
[$i]->orig
;
1389 if (is_array($orig)) {
1390 $orig = array_slice($from_lines, $xi, sizeof($orig));
1391 $xi +
= sizeof($orig);
1394 $closing = &$this->edits
[$i]->closing
;
1395 if (is_array($closing)) {
1396 $closing = array_slice($to_lines, $yi, sizeof($closing));
1397 $yi +
= sizeof($closing);
1400 wfProfileOut( $fname );
1405 * A class to format Diffs
1407 * This class formats the diff in classic diff format.
1408 * It is intended that this class be customized via inheritance,
1409 * to obtain fancier outputs.
1412 * @addtogroup DifferenceEngine
1417 * Number of leading 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 $leading_context_lines = 0;
1425 * Number of trailing context "lines" to preserve.
1427 * This should be left at zero for this class, but subclasses
1428 * may want to set this to other values.
1430 var $trailing_context_lines = 0;
1435 * @param $diff object A Diff object.
1436 * @return string The formatted output.
1438 function format($diff) {
1439 $fname = 'DiffFormatter::format';
1440 wfProfileIn( $fname );
1446 $nlead = $this->leading_context_lines
;
1447 $ntrail = $this->trailing_context_lines
;
1449 $this->_start_diff();
1451 foreach ($diff->edits
as $edit) {
1452 if ($edit->type
== 'copy') {
1453 if (is_array($block)) {
1454 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1459 $context = array_slice($edit->orig
, 0, $ntrail);
1460 $block[] = new _DiffOp_Copy($context);
1462 $this->_block($x0, $ntrail +
$xi - $x0,
1463 $y0, $ntrail +
$yi - $y0,
1468 $context = $edit->orig
;
1471 if (! is_array($block)) {
1472 $context = array_slice($context, sizeof($context) - $nlead);
1473 $x0 = $xi - sizeof($context);
1474 $y0 = $yi - sizeof($context);
1477 $block[] = new _DiffOp_Copy($context);
1483 $xi +
= sizeof($edit->orig
);
1485 $yi +
= sizeof($edit->closing
);
1488 if (is_array($block))
1489 $this->_block($x0, $xi - $x0,
1493 $end = $this->_end_diff();
1494 wfProfileOut( $fname );
1498 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1499 $fname = 'DiffFormatter::_block';
1500 wfProfileIn( $fname );
1501 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1502 foreach ($edits as $edit) {
1503 if ($edit->type
== 'copy')
1504 $this->_context($edit->orig
);
1505 elseif ($edit->type
== 'add')
1506 $this->_added($edit->closing
);
1507 elseif ($edit->type
== 'delete')
1508 $this->_deleted($edit->orig
);
1509 elseif ($edit->type
== 'change')
1510 $this->_changed($edit->orig
, $edit->closing
);
1512 trigger_error('Unknown edit type', E_USER_ERROR
);
1514 $this->_end_block();
1515 wfProfileOut( $fname );
1518 function _start_diff() {
1522 function _end_diff() {
1523 $val = ob_get_contents();
1528 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1530 $xbeg .= "," . ($xbeg +
$xlen - 1);
1532 $ybeg .= "," . ($ybeg +
$ylen - 1);
1534 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1537 function _start_block($header) {
1541 function _end_block() {
1544 function _lines($lines, $prefix = ' ') {
1545 foreach ($lines as $line)
1546 echo "$prefix $line\n";
1549 function _context($lines) {
1550 $this->_lines($lines);
1553 function _added($lines) {
1554 $this->_lines($lines, '>');
1556 function _deleted($lines) {
1557 $this->_lines($lines, '<');
1560 function _changed($orig, $closing) {
1561 $this->_deleted($orig);
1563 $this->_added($closing);
1569 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1573 define('NBSP', ' '); // iso-8859-x non-breaking space.
1578 * @addtogroup DifferenceEngine
1580 class _HWLDF_WordAccumulator
{
1581 function _HWLDF_WordAccumulator () {
1582 $this->_lines
= array();
1588 function _flushGroup ($new_tag) {
1589 if ($this->_group
!== '') {
1590 if ($this->_tag
== 'ins')
1591 $this->_line
.= '<ins class="diffchange">' .
1592 htmlspecialchars ( $this->_group
) . '</ins>';
1593 elseif ($this->_tag
== 'del')
1594 $this->_line
.= '<del class="diffchange">' .
1595 htmlspecialchars ( $this->_group
) . '</del>';
1597 $this->_line
.= htmlspecialchars ( $this->_group
);
1600 $this->_tag
= $new_tag;
1603 function _flushLine ($new_tag) {
1604 $this->_flushGroup($new_tag);
1605 if ($this->_line
!= '')
1606 array_push ( $this->_lines
, $this->_line
);
1608 # make empty lines visible by inserting an NBSP
1609 array_push ( $this->_lines
, NBSP
);
1613 function addWords ($words, $tag = '') {
1614 if ($tag != $this->_tag
)
1615 $this->_flushGroup($tag);
1617 foreach ($words as $word) {
1618 // new-line should only come as first char of word.
1621 if ($word[0] == "\n") {
1622 $this->_flushLine($tag);
1623 $word = substr($word, 1);
1625 assert(!strstr($word, "\n"));
1626 $this->_group
.= $word;
1630 function getLines() {
1631 $this->_flushLine('~done');
1632 return $this->_lines
;
1639 * @addtogroup DifferenceEngine
1641 class WordLevelDiff
extends MappedDiff
1643 const MAX_LINE_LENGTH
= 10000;
1645 function WordLevelDiff ($orig_lines, $closing_lines) {
1646 $fname = 'WordLevelDiff::WordLevelDiff';
1647 wfProfileIn( $fname );
1649 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1650 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1652 $this->MappedDiff($orig_words, $closing_words,
1653 $orig_stripped, $closing_stripped);
1654 wfProfileOut( $fname );
1657 function _split($lines) {
1658 $fname = 'WordLevelDiff::_split';
1659 wfProfileIn( $fname );
1662 $stripped = array();
1664 foreach ( $lines as $line ) {
1665 # If the line is too long, just pretend the entire line is one big word
1666 # This prevents resource exhaustion problems
1673 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1675 $stripped[] = $line;
1678 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1681 $words = array_merge( $words, $m[0] );
1682 $stripped = array_merge( $stripped, $m[1] );
1686 wfProfileOut( $fname );
1687 return array($words, $stripped);
1691 $fname = 'WordLevelDiff::orig';
1692 wfProfileIn( $fname );
1693 $orig = new _HWLDF_WordAccumulator
;
1695 foreach ($this->edits
as $edit) {
1696 if ($edit->type
== 'copy')
1697 $orig->addWords($edit->orig
);
1698 elseif ($edit->orig
)
1699 $orig->addWords($edit->orig
, 'del');
1701 $lines = $orig->getLines();
1702 wfProfileOut( $fname );
1706 function closing () {
1707 $fname = 'WordLevelDiff::closing';
1708 wfProfileIn( $fname );
1709 $closing = new _HWLDF_WordAccumulator
;
1711 foreach ($this->edits
as $edit) {
1712 if ($edit->type
== 'copy')
1713 $closing->addWords($edit->closing
);
1714 elseif ($edit->closing
)
1715 $closing->addWords($edit->closing
, 'ins');
1717 $lines = $closing->getLines();
1718 wfProfileOut( $fname );
1724 * Wikipedia Table style diff formatter.
1727 * @addtogroup DifferenceEngine
1729 class TableDiffFormatter
extends DiffFormatter
1731 function TableDiffFormatter() {
1732 $this->leading_context_lines
= 2;
1733 $this->trailing_context_lines
= 2;
1736 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1737 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1738 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1742 function _start_block( $header ) {
1746 function _end_block() {
1749 function _lines( $lines, $prefix=' ', $color='white' ) {
1752 # HTML-escape parameter before calling this
1753 function addedLine( $line ) {
1754 return $this->wrapLine( '+', 'diff-addedline', $line );
1757 # HTML-escape parameter before calling this
1758 function deletedLine( $line ) {
1759 return $this->wrapLine( '-', 'diff-deletedline', $line );
1762 # HTML-escape parameter before calling this
1763 function contextLine( $line ) {
1764 return $this->wrapLine( ' ', 'diff-context', $line );
1767 private function wrapLine( $marker, $class, $line ) {
1768 if( $line !== '' ) {
1769 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1770 $line = "<div>$line</div>";
1772 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1775 function emptyLine() {
1776 return '<td colspan="2"> </td>';
1779 function _added( $lines ) {
1780 foreach ($lines as $line) {
1781 echo '<tr>' . $this->emptyLine() .
1782 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1786 function _deleted($lines) {
1787 foreach ($lines as $line) {
1788 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1789 $this->emptyLine() . "</tr>\n";
1793 function _context( $lines ) {
1794 foreach ($lines as $line) {
1796 $this->contextLine( htmlspecialchars ( $line ) ) .
1797 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1801 function _changed( $orig, $closing ) {
1802 $fname = 'TableDiffFormatter::_changed';
1803 wfProfileIn( $fname );
1805 $diff = new WordLevelDiff( $orig, $closing );
1806 $del = $diff->orig();
1807 $add = $diff->closing();
1809 # Notice that WordLevelDiff returns HTML-escaped output.
1810 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1812 while ( $line = array_shift( $del ) ) {
1813 $aline = array_shift( $add );
1814 echo '<tr>' . $this->deletedLine( $line ) .
1815 $this->addedLine( $aline ) . "</tr>\n";
1817 foreach ($add as $line) { # If any leftovers
1818 echo '<tr>' . $this->emptyLine() .
1819 $this->addedLine( $line ) . "</tr>\n";
1821 wfProfileOut( $fname );