1f88f5cf320868c6e68f9deb3fb24d3697264b86
3 * @defgroup DifferenceEngine DifferenceEngine
7 * Constant to indicate diff cache compatibility.
8 * Bump this when changing the diff formatting in a way that
9 * fixes important bugs or such to force cached diff views to
12 define( 'MW_DIFF_VERSION', '1.11a' );
16 * @ingroup DifferenceEngine
18 class DifferenceEngine
{
22 var $mOldid, $mNewid, $mTitle;
23 var $mOldtitle, $mNewtitle, $mPagetitle;
24 var $mOldtext, $mNewtext;
25 var $mOldPage, $mNewPage;
26 var $mRcidMarkPatrolled;
27 var $mOldRev, $mNewRev;
28 var $mRevisionsLoaded = false; // Have the revisions been loaded
29 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
34 * @param $titleObj Title object that the diff is associated with
35 * @param $old Integer: old ID we want to show and diff with.
36 * @param $new String: either 'prev' or 'next'.
37 * @param $rcid Integer: ??? FIXME (default 0)
38 * @param $refreshCache boolean If set, refreshes the diff cache
40 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0, $refreshCache = false ) {
41 $this->mTitle
= $titleObj;
42 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
44 if ( 'prev' === $new ) {
45 # Show diff between revision $old and the previous one.
46 # Get previous one from DB.
48 $this->mNewid
= intval($old);
50 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
52 } elseif ( 'next' === $new ) {
53 # Show diff between revision $old and the previous one.
54 # Get previous one from DB.
56 $this->mOldid
= intval($old);
57 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
58 if ( false === $this->mNewid
) {
59 # if no result, NewId points to the newest old revision. The only newer
60 # revision is cur, which is "0".
65 $this->mOldid
= intval($old);
66 $this->mNewid
= intval($new);
68 $this->mRcidMarkPatrolled
= intval($rcid); # force it to be an integer
69 $this->mRefreshCache
= $refreshCache;
76 function showDiffPage( $diffOnly = false ) {
77 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
78 wfProfileIn( __METHOD__
);
81 # If external diffs are enabled both globally and for the user,
82 # we'll use the application/x-external-editor interface to call
83 # an external diff tool like kompare, kdiff3, etc.
84 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
85 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
87 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
88 $url1=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mOldid
);
89 $url2=$this->mTitle
->getFullURL("action=raw&oldid=".$this->mNewid
);
90 $special=$wgLang->getNsText(NS_SPECIAL
);
95 Script={$wgServer}{$wgScript}
96 Special namespace={$special}
110 $wgOut->setArticleFlag( false );
111 if ( ! $this->loadRevisionData() ) {
112 $t = $this->mTitle
->getPrefixedText();
113 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
114 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
115 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
116 wfProfileOut( __METHOD__
);
120 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
122 if ( $this->mNewRev
->isCurrent() ) {
123 $wgOut->setArticleFlag( true );
126 # mOldid is false if the difference engine is called with a "vague" query for
127 # a diff between a version V and its previous version V' AND the version V
128 # is the first version of that article. In that case, V' does not exist.
129 if ( $this->mOldid
=== false ) {
130 $this->showFirstRevision();
131 $this->renderNewRevision(); // should we respect $diffOnly here or not?
132 wfProfileOut( __METHOD__
);
136 $wgOut->suppressQuickbar();
138 $oldTitle = $this->mOldPage
->getPrefixedText();
139 $newTitle = $this->mNewPage
->getPrefixedText();
140 if( $oldTitle == $newTitle ) {
141 $wgOut->setPageTitle( $newTitle );
143 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
145 $wgOut->setSubtitle( wfMsg( 'difference' ) );
146 $wgOut->setRobotPolicy( 'noindex,nofollow' );
148 if ( !( $this->mOldPage
->userCanRead() && $this->mNewPage
->userCanRead() ) ) {
149 $wgOut->loginToUse();
151 wfProfileOut( __METHOD__
);
155 $sk = $wgUser->getSkin();
157 // Check if page is editable
158 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
159 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
160 $rollback = ' ' . $sk->generateRollback( $this->mNewRev
);
165 // Prepare a change patrol link, if applicable
166 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
167 // If we've been given an explicit change identifier, use it; saves time
168 if( $this->mRcidMarkPatrolled
) {
169 $rcid = $this->mRcidMarkPatrolled
;
171 // Look for an unpatrolled change corresponding to this diff
172 $db = wfGetDB( DB_SLAVE
);
173 $change = RecentChange
::newFromConds(
175 // Add redundant user,timestamp condition so we can use the existing index
176 'rc_user_text' => $this->mNewRev
->getRawUserText(),
177 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
178 'rc_this_oldid' => $this->mNewid
,
179 'rc_last_oldid' => $this->mOldid
,
184 if( $change instanceof RecentChange
) {
185 $rcid = $change->mAttribs
['rc_id'];
193 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
195 wfMsgHtml( 'markaspatrolleddiff' ),
196 "action=markpatrolled&rcid={$rcid}"
205 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'previousdiff' ),
206 'diff=prev&oldid='.$this->mOldid
, '', '', 'id="differences-prevlink"' );
207 if ( $this->mNewRev
->isCurrent() ) {
208 $nextlink = ' ';
210 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ),
211 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
217 if ($this->mOldRev
->mMinorEdit
== 1) {
218 $oldminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
221 if ($this->mNewRev
->mMinorEdit
== 1) {
222 $newminor = Xml
::span( wfMsg( 'minoreditletter'), 'minor' ) . ' ';
225 $rdel = ''; $ldel = '';
226 if( $wgUser->isAllowed( 'deleterevision' ) ) {
227 $revdel = SpecialPage
::getTitleFor( 'Revisiondelete' );
228 if( !$this->mOldRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
229 // If revision was hidden from sysops
230 $ldel = wfMsgHtml('rev-delundel');
232 $ldel = $sk->makeKnownLinkObj( $revdel,
233 wfMsgHtml('rev-delundel'),
234 'target=' . urlencode( $this->mOldRev
->mTitle
->getPrefixedDbkey() ) .
235 '&oldid=' . urlencode( $this->mOldRev
->getId() ) );
236 // Bolden oversighted content
237 if( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
238 $ldel = "<strong>$ldel</strong>";
240 $ldel = " <tt>(<small>$ldel</small>)</tt> ";
241 // We don't currently handle well changing the top revision's settings
242 if( $this->mNewRev
->isCurrent() ) {
243 // If revision was hidden from sysops
244 $rdel = wfMsgHtml('rev-delundel');
245 } else if( !$this->mNewRev
->userCan( Revision
::DELETED_RESTRICTED
) ) {
246 // If revision was hidden from sysops
247 $rdel = wfMsgHtml('rev-delundel');
249 $rdel = $sk->makeKnownLinkObj( $revdel,
250 wfMsgHtml('rev-delundel'),
251 'target=' . urlencode( $this->mNewRev
->mTitle
->getPrefixedDbkey() ) .
252 '&oldid=' . urlencode( $this->mNewRev
->getId() ) );
253 // Bolden oversighted content
254 if( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
255 $rdel = "<strong>$rdel</strong>";
257 $rdel = " <tt>(<small>$rdel</small>)</tt> ";
260 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle
.'</strong></div>' .
261 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev
, true ) . "</div>" .
262 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev
, !$diffOnly, true ) . $ldel . "</div>" .
263 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
264 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle
.'</strong></div>' .
265 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, true ) . " $rollback</div>" .
266 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev
, !$diffOnly, true ) . $rdel . "</div>" .
267 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
269 if( $wgEnableHtmlDiff ) {
270 $this->renderHtmlDiff();
273 $this->showDiff( $oldHeader, $newHeader );
276 $this->renderNewRevision();
279 wfProfileOut( __METHOD__
);
283 * Show the new revision of the page.
285 function renderNewRevision() {
287 wfProfileIn( __METHOD__
);
289 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
290 #add deleted rev tag if needed
291 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
292 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
293 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
294 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
297 if( !$this->mNewRev
->isCurrent() ) {
298 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
301 $this->loadNewText();
302 if( is_object( $this->mNewRev
) ) {
303 $wgOut->setRevisionId( $this->mNewRev
->getId() );
306 if ($this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage()) {
307 // Stolen from Article::view --AG 2007-10-11
309 // Give hooks a chance to customise the output
310 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
311 // Wrap the whole lot in a <pre> and don't parse
313 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
314 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
315 $wgOut->addHtml( htmlspecialchars( $this->mNewtext
) );
316 $wgOut->addHtml( "\n</pre>\n" );
319 $wgOut->addWikiTextTidy( $this->mNewtext
);
321 if( !$this->mNewRev
->isCurrent() ) {
322 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
325 wfProfileOut( __METHOD__
);
329 function renderHtmlDiff() {
330 global $wgOut, $wgTitle, $wgParser;
331 wfProfileIn( __METHOD__
);
333 $this->showDiffStyle();
335 #add deleted rev tag if needed
336 if( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
337 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
338 } else if( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
339 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
342 if( !$this->mNewRev
->isCurrent() ) {
343 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
349 if( is_object( $this->mOldRev
) ) {
350 $wgOut->setRevisionId( $this->mOldRev
->getId() );
353 $popts = $wgOut->parserOptions();
354 $oldTidy = $popts->setTidy( true );
356 $parserOutput = $wgParser->parse( $this->mOldtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
357 $popts->setTidy( $oldTidy );
360 //$wgOut->addParserOutputNoText( $parserOutput );
361 $oldHtml = $parserOutput->getText();
362 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
365 if( is_object( $this->mNewRev
) ) {
366 $wgOut->setRevisionId( $this->mNewRev
->getId() );
369 $popts = $wgOut->parserOptions();
370 $oldTidy = $popts->setTidy( true );
372 $parserOutput = $wgParser->parse( $this->mNewtext
, $wgTitle, $popts, true, true, $wgOut->getRevisionId() );
373 $popts->setTidy( $oldTidy );
375 $wgOut->addParserOutputNoText( $parserOutput );
376 $newHtml = $parserOutput->getText();
377 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
379 unset($parserOutput, $popts);
381 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
382 $differ->htmlDiff($oldHtml, $newHtml);
384 wfProfileOut( __METHOD__
);
388 * Show the first revision of an article. Uses normal diff headers in
389 * contrast to normal "old revision" display style.
391 function showFirstRevision() {
392 global $wgOut, $wgUser;
393 wfProfileIn( __METHOD__
);
395 # Get article text from the DB
397 if ( ! $this->loadNewText() ) {
398 $t = $this->mTitle
->getPrefixedText();
399 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid
, $this->mNewid
);
400 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
401 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
402 wfProfileOut( __METHOD__
);
405 if ( $this->mNewRev
->isCurrent() ) {
406 $wgOut->setArticleFlag( true );
409 # Check if user is allowed to look at this page. If not, bail out.
411 if ( !( $this->mTitle
->userCanRead() ) ) {
412 $wgOut->loginToUse();
414 wfProfileOut( __METHOD__
);
418 # Prepare the header box
420 $sk = $wgUser->getSkin();
422 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid
, '', '', 'id="differences-nextlink"' );
423 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
424 $sk->revUserTools( $this->mNewRev
) . "<br />" .
425 $sk->revComment( $this->mNewRev
) . "<br />" .
426 $nextlink . "</div>\n";
428 $wgOut->addHTML( $header );
430 $wgOut->setSubtitle( wfMsg( 'difference' ) );
431 $wgOut->setRobotPolicy( 'noindex,nofollow' );
433 wfProfileOut( __METHOD__
);
437 * Get the diff text, send it to $wgOut
438 * Returns false if the diff could not be generated, otherwise returns true
440 function showDiff( $otitle, $ntitle ) {
442 $diff = $this->getDiff( $otitle, $ntitle );
443 if ( $diff === false ) {
444 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
447 $this->showDiffStyle();
448 $wgOut->addHTML( $diff );
454 * Add style sheets and supporting JS for diff display.
456 function showDiffStyle() {
457 global $wgStylePath, $wgStyleVersion, $wgOut;
458 $wgOut->addStyle( 'common/diff.css' );
460 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
461 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
465 * Get complete diff table, including header
467 * @param Title $otitle Old title
468 * @param Title $ntitle New title
471 function getDiff( $otitle, $ntitle ) {
472 $body = $this->getDiffBody();
473 if ( $body === false ) {
476 $multi = $this->getMultiNotice();
477 return $this->addHeader( $body, $otitle, $ntitle, $multi );
482 * Get the diff table body, without header
486 function getDiffBody() {
488 wfProfileIn( __METHOD__
);
489 // Check if the diff should be hidden from this user
490 if ( $this->mOldRev
&& !$this->mOldRev
->userCan(Revision
::DELETED_TEXT
) ) {
492 } else if ( $this->mNewRev
&& !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
497 if ( $this->mOldid
&& $this->mNewid
) {
498 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
, 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
500 if ( !$this->mRefreshCache
) {
501 $difftext = $wgMemc->get( $key );
503 wfIncrStats( 'diff_cache_hit' );
504 $difftext = $this->localiseLineNumbers( $difftext );
505 $difftext .= "\n<!-- diff cache key $key -->\n";
506 wfProfileOut( __METHOD__
);
509 } // don't try to load but save the result
512 // Loadtext is permission safe, this just clears out the diff
513 if ( !$this->loadText() ) {
514 wfProfileOut( __METHOD__
);
518 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
520 // Save to cache for 7 days
521 if ( $key !== false && $difftext !== false ) {
522 wfIncrStats( 'diff_cache_miss' );
523 $wgMemc->set( $key, $difftext, 7*86400 );
525 wfIncrStats( 'diff_uncacheable' );
527 // Replace line numbers with the text in the user's language
528 if ( $difftext !== false ) {
529 $difftext = $this->localiseLineNumbers( $difftext );
531 wfProfileOut( __METHOD__
);
536 * Generate a diff, no caching
537 * $otext and $ntext must be already segmented
539 function generateDiffBody( $otext, $ntext ) {
540 global $wgExternalDiffEngine, $wgContLang;
542 $otext = str_replace( "\r\n", "\n", $otext );
543 $ntext = str_replace( "\r\n", "\n", $ntext );
545 if ( $wgExternalDiffEngine == 'wikidiff' ) {
546 # For historical reasons, external diff engine expects
547 # input text to be HTML-escaped already
548 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
549 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
550 if( !function_exists( 'wikidiff_do_diff' ) ) {
551 dl('php_wikidiff.so');
553 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
554 $this->debug( 'wikidiff1' );
557 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
558 # Better external diff engine, the 2 may some day be dropped
559 # This one does the escaping and segmenting itself
560 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
561 wfProfileIn( __METHOD__
. "-dl" );
562 @dl
('php_wikidiff2.so');
563 wfProfileOut( __METHOD__
. "-dl" );
565 if ( function_exists( 'wikidiff2_do_diff' ) ) {
566 wfProfileIn( 'wikidiff2_do_diff' );
567 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
568 $text .= $this->debug( 'wikidiff2' );
569 wfProfileOut( 'wikidiff2_do_diff' );
573 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
575 global $wgTmpDirectory;
576 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
577 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
579 $tempFile1 = fopen( $tempName1, "w" );
581 wfProfileOut( __METHOD__
);
584 $tempFile2 = fopen( $tempName2, "w" );
586 wfProfileOut( __METHOD__
);
589 fwrite( $tempFile1, $otext );
590 fwrite( $tempFile2, $ntext );
591 fclose( $tempFile1 );
592 fclose( $tempFile2 );
593 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
594 wfProfileIn( __METHOD__
. "-shellexec" );
595 $difftext = wfShellExec( $cmd );
596 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
597 wfProfileOut( __METHOD__
. "-shellexec" );
598 unlink( $tempName1 );
599 unlink( $tempName2 );
604 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
605 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
606 $diffs = new Diff( $ota, $nta );
607 $formatter = new TableDiffFormatter();
608 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
613 * Generate a debug comment indicating diff generating time,
614 * server node, and generator backend.
616 protected function debug( $generator="internal" ) {
617 global $wgShowHostnames, $wgNodeName;
618 $data = array( $generator );
619 if( $wgShowHostnames ) {
620 $data[] = $wgNodeName;
622 $data[] = wfTimestamp( TS_DB
);
623 return "<!-- diff generator: " .
632 * Replace line numbers with the text in the user's language
634 function localiseLineNumbers( $text ) {
635 return preg_replace_callback( '/<!--LINE (\d+)-->/',
636 array( &$this, 'localiseLineNumbersCb' ), $text );
639 function localiseLineNumbersCb( $matches ) {
641 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
646 * If there are revisions between the ones being compared, return a note saying so.
648 function getMultiNotice() {
649 if ( !is_object($this->mOldRev
) ||
!is_object($this->mNewRev
) )
652 if( !$this->mOldPage
->equals( $this->mNewPage
) ) {
653 // Comparing two different pages? Count would be meaningless.
657 $oldid = $this->mOldRev
->getId();
658 $newid = $this->mNewRev
->getId();
659 if ( $oldid > $newid ) {
660 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
663 $n = $this->mTitle
->countRevisionsBetween( $oldid, $newid );
667 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
672 * Add the header to a diff body
674 static function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
679 <col class='diff-marker' />
680 <col class='diff-content' />
681 <col class='diff-marker' />
682 <col class='diff-content' />
684 <td colspan='2' class='diff-otitle'>{$otitle}</td>
685 <td colspan='2' class='diff-ntitle'>{$ntitle}</td>
690 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
692 return $header . $diff . "</table>";
696 * Use specified text instead of loading from the database
698 function setText( $oldText, $newText ) {
699 $this->mOldtext
= $oldText;
700 $this->mNewtext
= $newText;
701 $this->mTextLoaded
= 2;
705 * Load revision metadata for the specified articles. If newid is 0, then compare
706 * the old article in oldid to the current article; if oldid is 0, then
707 * compare the current article to the immediately previous one (ignoring the
710 * If oldid is false, leave the corresponding revision object set
711 * to false. This is impossible via ordinary user input, and is provided for
714 function loadRevisionData() {
716 if ( $this->mRevisionsLoaded
) {
719 // Whether it succeeds or fails, we don't want to try again
720 $this->mRevisionsLoaded
= true;
723 // Load the new revision object
724 $this->mNewRev
= $this->mNewid
725 ? Revision
::newFromId( $this->mNewid
)
726 : Revision
::newFromTitle( $this->mTitle
);
727 if( !$this->mNewRev
instanceof Revision
)
730 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
731 $this->mNewid
= $this->mNewRev
->getId();
733 // Check if page is editable
734 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
736 // Set assorted variables
737 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
738 $this->mNewPage
= $this->mNewRev
->getTitle();
739 if( $this->mNewRev
->isCurrent() ) {
740 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
741 $this->mPagetitle
= htmlspecialchars( wfMsg( 'currentrev' ) );
742 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit' );
744 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)";
745 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
748 $newLink = $this->mNewPage
->escapeLocalUrl( 'oldid=' . $this->mNewid
);
749 $newEdit = $this->mNewPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid
);
750 $this->mPagetitle
= wfMsgHTML( 'revisionasof', $timestamp );
752 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
753 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
755 if ( !$this->mNewRev
->userCan(Revision
::DELETED_TEXT
) ) {
756 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
757 } else if ( $this->mNewRev
->isDeleted(Revision
::DELETED_TEXT
) ) {
758 $this->mNewtitle
= '<span class="history-deleted">'.$this->mNewtitle
.'</span>';
761 // Load the old revision object
762 $this->mOldRev
= false;
763 if( $this->mOldid
) {
764 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
765 } elseif ( $this->mOldid
=== 0 ) {
766 $rev = $this->mNewRev
->getPrevious();
768 $this->mOldid
= $rev->getId();
769 $this->mOldRev
= $rev;
771 // No previous revision; mark to show as first-version only.
772 $this->mOldid
= false;
773 $this->mOldRev
= false;
775 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
777 if( is_null( $this->mOldRev
) ) {
781 if ( $this->mOldRev
) {
782 $this->mOldPage
= $this->mOldRev
->getTitle();
784 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
785 $oldLink = $this->mOldPage
->escapeLocalUrl( 'oldid=' . $this->mOldid
);
786 $oldEdit = $this->mOldPage
->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid
);
787 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t ) );
789 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
790 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
791 // Add an "undo" link
792 $newUndo = $this->mNewPage
->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid
. '&undo=' . $this->mNewid
);
793 if( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
794 $this->mNewtitle
.= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
797 if( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
798 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
799 } else if( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
800 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
808 * Load the text of the revisions, as well as revision data.
810 function loadText() {
811 if ( $this->mTextLoaded
== 2 ) {
814 // Whether it succeeds or fails, we don't want to try again
815 $this->mTextLoaded
= 2;
818 if ( !$this->loadRevisionData() ) {
821 if ( $this->mOldRev
) {
822 $this->mOldtext
= $this->mOldRev
->revText();
823 if ( $this->mOldtext
=== false ) {
827 if ( $this->mNewRev
) {
828 $this->mNewtext
= $this->mNewRev
->revText();
829 if ( $this->mNewtext
=== false ) {
837 * Load the text of the new revision, not the old one
839 function loadNewText() {
840 if ( $this->mTextLoaded
>= 1 ) {
843 $this->mTextLoaded
= 1;
845 if ( !$this->loadRevisionData() ) {
848 $this->mNewtext
= $this->mNewRev
->getText();
855 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
857 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
858 // You may copy this code freely under the conditions of the GPL.
861 define('USE_ASSERTS', function_exists('assert'));
866 * @ingroup DifferenceEngine
874 trigger_error('pure virtual', E_USER_ERROR
);
878 return $this->orig ?
sizeof($this->orig
) : 0;
881 function nclosing() {
882 return $this->closing ?
sizeof($this->closing
) : 0;
889 * @ingroup DifferenceEngine
891 class _DiffOp_Copy
extends _DiffOp
{
894 function _DiffOp_Copy ($orig, $closing = false) {
895 if (!is_array($closing))
898 $this->closing
= $closing;
902 return new _DiffOp_Copy($this->closing
, $this->orig
);
909 * @ingroup DifferenceEngine
911 class _DiffOp_Delete
extends _DiffOp
{
912 var $type = 'delete';
914 function _DiffOp_Delete ($lines) {
915 $this->orig
= $lines;
916 $this->closing
= false;
920 return new _DiffOp_Add($this->orig
);
927 * @ingroup DifferenceEngine
929 class _DiffOp_Add
extends _DiffOp
{
932 function _DiffOp_Add ($lines) {
933 $this->closing
= $lines;
938 return new _DiffOp_Delete($this->closing
);
945 * @ingroup DifferenceEngine
947 class _DiffOp_Change
extends _DiffOp
{
948 var $type = 'change';
950 function _DiffOp_Change ($orig, $closing) {
952 $this->closing
= $closing;
956 return new _DiffOp_Change($this->closing
, $this->orig
);
961 * Class used internally by Diff to actually compute the diffs.
963 * The algorithm used here is mostly lifted from the perl module
964 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
965 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
967 * More ideas are taken from:
968 * http://www.ics.uci.edu/~eppstein/161/960229.html
970 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
971 * diffutils-2.7, which can be found at:
972 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
974 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
977 * Line length limits for robustness added by Tim Starling, 2005-08-31
978 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
980 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
982 * @ingroup DifferenceEngine
986 const MAX_XREF_LENGTH
= 10000;
988 function diff ($from_lines, $to_lines){
989 wfProfileIn( __METHOD__
);
991 // Diff and store locally
992 $this->diff_local($from_lines, $to_lines);
994 // Merge edits when possible
995 $this->_shift_boundaries($from_lines, $this->xchanged
, $this->ychanged
);
996 $this->_shift_boundaries($to_lines, $this->ychanged
, $this->xchanged
);
998 // Compute the edit operations.
999 $n_from = sizeof($from_lines);
1000 $n_to = sizeof($to_lines);
1004 while ($xi < $n_from ||
$yi < $n_to) {
1005 USE_ASSERTS
&& assert($yi < $n_to ||
$this->xchanged
[$xi]);
1006 USE_ASSERTS
&& assert($xi < $n_from ||
$this->ychanged
[$yi]);
1008 // Skip matching "snake".
1010 while ( $xi < $n_from && $yi < $n_to
1011 && !$this->xchanged
[$xi] && !$this->ychanged
[$yi]) {
1012 $copy[] = $from_lines[$xi++
];
1016 $edits[] = new _DiffOp_Copy($copy);
1018 // Find deletes & adds.
1020 while ($xi < $n_from && $this->xchanged
[$xi])
1021 $delete[] = $from_lines[$xi++
];
1024 while ($yi < $n_to && $this->ychanged
[$yi])
1025 $add[] = $to_lines[$yi++
];
1027 if ($delete && $add)
1028 $edits[] = new _DiffOp_Change($delete, $add);
1030 $edits[] = new _DiffOp_Delete($delete);
1032 $edits[] = new _DiffOp_Add($add);
1034 wfProfileOut( __METHOD__
);
1038 function diff_local ($from_lines, $to_lines) {
1039 global $wgExternalDiffEngine;
1040 wfProfileIn( __METHOD__
);
1042 if($wgExternalDiffEngine == 'wikidiff3'){
1044 $wikidiff3 = new WikiDiff3();
1045 $wikidiff3->diff($from_lines, $to_lines);
1046 $this->xchanged
= $wikidiff3->removed
;
1047 $this->ychanged
= $wikidiff3->added
;
1051 $n_from = sizeof($from_lines);
1052 $n_to = sizeof($to_lines);
1053 $this->xchanged
= $this->ychanged
= array();
1054 $this->xv
= $this->yv
= array();
1055 $this->xind
= $this->yind
= array();
1057 unset($this->in_seq
);
1060 // Skip leading common lines.
1061 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++
) {
1062 if ($from_lines[$skip] !== $to_lines[$skip])
1064 $this->xchanged
[$skip] = $this->ychanged
[$skip] = false;
1066 // Skip trailing common lines.
1067 $xi = $n_from; $yi = $n_to;
1068 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++
) {
1069 if ($from_lines[$xi] !== $to_lines[$yi])
1071 $this->xchanged
[$xi] = $this->ychanged
[$yi] = false;
1074 // Ignore lines which do not exist in both files.
1075 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1076 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1079 for ($yi = $skip; $yi < $n_to - $endskip; $yi++
) {
1080 $line = $to_lines[$yi];
1081 if ( ($this->ychanged
[$yi] = empty($xhash[$this->_line_hash($line)])) )
1083 $yhash[$this->_line_hash($line)] = 1;
1084 $this->yv
[] = $line;
1085 $this->yind
[] = $yi;
1087 for ($xi = $skip; $xi < $n_from - $endskip; $xi++
) {
1088 $line = $from_lines[$xi];
1089 if ( ($this->xchanged
[$xi] = empty($yhash[$this->_line_hash($line)])) )
1091 $this->xv
[] = $line;
1092 $this->xind
[] = $xi;
1096 $this->_compareseq(0, sizeof($this->xv
), 0, sizeof($this->yv
));
1098 wfProfileOut( __METHOD__
);
1102 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1104 function _line_hash( $line ) {
1105 if ( strlen( $line ) > self
::MAX_XREF_LENGTH
) {
1106 return md5( $line );
1112 /* Divide the Largest Common Subsequence (LCS) of the sequences
1113 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1116 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1117 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1118 * sub sequences. The first sub-sequence is contained in [X0, X1),
1119 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1120 * that (X0, Y0) == (XOFF, YOFF) and
1121 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1123 * This function assumes that the first lines of the specified portions
1124 * of the two files do not match, and likewise that the last lines do not
1125 * match. The caller must trim matching lines from the beginning and end
1126 * of the portions it is going to specify.
1128 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1131 if ($xlim - $xoff > $ylim - $yoff) {
1132 // Things seems faster (I'm not sure I understand why)
1133 // when the shortest sequence in X.
1135 list ($xoff, $xlim, $yoff, $ylim)
1136 = array( $yoff, $ylim, $xoff, $xlim);
1140 for ($i = $ylim - 1; $i >= $yoff; $i--)
1141 $ymatches[$this->xv
[$i]][] = $i;
1143 for ($i = $ylim - 1; $i >= $yoff; $i--)
1144 $ymatches[$this->yv
[$i]][] = $i;
1147 $this->seq
[0]= $yoff - 1;
1148 $this->in_seq
= array();
1149 $ymids[0] = array();
1151 $numer = $xlim - $xoff +
$nchunks - 1;
1153 for ($chunk = 0; $chunk < $nchunks; $chunk++
) {
1155 for ($i = 0; $i <= $this->lcs
; $i++
)
1156 $ymids[$i][$chunk-1] = $this->seq
[$i];
1158 $x1 = $xoff +
(int)(($numer +
($xlim-$xoff)*$chunk) / $nchunks);
1159 for ( ; $x < $x1; $x++
) {
1160 $line = $flip ?
$this->yv
[$x] : $this->xv
[$x];
1161 if (empty($ymatches[$line]))
1163 $matches = $ymatches[$line];
1165 while (list ($junk, $y) = each($matches))
1166 if (empty($this->in_seq
[$y])) {
1167 $k = $this->_lcs_pos($y);
1168 USE_ASSERTS
&& assert($k > 0);
1169 $ymids[$k] = $ymids[$k-1];
1172 while (list ( /* $junk */, $y) = each($matches)) {
1173 if ($y > $this->seq
[$k-1]) {
1174 USE_ASSERTS
&& assert($y < $this->seq
[$k]);
1175 // Optimization: this is a common case:
1176 // next match is just replacing previous match.
1177 $this->in_seq
[$this->seq
[$k]] = false;
1178 $this->seq
[$k] = $y;
1179 $this->in_seq
[$y] = 1;
1180 } else if (empty($this->in_seq
[$y])) {
1181 $k = $this->_lcs_pos($y);
1182 USE_ASSERTS
&& assert($k > 0);
1183 $ymids[$k] = $ymids[$k-1];
1189 $seps[] = $flip ?
array($yoff, $xoff) : array($xoff, $yoff);
1190 $ymid = $ymids[$this->lcs
];
1191 for ($n = 0; $n < $nchunks - 1; $n++
) {
1192 $x1 = $xoff +
(int)(($numer +
($xlim - $xoff) * $n) / $nchunks);
1193 $y1 = $ymid[$n] +
1;
1194 $seps[] = $flip ?
array($y1, $x1) : array($x1, $y1);
1196 $seps[] = $flip ?
array($ylim, $xlim) : array($xlim, $ylim);
1198 return array($this->lcs
, $seps);
1201 function _lcs_pos ($ypos) {
1203 if ($end == 0 ||
$ypos > $this->seq
[$end]) {
1204 $this->seq
[++
$this->lcs
] = $ypos;
1205 $this->in_seq
[$ypos] = 1;
1210 while ($beg < $end) {
1211 $mid = (int)(($beg +
$end) / 2);
1212 if ( $ypos > $this->seq
[$mid] )
1218 USE_ASSERTS
&& assert($ypos != $this->seq
[$end]);
1220 $this->in_seq
[$this->seq
[$end]] = false;
1221 $this->seq
[$end] = $ypos;
1222 $this->in_seq
[$ypos] = 1;
1226 /* Find LCS of two sequences.
1228 * The results are recorded in the vectors $this->{x,y}changed[], by
1229 * storing a 1 in the element for each line that is an insertion
1230 * or deletion (ie. is not in the LCS).
1232 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1234 * Note that XLIM, YLIM are exclusive bounds.
1235 * All line numbers are origin-0 and discarded lines are not counted.
1237 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1238 // Slide down the bottom initial diagonal.
1239 while ($xoff < $xlim && $yoff < $ylim
1240 && $this->xv
[$xoff] == $this->yv
[$yoff]) {
1245 // Slide up the top initial diagonal.
1246 while ($xlim > $xoff && $ylim > $yoff
1247 && $this->xv
[$xlim - 1] == $this->yv
[$ylim - 1]) {
1252 if ($xoff == $xlim ||
$yoff == $ylim)
1255 // This is ad hoc but seems to work well.
1256 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1257 //$nchunks = max(2,min(8,(int)$nchunks));
1258 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) +
1;
1260 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1264 // X and Y sequences have no common subsequence:
1265 // mark all changed.
1266 while ($yoff < $ylim)
1267 $this->ychanged
[$this->yind
[$yoff++
]] = 1;
1268 while ($xoff < $xlim)
1269 $this->xchanged
[$this->xind
[$xoff++
]] = 1;
1271 // Use the partitions to split this problem into subproblems.
1274 while ($pt2 = next($seps)) {
1275 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1281 /* Adjust inserts/deletes of identical lines to join changes
1282 * as much as possible.
1284 * We do something when a run of changed lines include a
1285 * line at one end and has an excluded, identical line at the other.
1286 * We are free to choose which identical line is included.
1287 * `compareseq' usually chooses the one at the beginning,
1288 * but usually it is cleaner to consider the following identical line
1289 * to be the "change".
1291 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1293 function _shift_boundaries ($lines, &$changed, $other_changed) {
1294 wfProfileIn( __METHOD__
);
1298 USE_ASSERTS
&& assert('sizeof($lines) == sizeof($changed)');
1299 $len = sizeof($lines);
1300 $other_len = sizeof($other_changed);
1304 * Scan forwards to find beginning of another run of changes.
1305 * Also keep track of the corresponding point in the other file.
1307 * Throughout this code, $i and $j are adjusted together so that
1308 * the first $i elements of $changed and the first $j elements
1309 * of $other_changed both contain the same number of zeros
1310 * (unchanged lines).
1311 * Furthermore, $j is always kept so that $j == $other_len or
1312 * $other_changed[$j] == false.
1314 while ($j < $other_len && $other_changed[$j])
1317 while ($i < $len && ! $changed[$i]) {
1318 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1320 while ($j < $other_len && $other_changed[$j])
1329 // Find the end of this run of changes.
1330 while (++
$i < $len && $changed[$i])
1335 * Record the length of this run of changes, so that
1336 * we can later determine whether the run has grown.
1338 $runlength = $i - $start;
1341 * Move the changed region back, so long as the
1342 * previous unchanged line matches the last changed one.
1343 * This merges with previous changed regions.
1345 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1346 $changed[--$start] = 1;
1347 $changed[--$i] = false;
1348 while ($start > 0 && $changed[$start - 1])
1350 USE_ASSERTS
&& assert('$j > 0');
1351 while ($other_changed[--$j])
1353 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1357 * Set CORRESPONDING to the end of the changed run, at the last
1358 * point where it corresponds to a changed run in the other file.
1359 * CORRESPONDING == LEN means no such point has been found.
1361 $corresponding = $j < $other_len ?
$i : $len;
1364 * Move the changed region forward, so long as the
1365 * first changed line matches the following unchanged one.
1366 * This merges with following changed regions.
1367 * Do this second, so that if there are no merges,
1368 * the changed region is moved forward as far as possible.
1370 while ($i < $len && $lines[$start] == $lines[$i]) {
1371 $changed[$start++
] = false;
1373 while ($i < $len && $changed[$i])
1376 USE_ASSERTS
&& assert('$j < $other_len && ! $other_changed[$j]');
1378 if ($j < $other_len && $other_changed[$j]) {
1379 $corresponding = $i;
1380 while ($j < $other_len && $other_changed[$j])
1384 } while ($runlength != $i - $start);
1387 * If possible, move the fully-merged run of changes
1388 * back to a corresponding run in the other file.
1390 while ($corresponding < $i) {
1391 $changed[--$start] = 1;
1393 USE_ASSERTS
&& assert('$j > 0');
1394 while ($other_changed[--$j])
1396 USE_ASSERTS
&& assert('$j >= 0 && !$other_changed[$j]');
1399 wfProfileOut( __METHOD__
);
1404 * Class representing a 'diff' between two sequences of strings.
1407 * @ingroup DifferenceEngine
1415 * Computes diff between sequences of strings.
1417 * @param $from_lines array An array of strings.
1418 * (Typically these are lines from a file.)
1419 * @param $to_lines array An array of strings.
1421 function Diff($from_lines, $to_lines) {
1422 $eng = new _DiffEngine
;
1423 $this->edits
= $eng->diff($from_lines, $to_lines);
1424 //$this->_check($from_lines, $to_lines);
1428 * Compute reversed Diff.
1432 * $diff = new Diff($lines1, $lines2);
1433 * $rev = $diff->reverse();
1434 * @return object A Diff object representing the inverse of the
1437 function reverse () {
1439 $rev->edits
= array();
1440 foreach ($this->edits
as $edit) {
1441 $rev->edits
[] = $edit->reverse();
1447 * Check for empty diff.
1449 * @return bool True iff two sequences were identical.
1451 function isEmpty () {
1452 foreach ($this->edits
as $edit) {
1453 if ($edit->type
!= 'copy')
1460 * Compute the length of the Longest Common Subsequence (LCS).
1462 * This is mostly for diagnostic purposed.
1464 * @return int The length of the LCS.
1468 foreach ($this->edits
as $edit) {
1469 if ($edit->type
== 'copy')
1470 $lcs +
= sizeof($edit->orig
);
1476 * Get the original set of lines.
1478 * This reconstructs the $from_lines parameter passed to the
1481 * @return array The original sequence of strings.
1486 foreach ($this->edits
as $edit) {
1488 array_splice($lines, sizeof($lines), 0, $edit->orig
);
1494 * Get the closing set of lines.
1496 * This reconstructs the $to_lines parameter passed to the
1499 * @return array The sequence of strings.
1501 function closing() {
1504 foreach ($this->edits
as $edit) {
1506 array_splice($lines, sizeof($lines), 0, $edit->closing
);
1512 * Check a Diff for validity.
1514 * This is here only for debugging purposes.
1516 function _check ($from_lines, $to_lines) {
1517 wfProfileIn( __METHOD__
);
1518 if (serialize($from_lines) != serialize($this->orig()))
1519 trigger_error("Reconstructed original doesn't match", E_USER_ERROR
);
1520 if (serialize($to_lines) != serialize($this->closing()))
1521 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR
);
1523 $rev = $this->reverse();
1524 if (serialize($to_lines) != serialize($rev->orig()))
1525 trigger_error("Reversed original doesn't match", E_USER_ERROR
);
1526 if (serialize($from_lines) != serialize($rev->closing()))
1527 trigger_error("Reversed closing doesn't match", E_USER_ERROR
);
1531 foreach ($this->edits
as $edit) {
1532 if ( $prevtype == $edit->type
)
1533 trigger_error("Edit sequence is non-optimal", E_USER_ERROR
);
1534 $prevtype = $edit->type
;
1537 $lcs = $this->lcs();
1538 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE
);
1539 wfProfileOut( __METHOD__
);
1544 * @todo document, bad name.
1546 * @ingroup DifferenceEngine
1548 class MappedDiff
extends Diff
1553 * Computes diff between sequences of strings.
1555 * This can be used to compute things like
1556 * case-insensitve diffs, or diffs which ignore
1557 * changes in white-space.
1559 * @param $from_lines array An array of strings.
1560 * (Typically these are lines from a file.)
1562 * @param $to_lines array An array of strings.
1564 * @param $mapped_from_lines array This array should
1565 * have the same size number of elements as $from_lines.
1566 * The elements in $mapped_from_lines and
1567 * $mapped_to_lines are what is actually compared
1568 * when computing the diff.
1570 * @param $mapped_to_lines array This array should
1571 * have the same number of elements as $to_lines.
1573 function MappedDiff($from_lines, $to_lines,
1574 $mapped_from_lines, $mapped_to_lines) {
1575 wfProfileIn( __METHOD__
);
1577 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1578 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1580 $this->Diff($mapped_from_lines, $mapped_to_lines);
1583 for ($i = 0; $i < sizeof($this->edits
); $i++
) {
1584 $orig = &$this->edits
[$i]->orig
;
1585 if (is_array($orig)) {
1586 $orig = array_slice($from_lines, $xi, sizeof($orig));
1587 $xi +
= sizeof($orig);
1590 $closing = &$this->edits
[$i]->closing
;
1591 if (is_array($closing)) {
1592 $closing = array_slice($to_lines, $yi, sizeof($closing));
1593 $yi +
= sizeof($closing);
1596 wfProfileOut( __METHOD__
);
1601 * A class to format Diffs
1603 * This class formats the diff in classic diff format.
1604 * It is intended that this class be customized via inheritance,
1605 * to obtain fancier outputs.
1608 * @ingroup DifferenceEngine
1610 class DiffFormatter
{
1612 * Number of leading context "lines" to preserve.
1614 * This should be left at zero for this class, but subclasses
1615 * may want to set this to other values.
1617 var $leading_context_lines = 0;
1620 * Number of trailing context "lines" to preserve.
1622 * This should be left at zero for this class, but subclasses
1623 * may want to set this to other values.
1625 var $trailing_context_lines = 0;
1630 * @param $diff object A Diff object.
1631 * @return string The formatted output.
1633 function format($diff) {
1634 wfProfileIn( __METHOD__
);
1640 $nlead = $this->leading_context_lines
;
1641 $ntrail = $this->trailing_context_lines
;
1643 $this->_start_diff();
1645 foreach ($diff->edits
as $edit) {
1646 if ($edit->type
== 'copy') {
1647 if (is_array($block)) {
1648 if (sizeof($edit->orig
) <= $nlead +
$ntrail) {
1653 $context = array_slice($edit->orig
, 0, $ntrail);
1654 $block[] = new _DiffOp_Copy($context);
1656 $this->_block($x0, $ntrail +
$xi - $x0,
1657 $y0, $ntrail +
$yi - $y0,
1662 $context = $edit->orig
;
1665 if (! is_array($block)) {
1666 $context = array_slice($context, sizeof($context) - $nlead);
1667 $x0 = $xi - sizeof($context);
1668 $y0 = $yi - sizeof($context);
1671 $block[] = new _DiffOp_Copy($context);
1677 $xi +
= sizeof($edit->orig
);
1679 $yi +
= sizeof($edit->closing
);
1682 if (is_array($block))
1683 $this->_block($x0, $xi - $x0,
1687 $end = $this->_end_diff();
1688 wfProfileOut( __METHOD__
);
1692 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1693 wfProfileIn( __METHOD__
);
1694 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1695 foreach ($edits as $edit) {
1696 if ($edit->type
== 'copy')
1697 $this->_context($edit->orig
);
1698 elseif ($edit->type
== 'add')
1699 $this->_added($edit->closing
);
1700 elseif ($edit->type
== 'delete')
1701 $this->_deleted($edit->orig
);
1702 elseif ($edit->type
== 'change')
1703 $this->_changed($edit->orig
, $edit->closing
);
1705 trigger_error('Unknown edit type', E_USER_ERROR
);
1707 $this->_end_block();
1708 wfProfileOut( __METHOD__
);
1711 function _start_diff() {
1715 function _end_diff() {
1716 $val = ob_get_contents();
1721 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1723 $xbeg .= "," . ($xbeg +
$xlen - 1);
1725 $ybeg .= "," . ($ybeg +
$ylen - 1);
1727 return $xbeg . ($xlen ?
($ylen ?
'c' : 'd') : 'a') . $ybeg;
1730 function _start_block($header) {
1731 echo $header . "\n";
1734 function _end_block() {
1737 function _lines($lines, $prefix = ' ') {
1738 foreach ($lines as $line)
1739 echo "$prefix $line\n";
1742 function _context($lines) {
1743 $this->_lines($lines);
1746 function _added($lines) {
1747 $this->_lines($lines, '>');
1749 function _deleted($lines) {
1750 $this->_lines($lines, '<');
1753 function _changed($orig, $closing) {
1754 $this->_deleted($orig);
1756 $this->_added($closing);
1761 * A formatter that outputs unified diffs
1762 * @ingroup DifferenceEngine
1765 class UnifiedDiffFormatter
extends DiffFormatter
{
1766 var $leading_context_lines = 2;
1767 var $trailing_context_lines = 2;
1769 function _added($lines) {
1770 $this->_lines($lines, '+');
1772 function _deleted($lines) {
1773 $this->_lines($lines, '-');
1775 function _changed($orig, $closing) {
1776 $this->_deleted($orig);
1777 $this->_added($closing);
1779 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1780 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1785 * A pseudo-formatter that just passes along the Diff::$edits array
1786 * @ingroup DifferenceEngine
1788 class ArrayDiffFormatter
extends DiffFormatter
{
1789 function format($diff) {
1793 foreach($diff->edits
as $edit)
1794 switch($edit->type
) {
1796 foreach($edit->closing
as $l) {
1800 'newline' => $newline++
1805 foreach($edit->orig
as $l) {
1807 'action' => 'delete',
1809 'oldline' => $oldline++
,
1814 foreach($edit->orig
as $i => $l) {
1816 'action' => 'change',
1818 'new' => @$edit->closing
[$i],
1819 'oldline' => $oldline++
,
1820 'newline' => $newline++
,
1825 $oldline +
= count($edit->orig
);
1826 $newline +
= count($edit->orig
);
1833 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1837 define('NBSP', ' '); // iso-8859-x non-breaking space.
1842 * @ingroup DifferenceEngine
1844 class _HWLDF_WordAccumulator
{
1845 function _HWLDF_WordAccumulator () {
1846 $this->_lines
= array();
1852 function _flushGroup ($new_tag) {
1853 if ($this->_group
!== '') {
1854 if ($this->_tag
== 'ins')
1855 $this->_line
.= '<ins class="diffchange diffchange-inline">' .
1856 htmlspecialchars ( $this->_group
) . '</ins>';
1857 elseif ($this->_tag
== 'del')
1858 $this->_line
.= '<del class="diffchange diffchange-inline">' .
1859 htmlspecialchars ( $this->_group
) . '</del>';
1861 $this->_line
.= htmlspecialchars ( $this->_group
);
1864 $this->_tag
= $new_tag;
1867 function _flushLine ($new_tag) {
1868 $this->_flushGroup($new_tag);
1869 if ($this->_line
!= '')
1870 array_push ( $this->_lines
, $this->_line
);
1872 # make empty lines visible by inserting an NBSP
1873 array_push ( $this->_lines
, NBSP
);
1877 function addWords ($words, $tag = '') {
1878 if ($tag != $this->_tag
)
1879 $this->_flushGroup($tag);
1881 foreach ($words as $word) {
1882 // new-line should only come as first char of word.
1885 if ($word[0] == "\n") {
1886 $this->_flushLine($tag);
1887 $word = substr($word, 1);
1889 assert(!strstr($word, "\n"));
1890 $this->_group
.= $word;
1894 function getLines() {
1895 $this->_flushLine('~done');
1896 return $this->_lines
;
1903 * @ingroup DifferenceEngine
1905 class WordLevelDiff
extends MappedDiff
{
1906 const MAX_LINE_LENGTH
= 10000;
1908 function WordLevelDiff ($orig_lines, $closing_lines) {
1909 wfProfileIn( __METHOD__
);
1911 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1912 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1914 $this->MappedDiff($orig_words, $closing_words,
1915 $orig_stripped, $closing_stripped);
1916 wfProfileOut( __METHOD__
);
1919 function _split($lines) {
1920 wfProfileIn( __METHOD__
);
1923 $stripped = array();
1925 foreach ( $lines as $line ) {
1926 # If the line is too long, just pretend the entire line is one big word
1927 # This prevents resource exhaustion problems
1934 if ( strlen( $line ) > self
::MAX_LINE_LENGTH
) {
1936 $stripped[] = $line;
1939 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1942 $words = array_merge( $words, $m[0] );
1943 $stripped = array_merge( $stripped, $m[1] );
1947 wfProfileOut( __METHOD__
);
1948 return array($words, $stripped);
1952 wfProfileIn( __METHOD__
);
1953 $orig = new _HWLDF_WordAccumulator
;
1955 foreach ($this->edits
as $edit) {
1956 if ($edit->type
== 'copy')
1957 $orig->addWords($edit->orig
);
1958 elseif ($edit->orig
)
1959 $orig->addWords($edit->orig
, 'del');
1961 $lines = $orig->getLines();
1962 wfProfileOut( __METHOD__
);
1966 function closing () {
1967 wfProfileIn( __METHOD__
);
1968 $closing = new _HWLDF_WordAccumulator
;
1970 foreach ($this->edits
as $edit) {
1971 if ($edit->type
== 'copy')
1972 $closing->addWords($edit->closing
);
1973 elseif ($edit->closing
)
1974 $closing->addWords($edit->closing
, 'ins');
1976 $lines = $closing->getLines();
1977 wfProfileOut( __METHOD__
);
1983 * Wikipedia Table style diff formatter.
1986 * @ingroup DifferenceEngine
1988 class TableDiffFormatter
extends DiffFormatter
{
1989 function TableDiffFormatter() {
1990 $this->leading_context_lines
= 2;
1991 $this->trailing_context_lines
= 2;
1994 public static function escapeWhiteSpace( $msg ) {
1995 $msg = preg_replace( '/^ /m', ' ', $msg );
1996 $msg = preg_replace( '/ $/m', ' ', $msg );
1997 $msg = preg_replace( '/ /', ' ', $msg );
2001 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2002 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2003 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2007 function _start_block( $header ) {
2011 function _end_block() {
2014 function _lines( $lines, $prefix=' ', $color='white' ) {
2017 # HTML-escape parameter before calling this
2018 function addedLine( $line ) {
2019 return $this->wrapLine( '+', 'diff-addedline', $line );
2022 # HTML-escape parameter before calling this
2023 function deletedLine( $line ) {
2024 return $this->wrapLine( '-', 'diff-deletedline', $line );
2027 # HTML-escape parameter before calling this
2028 function contextLine( $line ) {
2029 return $this->wrapLine( ' ', 'diff-context', $line );
2032 private function wrapLine( $marker, $class, $line ) {
2033 if( $line !== '' ) {
2034 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2035 $line = Xml
::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2037 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2040 function emptyLine() {
2041 return '<td colspan="2"> </td>';
2044 function _added( $lines ) {
2045 foreach ($lines as $line) {
2046 echo '<tr>' . $this->emptyLine() .
2047 $this->addedLine( '<ins class="diffchange">' .
2048 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2052 function _deleted($lines) {
2053 foreach ($lines as $line) {
2054 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2055 htmlspecialchars ( $line ) . '</del>' ) .
2056 $this->emptyLine() . "</tr>\n";
2060 function _context( $lines ) {
2061 foreach ($lines as $line) {
2063 $this->contextLine( htmlspecialchars ( $line ) ) .
2064 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2068 function _changed( $orig, $closing ) {
2069 wfProfileIn( __METHOD__
);
2071 $diff = new WordLevelDiff( $orig, $closing );
2072 $del = $diff->orig();
2073 $add = $diff->closing();
2075 # Notice that WordLevelDiff returns HTML-escaped output.
2076 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2078 while ( $line = array_shift( $del ) ) {
2079 $aline = array_shift( $add );
2080 echo '<tr>' . $this->deletedLine( $line ) .
2081 $this->addedLine( $aline ) . "</tr>\n";
2083 foreach ($add as $line) { # If any leftovers
2084 echo '<tr>' . $this->emptyLine() .
2085 $this->addedLine( $line ) . "</tr>\n";
2087 wfProfileOut( __METHOD__
);