4 * @addtogroup DifferenceEngine
10 * @addtogroup DifferenceEngine
12 class DifferenceEngine
{
16 var $mOldid, $mNewid, $mTitle;
17 var $mOldtitle, $mNewtitle, $mPagetitle;
18 var $mOldtext, $mNewtext;
19 var $mOldPage, $mNewPage;
20 var $mRcidMarkPatrolled;
21 var $mOldRev, $mNewRev;
22 var $mRevisionsLoaded = false; // Have the revisions been loaded
23 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
28 * @param $titleObj Title object that the diff is associated with
29 * @param $old Integer: old ID we want to show and diff with.
30 * @param $new String: either 'prev' or 'next'.
31 * @param $rcid Integer: ??? FIXME (default 0)
33 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
34 $this->mTitle
= $titleObj;
35 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
37 if ( 'prev' === $new ) {
38 # Show diff between revision $old and the previous one.
39 # Get previous one from DB.
41 $this->mNewid
= intval($old);
43 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
45 } elseif ( 'next' === $new ) {
46 # Show diff between revision $old and the previous one.
47 # Get previous one from DB.
49 $this->mOldid
= intval($old);
50 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
51 if ( false === $this->mNewid
) {
52 # if no result, NewId points to the newest old revision. The only newer
53 # revision is cur, which is "0".
58 $this->mOldid
= intval($old);
59 $this->mNewid
= intval($new);
61 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
64 function showDiffPage( $diffOnly = false ) {
65 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
66 $fname = 'DifferenceEngine::showDiffPage';
67 wfProfileIn( $fname );
69 # If external diffs are enabled both globally and for the user,
70 # we'll use the application/x-external-editor interface to call
71 # an external diff tool like kompare, kdiff3, etc.
72 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
73 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
75 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
76 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
77 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
78 $special=$wgLang->getNsText(NS_SPECIAL
);
83 Script={$wgServer}{$wgScript}
84 Special namespace={$special}
98 $wgOut->setArticleFlag( false );
99 if ( ! $this->loadRevisionData() ) {
100 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
101 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
102 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
103 $wgOut->addWikitext( $mtext );
104 wfProfileOut( $fname );
108 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
110 if ( $this->mNewRev
->isCurrent() ) {
111 $wgOut->setArticleFlag( true );
114 # mOldid is false if the difference engine is called with a "vague" query for
115 # a diff between a version V and its previous version V' AND the version V
116 # is the first version of that article. In that case, V' does not exist.
117 if ( $this->mOldid
=== false ) {
118 $this->showFirstRevision();
119 $this->renderNewRevision(); // should we respect $diffOnly here or not?
120 wfProfileOut( $fname );
124 $wgOut->suppressQuickbar();
126 $oldTitle = $this->mOldPage
->getPrefixedText();
127 $newTitle = $this->mNewPage
->getPrefixedText();
128 if( $oldTitle == $newTitle ) {
129 $wgOut->setPageTitle( $newTitle );
131 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
133 $wgOut->setSubtitle( wfMsg( 'difference' ) );
134 $wgOut->setRobotpolicy( 'noindex,nofollow' );
136 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
137 $wgOut->loginToUse();
139 wfProfileOut( $fname );
143 $sk = $wgUser->getSkin();
145 if ( $this->mNewRev
->isCurrent() && $wgUser->isAllowed('rollback') ) {
146 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
150 if( $wgUseRCPatrol && $this->mRcidMarkPatrolled
!= 0 && $wgUser->isAllowed( 'patrol' ) ) {
151 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
156 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
157 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
158 if ( $this->mNewRev
->isCurrent() ) {
159 $nextlink = ' ';
161 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
162 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
168 if ($this->mOldRev
->mMinorEdit
== 1) {
169 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
170 wfMsg( 'minoreditletter') ) . ' ';
173 if ($this->mNewRev
->mMinorEdit
== 1) {
174 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
175 wfMsg( 'minoreditletter') ) . ' ';
178 $rdel = ''; $ldel = '';
179 if( $wgUser->isAllowed( 'deleterevision' ) ) {
180 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
181 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
182 // If revision was hidden from sysops
183 $ldel = wfMsgHtml('rev-delundel');
185 $ldel = $sk->makeKnownLinkObj( $revdel,
186 wfMsgHtml('rev-delundel'),
187 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
188 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
189 // Bolden oversighted content
190 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
191 $ldel = "<strong>$ldel</strong>";
193 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
194 // We don't currently handle well changing the top revision's settings
195 if( $this->mNewRev
->isCurrent() ) {
196 // If revision was hidden from sysops
197 $rdel = wfMsgHtml('rev-delundel');
198 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
199 // If revision was hidden from sysops
200 $rdel = wfMsgHtml('rev-delundel');
202 $rdel = $sk->makeKnownLinkObj( $revdel,
203 wfMsgHtml('rev-delundel'),
204 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
205 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
206 // Bolden oversighted content
207 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
208 $rdel = "<strong>$rdel</strong>";
210 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
213 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />" .
214 $sk->revUserTools( $this->mOldRev
, true ) . "<br />" .
215 $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . "$ldel<br />" .
217 $newHeader = "<strong>{$this->mNewtitle}</strong><br />" .
218 $sk->revUserTools( $this->mNewRev
, true ) . " $rollback<br />" .
219 $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . "$rdel<br />" .
222 $this->showDiff( $oldHeader, $newHeader );
225 $this->renderNewRevision();
227 wfProfileOut( $fname );
231 * Show the new revision of the page.
233 function renderNewRevision() {
235 $fname = 'DifferenceEngine::renderNewRevision';
236 wfProfileIn( $fname );
238 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
239 #add deleted rev tag if needed
240 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
241 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
242 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
243 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
246 if( !$this->mNewRev
->isCurrent() ) {
247 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
250 $this->loadNewText();
251 if( is_object( $this->mNewRev
) ) {
252 $wgOut->setRevisionId( $this->mNewRev
->getId() );
255 $wgOut->addWikiTextTidy( $this->mNewtext
);
257 if( !$this->mNewRev
->isCurrent() ) {
258 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
261 wfProfileOut( $fname );
265 * Show the first revision of an article. Uses normal diff headers in
266 * contrast to normal "old revision" display style.
268 function showFirstRevision() {
269 global $wgOut, $wgUser;
271 $fname = 'DifferenceEngine::showFirstRevision';
272 wfProfileIn( $fname );
274 # Get article text from the DB
276 if ( ! $this->loadNewText() ) {
277 $t = $this->mTitle
->getPrefixedText() . " (Diff: {$this->mOldid}, " .
279 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
280 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
281 $wgOut->addWikitext( $mtext );
282 wfProfileOut( $fname );
285 if ( $this->mNewRev
->isCurrent() ) {
286 $wgOut->setArticleFlag( true );
289 # Check if user is allowed to look at this page. If not, bail out.
291 if ( !( $this->mTitle
->userCanRead() ) ) {
292 $wgOut->loginToUse();
294 wfProfileOut( $fname );
298 # Prepare the header box
300 $sk = $wgUser->getSkin();
302 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
303 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
304 $sk->revUserTools( $this->mNewRev
) . "<br />" .
305 $sk->revComment( $this->mNewRev
) . "<br />" .
306 $nextlink . "</div>\n";
308 $wgOut->addHTML( $header );
310 $wgOut->setSubtitle( wfMsg( 'difference' ) );
311 $wgOut->setRobotpolicy( 'noindex,nofollow' );
313 wfProfileOut( $fname );
317 * Get the diff text, send it to $wgOut
318 * Returns false if the diff could not be generated, otherwise returns true
320 function showDiff( $otitle, $ntitle ) {
322 $diff = $this->getDiff( $otitle, $ntitle );
323 if ( $diff === false ) {
324 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
327 $wgOut->addHTML( $diff );
333 * Get diff table, including header
334 * Note that the interface has changed, it's no longer static.
335 * Returns false on error
337 function getDiff( $otitle, $ntitle ) {
338 $body = $this->getDiffBody();
339 if ( $body === false ) {
342 $multi = $this->getMultiNotice();
343 return $this->addHeader( $body, $otitle, $ntitle, $multi );
348 * Get the diff table body, without header
350 * Returns false on error
352 function getDiffBody() {
354 $fname = 'DifferenceEngine::getDiffBody';
355 wfProfileIn( $fname );
359 if ( $this->mOldid
&& $this->mNewid
) {
361 $key = wfMemcKey( 'diff', 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
362 $difftext = $wgMemc->get( $key );
364 wfIncrStats( 'diff_cache_hit' );
365 $difftext = $this->localiseLineNumbers( $difftext );
366 $difftext .= "\n<!-- diff cache key $key -->\n";
367 wfProfileOut( $fname );
372 // Loadtext is permission safe, this just clears out the diff
373 if ( !$this->loadText() ) {
374 wfProfileOut( $fname );
376 } else if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
378 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
382 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
384 // Save to cache for 7 days
385 // Only do this for public revs, otherwise an admin can view the diff and a non-admin can nab it!
386 if ( $this->mOldRev
&& $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
387 wfIncrStats( 'diff_uncacheable' );
388 } else if ( $this->mNewRev
&& $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
389 wfIncrStats( 'diff_uncacheable' );
390 } else if ( $key !== false && $difftext !== false ) {
391 wfIncrStats( 'diff_cache_miss' );
392 $wgMemc->set( $key, $difftext, 7*86400 );
394 wfIncrStats( 'diff_uncacheable' );
396 // Replace line numbers with the text in the user's language
397 if ( $difftext !== false ) {
398 $difftext = $this->localiseLineNumbers( $difftext );
400 wfProfileOut( $fname );
405 * Generate a diff, no caching
406 * $otext and $ntext must be already segmented
408 function generateDiffBody( $otext, $ntext ) {
409 global $wgExternalDiffEngine, $wgContLang;
410 $fname = 'DifferenceEngine::generateDiffBody';
412 $otext = str_replace( "\r\n", "\n", $otext );
413 $ntext = str_replace( "\r\n", "\n", $ntext );
415 if ( $wgExternalDiffEngine == 'wikidiff' ) {
416 # For historical reasons, external diff engine expects
417 # input text to be HTML-escaped already
418 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
419 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
420 if( !function_exists( 'wikidiff_do_diff' ) ) {
421 dl('php_wikidiff.so');
423 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
426 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
427 # Better external diff engine, the 2 may some day be dropped
428 # This one does the escaping and segmenting itself
429 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
430 wfProfileIn( "$fname-dl" );
431 @dl
('php_wikidiff2.so');
432 wfProfileOut( "$fname-dl" );
434 if ( function_exists( 'wikidiff2_do_diff' ) ) {
435 wfProfileIn( 'wikidiff2_do_diff' );
436 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
437 wfProfileOut( 'wikidiff2_do_diff' );
441 if ( $wgExternalDiffEngine !== false ) {
443 global $wgTmpDirectory;
444 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
445 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
447 $tempFile1 = fopen( $tempName1, "w" );
449 wfProfileOut( $fname );
452 $tempFile2 = fopen( $tempName2, "w" );
454 wfProfileOut( $fname );
457 fwrite( $tempFile1, $otext );
458 fwrite( $tempFile2, $ntext );
459 fclose( $tempFile1 );
460 fclose( $tempFile2 );
461 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
462 wfProfileIn( "$fname-shellexec" );
463 $difftext = wfShellExec( $cmd );
464 wfProfileOut( "$fname-shellexec" );
465 unlink( $tempName1 );
466 unlink( $tempName2 );
471 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
472 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
473 $diffs = new Diff( $ota, $nta );
474 $formatter = new TableDiffFormatter();
475 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
480 * Replace line numbers with the text in the user's language
482 function localiseLineNumbers( $text ) {
483 return preg_replace_callback( '/<!--LINE (\d+)-->/',
484 array( &$this, 'localiseLineNumbersCb' ), $text );
487 function localiseLineNumbersCb( $matches ) {
489 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
494 * If there are revisions between the ones being compared, return a note saying so.
496 function getMultiNotice() {
497 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
500 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
501 // Comparing two different pages? Count would be meaningless.
505 $oldid = $this->mOldRev
->getId();
506 $newid = $this->mNewRev
->getId();
507 if ( $oldid > $newid ) {
508 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
511 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
515 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
520 * Add the header to a diff body
522 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
526 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
528 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
529 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
534 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
536 return $header . $diff . "</table>";
540 * Use specified text instead of loading from the database
542 function setText( $oldText, $newText ) {
543 $this->mOldtext
= $oldText;
544 $this->mNewtext
= $newText;
545 $this->mTextLoaded
= 2;
549 * Load revision metadata for the specified articles. If newid is 0, then compare
550 * the old article in oldid to the current article; if oldid is 0, then
551 * compare the current article to the immediately previous one (ignoring the
554 * If oldid is false, leave the corresponding revision object set
555 * to false. This is impossible via ordinary user input, and is provided for
558 function loadRevisionData() {
560 if ( $this->mRevisionsLoaded
) {
563 // Whether it succeeds or fails, we don't want to try again
564 $this->mRevisionsLoaded
= true;
567 // Load the new revision object
568 if( $this->mNewid
) {
569 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
571 $this->mNewRev
= Revision
::newFromTitle( $this->mTitle
);
574 if( is_null( $this->mNewRev
) ) {
578 // Set assorted variables
579 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
580 $this->mNewPage
= $this->mNewRev
->getTitle();
581 if( $this->mNewRev
->isCurrent() ) {
582 $newLink = $this->mNewPage
->escapeLocalUrl();
583 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
584 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
586 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
587 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
590 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
591 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
592 $this->mPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
594 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>"
595 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
597 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
598 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
599 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
600 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
603 // Load the old revision object
604 $this->mOldRev
= false;
605 if( $this->mOldid
) {
606 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
607 } elseif ( $this->mOldid
=== 0 ) {
608 $rev = $this->mNewRev
->getPrevious();
610 $this->mOldid
= $rev->getId();
611 $this->mOldRev
= $rev;
613 // No previous revision; mark to show as first-version only.
614 $this->mOldid
= false;
615 $this->mOldRev
= false;
617 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
619 if( is_null( $this->mOldRev
) ) {
623 if ( $this->mOldRev
) {
624 $this->mOldPage
= $this->mOldRev
->getTitle();
626 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
627 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
628 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
629 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
631 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
632 . "(<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
633 // Now that we considered old rev, we can make undo link (bug 8133, multi-edit undo)
634 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undoto=' . $this->mNewid
);
635 if ( $this->mNewRev
->userCan(Revision
::DELETED_TEXT
) )
636 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
638 if ( !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
639 $this->mOldtitle
= "<span class='history-deleted'>{$this->mOldPagetitle}</span>";
640 } else if ( $this->mOldRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
641 $this->mOldtitle
= '<span class="history-deleted">'.$this->mOldtitle
.'</span>';
649 * Load the text of the revisions, as well as revision data.
651 function loadText() {
652 if ( $this->mTextLoaded
== 2 ) {
655 // Whether it succeeds or fails, we don't want to try again
656 $this->mTextLoaded
= 2;
659 if ( !$this->loadRevisionData() ) {
662 if ( $this->mOldRev
) {
663 $this->mOldtext
= $this->mOldRev
->revText();
664 if ( $this->mOldtext
=== false ) {
668 if ( $this->mNewRev
) {
669 $this->mNewtext
= $this->mNewRev
->revText();
670 if ( $this->mNewtext
=== false ) {
678 * Load the text of the new revision, not the old one
680 function loadNewText() {
681 if ( $this->mTextLoaded
>= 1 ) {
684 $this->mTextLoaded
= 1;
686 if ( !$this->loadRevisionData() ) {
689 $this->mNewtext
= $this->mNewRev
->getText();
696 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
698 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
699 // You may copy this code freely under the conditions of the GPL.
702 define('USE_ASSERTS', function_exists('assert'));
707 * @addtogroup DifferenceEngine
715 trigger_error('pure virtual', E_USER_ERROR
);
719 return $this->orig ?
sizeof($this->orig
) : 0;
722 function nclosing() {
723 return $this->closing ?
sizeof($this->closing
) : 0;
730 * @addtogroup DifferenceEngine
732 class _DiffOp_Copy
extends _DiffOp
{
735 function _DiffOp_Copy ($orig, $closing = false) {
736 if (!is_array($closing))
739 $this->closing
= $closing;
743 return new _DiffOp_Copy($this->closing
, $this->orig
);
750 * @addtogroup DifferenceEngine
752 class _DiffOp_Delete
extends _DiffOp
{
753 var $type = 'delete';
755 function _DiffOp_Delete ($lines) {
756 $this->orig
= $lines;
757 $this->closing
= false;
761 return new _DiffOp_Add($this->orig
);
768 * @addtogroup DifferenceEngine
770 class _DiffOp_Add
extends _DiffOp
{
773 function _DiffOp_Add ($lines) {
774 $this->closing
= $lines;
779 return new _DiffOp_Delete($this->closing
);
786 * @addtogroup DifferenceEngine
788 class _DiffOp_Change
extends _DiffOp
{
789 var $type = 'change';
791 function _DiffOp_Change ($orig, $closing) {
793 $this->closing
= $closing;
797 return new _DiffOp_Change($this->closing
, $this->orig
);
803 * Class used internally by Diff to actually compute the diffs.
805 * The algorithm used here is mostly lifted from the perl module
806 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
807 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
809 * More ideas are taken from:
810 * http://www.ics.uci.edu/~eppstein/161/960229.html
812 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
813 * diffutils-2.7, which can be found at:
814 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
816 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
819 * Line length limits for robustness added by Tim Starling, 2005-08-31
821 * @author Geoffrey T. Dairiki, Tim Starling
823 * @addtogroup DifferenceEngine
827 const MAX_XREF_LENGTH
= 10000;
829 function diff ($from_lines, $to_lines) {
830 $fname = '_DiffEngine::diff';
831 wfProfileIn( $fname );
833 $n_from = sizeof($from_lines);
834 $n_to = sizeof($to_lines);
836 $this->xchanged
= $this->ychanged
= array();
837 $this->xv
= $this->yv
= array();
838 $this->xind
= $this->yind
= array();
840 unset($this->in_seq
);
843 // Skip leading common lines.
844 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
845 if ($from_lines[$skip] !== $to_lines[$skip])
847 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
849 // Skip trailing common lines.
850 $xi = $n_from; $yi = $n_to;
851 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
852 if ($from_lines[$xi] !== $to_lines[$yi])
854 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
857 // Ignore lines which do not exist in both files.
858 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
859 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
862 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
863 $line = $to_lines[$yi];
864 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
866 $yhash[$this->_line_hash($line)] = 1;
870 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
871 $line = $from_lines[$xi];
872 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
879 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
881 // Merge edits when possible
882 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
883 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
885 // Compute the edit operations.
888 while ($xi < $n_from ||
$yi < $n_to) {
889 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
890 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
892 // Skip matching "snake".
894 while ( $xi < $n_from && $yi < $n_to
895 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
896 $copy[] = $from_lines[$xi++
];
900 $edits[] = new _DiffOp_Copy($copy);
902 // Find deletes & adds.
904 while ($xi < $n_from && $this->xchanged
[$xi])
905 $delete[] = $from_lines[$xi++
];
908 while ($yi < $n_to && $this->ychanged
[$yi])
909 $add[] = $to_lines[$yi++
];
912 $edits[] = new _DiffOp_Change($delete, $add);
914 $edits[] = new _DiffOp_Delete($delete);
916 $edits[] = new _DiffOp_Add($add);
918 wfProfileOut( $fname );
923 * Returns the whole line if it's small enough, or the MD5 hash otherwise
925 function _line_hash( $line ) {
926 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
934 /* Divide the Largest Common Subsequence (LCS) of the sequences
935 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
938 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
939 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
940 * sub sequences. The first sub-sequence is contained in [X0, X1),
941 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
942 * that (X0, Y0) == (XOFF, YOFF) and
943 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
945 * This function assumes that the first lines of the specified portions
946 * of the two files do not match, and likewise that the last lines do not
947 * match. The caller must trim matching lines from the beginning and end
948 * of the portions it is going to specify.
950 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
951 $fname = '_DiffEngine::_diag';
952 wfProfileIn( $fname );
955 if ($xlim - $xoff > $ylim - $yoff) {
956 // Things seems faster (I'm not sure I understand why)
957 // when the shortest sequence in X.
959 list ($xoff, $xlim, $yoff, $ylim)
960 = array( $yoff, $ylim, $xoff, $xlim);
964 for ($i = $ylim - 1; $i >= $yoff; $i--)
965 $ymatches[$this->xv
[$i]][] = $i;
967 for ($i = $ylim - 1; $i >= $yoff; $i--)
968 $ymatches[$this->yv
[$i]][] = $i;
971 $this->seq
[0]= $yoff - 1;
972 $this->in_seq
= array();
975 $numer = $xlim - $xoff +
$nchunks - 1;
977 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
978 wfProfileIn( "$fname-chunk" );
980 for ($i = 0; $i <= $this->lcs
; $i++
)
981 $ymids[$i][$chunk-1] = $this->seq
[$i];
983 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
984 for ( ; $x < $x1; $x++
) {
985 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
986 if (empty($ymatches[$line]))
988 $matches = $ymatches[$line];
990 while (list ($junk, $y) = each($matches))
991 if (empty($this->in_seq
[$y])) {
992 $k = $this->_lcs_pos($y);
993 USE_ASSERTS
&& assert($k > 0);
994 $ymids[$k] = $ymids[$k-1];
997 while (list ( /* $junk */, $y) = each($matches)) {
998 if ($y > $this->seq
[$k-1]) {
999 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1000 // Optimization: this is a common case:
1001 // next match is just replacing previous match.
1002 $this->in_seq
[$this->seq
[$k]] = false;
1003 $this->seq
[$k] = $y;
1004 $this->in_seq
[$y] = 1;
1005 } else if (empty($this->in_seq
[$y])) {
1006 $k = $this->_lcs_pos($y);
1007 USE_ASSERTS
&& assert($k > 0);
1008 $ymids[$k] = $ymids[$k-1];
1012 wfProfileOut( "$fname-chunk" );
1015 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1016 $ymid = $ymids[$this->lcs
];
1017 for ($n = 0; $n < $nchunks - 1; $n++
) {
1018 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1019 $y1 = $ymid[$n] +
1;
1020 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1022 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1024 wfProfileOut( $fname );
1025 return array($this->lcs
, $seps);
1028 function _lcs_pos ($ypos) {
1029 $fname = '_DiffEngine::_lcs_pos';
1030 wfProfileIn( $fname );
1033 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1034 $this->seq
[++
$this->lcs
] = $ypos;
1035 $this->in_seq
[$ypos] = 1;
1036 wfProfileOut( $fname );
1041 while ($beg < $end) {
1042 $mid = (int)(($beg +
$end) / 2);
1043 if ( $ypos > $this->seq
[$mid] )
1049 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1051 $this->in_seq
[$this->seq
[$end]] = false;
1052 $this->seq
[$end] = $ypos;
1053 $this->in_seq
[$ypos] = 1;
1054 wfProfileOut( $fname );
1058 /* Find LCS of two sequences.
1060 * The results are recorded in the vectors $this->{x,y}changed[], by
1061 * storing a 1 in the element for each line that is an insertion
1062 * or deletion (ie. is not in the LCS).
1064 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1066 * Note that XLIM, YLIM are exclusive bounds.
1067 * All line numbers are origin-0 and discarded lines are not counted.
1069 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1070 $fname = '_DiffEngine::_compareseq';
1071 wfProfileIn( $fname );
1073 // Slide down the bottom initial diagonal.
1074 while ($xoff < $xlim && $yoff < $ylim
1075 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1080 // Slide up the top initial diagonal.
1081 while ($xlim > $xoff && $ylim > $yoff
1082 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1087 if ($xoff == $xlim ||
$yoff == $ylim)
1090 // This is ad hoc but seems to work well.
1091 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1092 //$nchunks = max(2,min(8,(int)$nchunks));
1093 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1095 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1099 // X and Y sequences have no common subsequence:
1100 // mark all changed.
1101 while ($yoff < $ylim)
1102 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1103 while ($xoff < $xlim)
1104 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1106 // Use the partitions to split this problem into subproblems.
1109 while ($pt2 = next($seps)) {
1110 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1114 wfProfileOut( $fname );
1117 /* Adjust inserts/deletes of identical lines to join changes
1118 * as much as possible.
1120 * We do something when a run of changed lines include a
1121 * line at one end and has an excluded, identical line at the other.
1122 * We are free to choose which identical line is included.
1123 * `compareseq' usually chooses the one at the beginning,
1124 * but usually it is cleaner to consider the following identical line
1125 * to be the "change".
1127 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1129 function _shift_boundaries ($lines, &$changed, $other_changed) {
1130 $fname = '_DiffEngine::_shift_boundaries';
1131 wfProfileIn( $fname );
1135 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1136 $len = sizeof($lines);
1137 $other_len = sizeof($other_changed);
1141 * Scan forwards to find beginning of another run of changes.
1142 * Also keep track of the corresponding point in the other file.
1144 * Throughout this code, $i and $j are adjusted together so that
1145 * the first $i elements of $changed and the first $j elements
1146 * of $other_changed both contain the same number of zeros
1147 * (unchanged lines).
1148 * Furthermore, $j is always kept so that $j == $other_len or
1149 * $other_changed[$j] == false.
1151 while ($j < $other_len && $other_changed[$j])
1154 while ($i < $len && ! $changed[$i]) {
1155 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1157 while ($j < $other_len && $other_changed[$j])
1166 // Find the end of this run of changes.
1167 while (++
$i < $len && $changed[$i])
1172 * Record the length of this run of changes, so that
1173 * we can later determine whether the run has grown.
1175 $runlength = $i - $start;
1178 * Move the changed region back, so long as the
1179 * previous unchanged line matches the last changed one.
1180 * This merges with previous changed regions.
1182 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1183 $changed[--$start] = 1;
1184 $changed[--$i] = false;
1185 while ($start > 0 && $changed[$start - 1])
1187 USE_ASSERTS
&& assert('$j > 0');
1188 while ($other_changed[--$j])
1190 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1194 * Set CORRESPONDING to the end of the changed run, at the last
1195 * point where it corresponds to a changed run in the other file.
1196 * CORRESPONDING == LEN means no such point has been found.
1198 $corresponding = $j < $other_len ?
$i : $len;
1201 * Move the changed region forward, so long as the
1202 * first changed line matches the following unchanged one.
1203 * This merges with following changed regions.
1204 * Do this second, so that if there are no merges,
1205 * the changed region is moved forward as far as possible.
1207 while ($i < $len && $lines[$start] == $lines[$i]) {
1208 $changed[$start++
] = false;
1210 while ($i < $len && $changed[$i])
1213 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1215 if ($j < $other_len && $other_changed[$j]) {
1216 $corresponding = $i;
1217 while ($j < $other_len && $other_changed[$j])
1221 } while ($runlength != $i - $start);
1224 * If possible, move the fully-merged run of changes
1225 * back to a corresponding run in the other file.
1227 while ($corresponding < $i) {
1228 $changed[--$start] = 1;
1230 USE_ASSERTS
&& assert('$j > 0');
1231 while ($other_changed[--$j])
1233 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1236 wfProfileOut( $fname );
1241 * Class representing a 'diff' between two sequences of strings.
1244 * @addtogroup DifferenceEngine
1252 * Computes diff between sequences of strings.
1254 * @param $from_lines array An array of strings.
1255 * (Typically these are lines from a file.)
1256 * @param $to_lines array An array of strings.
1258 function Diff($from_lines, $to_lines) {
1259 $eng = new _DiffEngine
;
1260 $this->edits
= $eng->diff($from_lines, $to_lines);
1261 //$this->_check($from_lines, $to_lines);
1265 * Compute reversed Diff.
1269 * $diff = new Diff($lines1, $lines2);
1270 * $rev = $diff->reverse();
1271 * @return object A Diff object representing the inverse of the
1274 function reverse () {
1276 $rev->edits
= array();
1277 foreach ($this->edits
as $edit) {
1278 $rev->edits
[] = $edit->reverse();
1284 * Check for empty diff.
1286 * @return bool True iff two sequences were identical.
1288 function isEmpty () {
1289 foreach ($this->edits
as $edit) {
1290 if ($edit->type
!= 'copy')
1297 * Compute the length of the Longest Common Subsequence (LCS).
1299 * This is mostly for diagnostic purposed.
1301 * @return int The length of the LCS.
1305 foreach ($this->edits
as $edit) {
1306 if ($edit->type
== 'copy')
1307 $lcs +
= sizeof($edit->orig
);
1313 * Get the original set of lines.
1315 * This reconstructs the $from_lines parameter passed to the
1318 * @return array The original sequence of strings.
1323 foreach ($this->edits
as $edit) {
1325 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1331 * Get the closing set of lines.
1333 * This reconstructs the $to_lines parameter passed to the
1336 * @return array The sequence of strings.
1338 function closing() {
1341 foreach ($this->edits
as $edit) {
1343 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1349 * Check a Diff for validity.
1351 * This is here only for debugging purposes.
1353 function _check ($from_lines, $to_lines) {
1354 $fname = 'Diff::_check';
1355 wfProfileIn( $fname );
1356 if (serialize($from_lines) != serialize($this->orig()))
1357 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1358 if (serialize($to_lines) != serialize($this->closing()))
1359 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1361 $rev = $this->reverse();
1362 if (serialize($to_lines) != serialize($rev->orig()))
1363 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1364 if (serialize($from_lines) != serialize($rev->closing()))
1365 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1369 foreach ($this->edits
as $edit) {
1370 if ( $prevtype == $edit->type
)
1371 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1372 $prevtype = $edit->type
;
1375 $lcs = $this->lcs();
1376 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1377 wfProfileOut( $fname );
1385 * @addtogroup DifferenceEngine
1387 class MappedDiff
extends Diff
1392 * Computes diff between sequences of strings.
1394 * This can be used to compute things like
1395 * case-insensitve diffs, or diffs which ignore
1396 * changes in white-space.
1398 * @param $from_lines array An array of strings.
1399 * (Typically these are lines from a file.)
1401 * @param $to_lines array An array of strings.
1403 * @param $mapped_from_lines array This array should
1404 * have the same size number of elements as $from_lines.
1405 * The elements in $mapped_from_lines and
1406 * $mapped_to_lines are what is actually compared
1407 * when computing the diff.
1409 * @param $mapped_to_lines array This array should
1410 * have the same number of elements as $to_lines.
1412 function MappedDiff($from_lines, $to_lines,
1413 $mapped_from_lines, $mapped_to_lines) {
1414 $fname = 'MappedDiff::MappedDiff';
1415 wfProfileIn( $fname );
1417 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1418 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1420 $this->Diff($mapped_from_lines, $mapped_to_lines);
1423 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1424 $orig = &$this->edits
[$i]->orig
;
1425 if (is_array($orig)) {
1426 $orig = array_slice($from_lines, $xi, sizeof($orig));
1427 $xi +
= sizeof($orig);
1430 $closing = &$this->edits
[$i]->closing
;
1431 if (is_array($closing)) {
1432 $closing = array_slice($to_lines, $yi, sizeof($closing));
1433 $yi +
= sizeof($closing);
1436 wfProfileOut( $fname );
1441 * A class to format Diffs
1443 * This class formats the diff in classic diff format.
1444 * It is intended that this class be customized via inheritance,
1445 * to obtain fancier outputs.
1448 * @addtogroup DifferenceEngine
1453 * Number of leading context "lines" to preserve.
1455 * This should be left at zero for this class, but subclasses
1456 * may want to set this to other values.
1458 var $leading_context_lines = 0;
1461 * Number of trailing context "lines" to preserve.
1463 * This should be left at zero for this class, but subclasses
1464 * may want to set this to other values.
1466 var $trailing_context_lines = 0;
1471 * @param $diff object A Diff object.
1472 * @return string The formatted output.
1474 function format($diff) {
1475 $fname = 'DiffFormatter::format';
1476 wfProfileIn( $fname );
1482 $nlead = $this->leading_context_lines
;
1483 $ntrail = $this->trailing_context_lines
;
1485 $this->_start_diff();
1487 foreach ($diff->edits
as $edit) {
1488 if ($edit->type
== 'copy') {
1489 if (is_array($block)) {
1490 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1495 $context = array_slice($edit->orig
, 0, $ntrail);
1496 $block[] = new _DiffOp_Copy($context);
1498 $this->_block($x0, $ntrail +
$xi - $x0,
1499 $y0, $ntrail +
$yi - $y0,
1504 $context = $edit->orig
;
1507 if (! is_array($block)) {
1508 $context = array_slice($context, sizeof($context) - $nlead);
1509 $x0 = $xi - sizeof($context);
1510 $y0 = $yi - sizeof($context);
1513 $block[] = new _DiffOp_Copy($context);
1519 $xi +
= sizeof($edit->orig
);
1521 $yi +
= sizeof($edit->closing
);
1524 if (is_array($block))
1525 $this->_block($x0, $xi - $x0,
1529 $end = $this->_end_diff();
1530 wfProfileOut( $fname );
1534 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1535 $fname = 'DiffFormatter::_block';
1536 wfProfileIn( $fname );
1537 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1538 foreach ($edits as $edit) {
1539 if ($edit->type
== 'copy')
1540 $this->_context($edit->orig
);
1541 elseif ($edit->type
== 'add')
1542 $this->_added($edit->closing
);
1543 elseif ($edit->type
== 'delete')
1544 $this->_deleted($edit->orig
);
1545 elseif ($edit->type
== 'change')
1546 $this->_changed($edit->orig
, $edit->closing
);
1548 trigger_error('Unknown edit type', E_USER_ERROR
);
1550 $this->_end_block();
1551 wfProfileOut( $fname );
1554 function _start_diff() {
1558 function _end_diff() {
1559 $val = ob_get_contents();
1564 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1566 $xbeg .= "," . ($xbeg +
$xlen - 1);
1568 $ybeg .= "," . ($ybeg +
$ylen - 1);
1570 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1573 function _start_block($header) {
1577 function _end_block() {
1580 function _lines($lines, $prefix = ' ') {
1581 foreach ($lines as $line)
1582 echo "$prefix $line\n";
1585 function _context($lines) {
1586 $this->_lines($lines);
1589 function _added($lines) {
1590 $this->_lines($lines, '>');
1592 function _deleted($lines) {
1593 $this->_lines($lines, '<');
1596 function _changed($orig, $closing) {
1597 $this->_deleted($orig);
1599 $this->_added($closing);
1605 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1609 define('NBSP', ' '); // iso-8859-x non-breaking space.
1614 * @addtogroup DifferenceEngine
1616 class _HWLDF_WordAccumulator
{
1617 function _HWLDF_WordAccumulator () {
1618 $this->_lines
= array();
1624 function _flushGroup ($new_tag) {
1625 if ($this->_group
!== '') {
1626 if ($this->_tag
== 'ins')
1627 $this->_line
.= '<ins class="diffchange">' .
1628 htmlspecialchars ( $this->_group
) . '</ins>';
1629 elseif ($this->_tag
== 'del')
1630 $this->_line
.= '<del class="diffchange">' .
1631 htmlspecialchars ( $this->_group
) . '</del>';
1633 $this->_line
.= htmlspecialchars ( $this->_group
);
1636 $this->_tag
= $new_tag;
1639 function _flushLine ($new_tag) {
1640 $this->_flushGroup($new_tag);
1641 if ($this->_line
!= '')
1642 array_push ( $this->_lines
, $this->_line
);
1644 # make empty lines visible by inserting an NBSP
1645 array_push ( $this->_lines
, NBSP
);
1649 function addWords ($words, $tag = '') {
1650 if ($tag != $this->_tag
)
1651 $this->_flushGroup($tag);
1653 foreach ($words as $word) {
1654 // new-line should only come as first char of word.
1657 if ($word[0] == "\n") {
1658 $this->_flushLine($tag);
1659 $word = substr($word, 1);
1661 assert(!strstr($word, "\n"));
1662 $this->_group
.= $word;
1666 function getLines() {
1667 $this->_flushLine('~done');
1668 return $this->_lines
;
1675 * @addtogroup DifferenceEngine
1677 class WordLevelDiff
extends MappedDiff
1679 const MAX_LINE_LENGTH
= 10000;
1681 function WordLevelDiff ($orig_lines, $closing_lines) {
1682 $fname = 'WordLevelDiff::WordLevelDiff';
1683 wfProfileIn( $fname );
1685 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1686 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1688 $this->MappedDiff($orig_words, $closing_words,
1689 $orig_stripped, $closing_stripped);
1690 wfProfileOut( $fname );
1693 function _split($lines) {
1694 $fname = 'WordLevelDiff::_split';
1695 wfProfileIn( $fname );
1698 $stripped = array();
1700 foreach ( $lines as $line ) {
1701 # If the line is too long, just pretend the entire line is one big word
1702 # This prevents resource exhaustion problems
1709 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1711 $stripped[] = $line;
1714 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1717 $words = array_merge( $words, $m[0] );
1718 $stripped = array_merge( $stripped, $m[1] );
1722 wfProfileOut( $fname );
1723 return array($words, $stripped);
1727 $fname = 'WordLevelDiff::orig';
1728 wfProfileIn( $fname );
1729 $orig = new _HWLDF_WordAccumulator
;
1731 foreach ($this->edits
as $edit) {
1732 if ($edit->type
== 'copy')
1733 $orig->addWords($edit->orig
);
1734 elseif ($edit->orig
)
1735 $orig->addWords($edit->orig
, 'del');
1737 $lines = $orig->getLines();
1738 wfProfileOut( $fname );
1742 function closing () {
1743 $fname = 'WordLevelDiff::closing';
1744 wfProfileIn( $fname );
1745 $closing = new _HWLDF_WordAccumulator
;
1747 foreach ($this->edits
as $edit) {
1748 if ($edit->type
== 'copy')
1749 $closing->addWords($edit->closing
);
1750 elseif ($edit->closing
)
1751 $closing->addWords($edit->closing
, 'ins');
1753 $lines = $closing->getLines();
1754 wfProfileOut( $fname );
1760 * Wikipedia Table style diff formatter.
1763 * @addtogroup DifferenceEngine
1765 class TableDiffFormatter
extends DiffFormatter
1767 function TableDiffFormatter() {
1768 $this->leading_context_lines
= 2;
1769 $this->trailing_context_lines
= 2;
1772 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1773 $r = '<tr><td colspan="2" align="left"><strong><!--LINE '.$xbeg."--></strong></td>\n" .
1774 '<td colspan="2" align="left"><strong><!--LINE '.$ybeg."--></strong></td></tr>\n";
1778 function _start_block( $header ) {
1782 function _end_block() {
1785 function _lines( $lines, $prefix=' ', $color='white' ) {
1788 # HTML-escape parameter before calling this
1789 function addedLine( $line ) {
1790 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1793 # HTML-escape parameter before calling this
1794 function deletedLine( $line ) {
1795 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1798 # HTML-escape parameter before calling this
1799 function contextLine( $line ) {
1800 return "<td> </td><td class='diff-context'>{$line}</td>";
1803 function emptyLine() {
1804 return '<td colspan="2"> </td>';
1807 function _added( $lines ) {
1808 foreach ($lines as $line) {
1809 echo '<tr>' . $this->emptyLine() .
1810 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1814 function _deleted($lines) {
1815 foreach ($lines as $line) {
1816 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1817 $this->emptyLine() . "</tr>\n";
1821 function _context( $lines ) {
1822 foreach ($lines as $line) {
1824 $this->contextLine( htmlspecialchars ( $line ) ) .
1825 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1829 function _changed( $orig, $closing ) {
1830 $fname = 'TableDiffFormatter::_changed';
1831 wfProfileIn( $fname );
1833 $diff = new WordLevelDiff( $orig, $closing );
1834 $del = $diff->orig();
1835 $add = $diff->closing();
1837 # Notice that WordLevelDiff returns HTML-escaped output.
1838 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1840 while ( $line = array_shift( $del ) ) {
1841 $aline = array_shift( $add );
1842 echo '<tr>' . $this->deletedLine( $line ) .
1843 $this->addedLine( $aline ) . "</tr>\n";
1845 foreach ($add as $line) { # If any leftovers
1846 echo '<tr>' . $this->emptyLine() .
1847 $this->addedLine( $line ) . "</tr>\n";
1849 wfProfileOut( $fname );