attempt to fix ini_set error by using set_include_path Patch by robertoz
[mediawiki.git] / includes / DifferenceEngine.php
blob3de028fda26f278becba0e969e71271d27ea3c17
1 <?php
2 /**
3 * See diff.doc
4 * @package MediaWiki
5 * @subpackage DifferenceEngine
6 */
8 /** */
9 require_once( 'Revision.php' );
11 define( 'MAX_DIFF_LINE', 10000 );
12 define( 'MAX_DIFF_XREF_LENGTH', 10000 );
14 /**
15 * @todo document
16 * @access public
17 * @package MediaWiki
18 * @subpackage DifferenceEngine
20 class DifferenceEngine {
21 /**#@+
22 * @access private
24 var $mOldid, $mNewid, $mTitle;
25 var $mOldtitle, $mNewtitle, $mPagetitle;
26 var $mOldtext, $mNewtext;
27 var $mOldUser, $mNewUser;
28 var $mOldComment, $mNewComment;
29 var $mOldPage, $mNewPage;
30 var $mRcidMarkPatrolled;
31 var $mOldRev, $mNewRev;
32 var $mRevisionsLoaded = false; // Have the revisions been loaded
33 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
34 /**#@-*/
36 /**
37 * Constructor
38 * @param Title $titleObj Title object that the diff is associated with
39 * @param integer $old Old ID we want to show and diff with.
40 * @param string $new Either 'prev' or 'next'.
41 * @param integer $rcid ??? (default 0)
43 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
44 $this->mTitle = $titleObj;
46 if ( 'prev' == $new ) {
47 # Show diff between revision $old and the previous one.
48 # Get previous one from DB.
50 $this->mNewid = intval($old);
52 $this->mOldid = $this->mTitle->getPreviousRevisionID( $this->mNewid );
54 } elseif ( 'next' == $new ) {
55 # Show diff between revision $old and the previous one.
56 # Get previous one from DB.
58 $this->mOldid = intval($old);
59 $this->mNewid = $this->mTitle->getNextRevisionID( $this->mOldid );
60 if ( false === $this->mNewid ) {
61 # if no result, NewId points to the newest old revision. The only newer
62 # revision is cur, which is "0".
63 $this->mNewid = 0;
66 } else {
67 $this->mOldid = intval($old);
68 $this->mNewid = intval($new);
70 $this->mRcidMarkPatrolled = intval($rcid); # force it to be an integer
73 function showDiffPage() {
74 global $wgUser, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol,
75 $wgUseExternalEditor, $wgUseRCPatrol;
76 $fname = 'DifferenceEngine::showDiffPage';
77 wfProfileIn( $fname );
79 # If external diffs are enabled both globally and for the user,
80 # we'll use the application/x-external-editor interface to call
81 # an external diff tool like kompare, kdiff3, etc.
82 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
83 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
84 $wgOut->disable();
85 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
86 $url1=$this->mTitle->getFullURL("action=raw&oldid=".$this->mOldid);
87 $url2=$this->mTitle->getFullURL("action=raw&oldid=".$this->mNewid);
88 $special=$wgLang->getNsText(NS_SPECIAL);
89 $control=<<<CONTROL
90 [Process]
91 Type=Diff text
92 Engine=MediaWiki
93 Script={$wgServer}{$wgScript}
94 Special namespace={$special}
96 [File]
97 Extension=wiki
98 URL=$url1
100 [File 2]
101 Extension=wiki
102 URL=$url2
103 CONTROL;
104 echo($control);
105 return;
108 # mOldid is false if the difference engine is called with a "vague" query for
109 # a diff between a version V and its previous version V' AND the version V
110 # is the first version of that article. In that case, V' does not exist.
111 if ( $this->mOldid === false ) {
112 $this->showFirstRevision();
113 wfProfileOut( $fname );
114 return;
117 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
118 "{$this->mNewid})";
119 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
121 $wgOut->setArticleFlag( false );
122 if ( ! $this->loadRevisionData() ) {
123 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
124 $wgOut->addWikitext( $mtext );
125 wfProfileOut( $fname );
126 return;
128 if ( $this->mNewRev->isCurrent() ) {
129 $wgOut->setArticleFlag( true );
132 $wgOut->suppressQuickbar();
134 $oldTitle = $this->mOldPage->getPrefixedText();
135 $newTitle = $this->mNewPage->getPrefixedText();
136 if( $oldTitle == $newTitle ) {
137 $wgOut->setPageTitle( $newTitle );
138 } else {
139 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
141 $wgOut->setSubtitle( wfMsg( 'difference' ) );
142 $wgOut->setRobotpolicy( 'noindex,follow' );
144 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
145 $wgOut->loginToUse();
146 $wgOut->output();
147 wfProfileOut( $fname );
148 exit;
151 $sk = $wgUser->getSkin();
152 $talk = $wgContLang->getNsText( NS_TALK );
153 $contribs = wfMsg( 'contribslink' );
155 $this->mOldComment = $sk->formatComment($this->mOldComment);
156 $this->mNewComment = $sk->formatComment($this->mNewComment);
158 $oldUserLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER, $this->mOldUser ), $this->mOldUser );
159 $newUserLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER, $this->mNewUser ), $this->mNewUser );
160 $oldUTLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER_TALK, $this->mOldUser ), $talk );
161 $newUTLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER_TALK, $this->mNewUser ), $talk );
162 $oldContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, 'Contributions' ), $contribs,
163 'target=' . urlencode($this->mOldUser) );
164 $newContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, 'Contributions' ), $contribs,
165 'target=' . urlencode($this->mNewUser) );
166 if ( $this->mNewRev->isCurrent() && $wgUser->isAllowed('rollback') ) {
167 $rollback = '&nbsp;&nbsp;&nbsp;<strong>[' . $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'rollbacklink' ),
168 'action=rollback&from=' . urlencode($this->mNewUser) .
169 '&token=' . urlencode( $wgUser->editToken( array( $this->mTitle->getPrefixedText(), $this->mNewUser ) ) ) ) .
170 ']</strong>';
171 } else {
172 $rollback = '';
174 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled != 0 && $wgUser->isLoggedIn() &&
175 ( $wgUser->isAllowed('rollback') || !$wgOnlySysopsCanPatrol ) )
177 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'markaspatrolleddiff' ),
178 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
179 } else {
180 $patrol = '';
183 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousdiff' ),
184 'diff=prev&oldid='.$this->mOldid, '', '', 'id="differences-prevlink"' );
185 if ( $this->mNewRev->isCurrent() ) {
186 $nextlink = '';
187 } else {
188 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ),
189 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
192 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
193 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment .
194 '<br />' . $prevlink;
195 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
196 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment .
197 '<br />' . $nextlink . $patrol;
199 $this->showDiff( $oldHeader, $newHeader );
200 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
202 if( !$this->mNewRev->isCurrent() ) {
203 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
206 $this->loadNewText();
207 if( is_object( $this->mNewRev ) ) {
208 $wgOut->setRevisionId( $this->mNewRev->getId() );
210 $wgOut->addWikiText( $this->mNewtext );
212 if( !$this->mNewRev->isCurrent() ) {
213 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
216 wfProfileOut( $fname );
220 * Show the first revision of an article. Uses normal diff headers in
221 * contrast to normal "old revision" display style.
223 function showFirstRevision() {
224 global $wgOut, $wgUser, $wgLang;
226 $fname = 'DifferenceEngine::showFirstRevision';
227 wfProfileIn( $fname );
229 # Get article text from the DB
231 if ( ! $this->loadNewText() ) {
232 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
233 "{$this->mNewid})";
234 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
235 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
236 $wgOut->addWikitext( $mtext );
237 wfProfileOut( $fname );
238 return;
240 if ( $this->mNewRev->isCurrent() ) {
241 $wgOut->setArticleFlag( true );
244 # Check if user is allowed to look at this page. If not, bail out.
246 if ( !( $this->mTitle->userCanRead() ) ) {
247 $wgOut->loginToUse();
248 $wgOut->output();
249 wfProfileOut( $fname );
250 exit;
253 # Prepare the header box
255 $sk = $wgUser->getSkin();
257 $uTLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER_TALK, $this->mOldUser ), $wgLang->getNsText( NS_TALK ) );
258 $userLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER, $this->mOldUser ), $this->mOldUser );
259 $contribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, 'Contributions' ), wfMsg( 'contribslink' ),
260 'target=' . urlencode($this->mOldUser) );
261 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
262 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
263 "($uTLink | $contribs)<br />" . $this->mOldComment .
264 '<br />' . $nextlink. "</div>\n";
266 $wgOut->addHTML( $header );
268 $wgOut->setSubtitle( wfMsg( 'difference' ) );
269 $wgOut->setRobotpolicy( 'noindex,follow' );
272 # Show current revision
274 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
275 if( is_object( $this->mNewRev ) ) {
276 $wgOut->setRevisionId( $this->mNewRev->getId() );
278 $wgOut->addWikiText( $this->mNewtext );
280 wfProfileOut( $fname );
284 * Get the diff text, send it to $wgOut
285 * Returns false if the diff could not be generated, otherwise returns true
287 function showDiff( $otitle, $ntitle ) {
288 global $wgOut;
289 $diff = $this->getDiff( $otitle, $ntitle );
290 if ( $diff === false ) {
291 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" ) );
292 return false;
293 } else {
294 $wgOut->addHTML( $diff );
295 return true;
300 * Get diff table, including header
301 * Note that the interface has changed, it's no longer static.
302 * Returns false on error
304 function getDiff( $otitle, $ntitle ) {
305 $body = $this->getDiffBody();
306 if ( $body === false ) {
307 return false;
308 } else {
309 return $this->addHeader( $body, $otitle, $ntitle );
314 * Get the diff table body, without header
315 * Returns false on error
317 function getDiffBody() {
318 global $wgUseExternalDiffEngine, $wgContLang, $wgMemc, $wgDBname;
320 // Cacheable?
321 $key = false;
322 if ( $this->mOldid && $this->mNewid ) {
323 // Try cache
324 $key = "$wgDBname:diff:oldid:{$this->mOldid}:newid:{$this->mNewid}";
325 $difftext = $wgMemc->get( $key );
326 if ( $difftext ) {
327 return $difftext;
331 if ( !$this->loadText() ) {
332 return false;
335 $otext = $wgContLang->segmentForDiff($this->mOldtext);
336 $ntext = $wgContLang->segmentForDiff($this->mNewtext);
337 if ( $wgUseExternalDiffEngine ) {
338 # For historical reasons, external diff engine expects
339 # input text to be HTML-escaped already
340 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
341 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
342 if( !function_exists( 'wikidiff_do_diff' ) ) {
343 dl('php_wikidiff.so');
345 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
346 } else {
347 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
348 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
349 $diffs =& new Diff( $ota, $nta );
350 $formatter =& new TableDiffFormatter();
351 $difftext = $formatter->format( $diffs );
353 $difftext = $wgContLang->unsegmentForDiff($difftext);
355 // Save to cache for 7 days
356 if ( $key !== false ) {
357 $wgMemc->set( $key, $difftext, 7*86400 );
359 return $difftext;
363 * Add the header to a diff body
365 function addHeader( $diff, $otitle, $ntitle ) {
366 $out = "
367 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
368 <tr>
369 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
370 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
371 </tr>
372 $diff
373 </table>
375 return $out;
378 /**
379 * Use specified text instead of loading from the database
381 function setText( $oldText, $newText ) {
382 $this->mOldtext = $oldText;
383 $this->mNewtext = $newText;
384 $this->mTextLoaded = 2;
388 * Load revision metadata for the specified articles. If newid is 0, then compare
389 * the old article in oldid to the current article; if oldid is 0, then
390 * compare the current article to the immediately previous one (ignoring the
391 * value of newid).
393 * If oldid is false, leave the corresponding revision object set
394 * to false. This is impossible via ordinary user input, and is provided for
395 * API convenience.
397 function loadRevisionData() {
398 global $wgLang;
399 if ( $this->mRevisionsLoaded ) {
400 return true;
401 } else {
402 // Whether it succeeds or fails, we don't want to try again
403 $this->mRevisionsLoaded = true;
406 // Load the new revision object
407 if( $this->mNewid ) {
408 $this->mNewRev = Revision::newFromId( $this->mNewid );
409 } else {
410 $this->mNewRev = Revision::newFromTitle( $this->mTitle );
413 if( is_null( $this->mNewRev ) ) {
414 return false;
417 // Set assorted variables
418 if( $this->mNewRev->isCurrent() ) {
419 $this->mPagetitle = htmlspecialchars( wfMsg( 'currentrev' ) );
420 $this->mNewPage = $this->mTitle;
421 $newLink = $this->mNewPage->escapeLocalUrl();
422 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
423 } else {
424 $this->mNewPage = $this->mNewRev->getTitle();
425 $newLink = $this->mNewPage->escapeLocalUrl ('oldid=' . $this->mNewid );
426 $t = $wgLang->timeanddate( $this->mNewRev->getTimestamp(), true );
427 $this->mPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $t ) );
428 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
431 $this->mNewUser = $this->mNewRev->getUserText();
432 $this->mNewComment = $this->mNewRev->getComment();
434 // Load the old revision object
435 $this->mOldRev = false;
436 if( $this->mOldid ) {
437 $this->mOldRev = Revision::newFromId( $this->mOldid );
438 } elseif ( $this->mOldid === 0 ) {
439 $this->mOldRev = $this->mNewRev->getPrevious();
440 $this->mOldid = $this->mOldRev->getId();
441 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
443 if( is_null( $this->mOldRev ) ) {
444 return false;
447 if ( $this->mOldRev ) {
448 $this->mOldPage = $this->mOldRev->getTitle();
450 $t = $wgLang->timeanddate( $this->mOldRev->getTimestamp(), true );
451 $oldLink = $this->mOldPage->escapeLocalUrl( 'oldid=' . $this->mOldid );
452 $this->mOldtitle = "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
455 $this->mOldUser = $this->mOldRev->getUserText();
456 $this->mOldComment = $this->mOldRev->getComment();
459 return true;
463 * Load the text of the revisions, as well as revision data.
465 function loadText() {
466 if ( $this->mTextLoaded == 2 ) {
467 return true;
468 } else {
469 // Whether it succeeds or fails, we don't want to try again
470 $this->mTextLoaded = 2;
473 if ( !$this->loadRevisionData() ) {
474 return false;
476 if ( $this->mOldRev ) {
477 $this->mOldtext = $this->mOldRev->getText();
479 if ( $this->mNewRev ) {
480 $this->mNewtext = $this->mNewRev->getText();
482 return true;
486 * Load the text of the new revision, not the old one
488 function loadNewText() {
489 if ( $this->mTextLoaded >= 1 ) {
490 return true;
491 } else {
492 $this->mTextLoaded = 1;
494 if ( !$this->loadRevisionData() ) {
495 return false;
497 $this->mNewtext = $this->mNewRev->getText();
498 return true;
504 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
506 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
507 // You may copy this code freely under the conditions of the GPL.
510 define('USE_ASSERTS', function_exists('assert'));
513 * @todo document
514 * @access private
515 * @package MediaWiki
516 * @subpackage DifferenceEngine
518 class _DiffOp {
519 var $type;
520 var $orig;
521 var $closing;
523 function reverse() {
524 trigger_error('pure virtual', E_USER_ERROR);
527 function norig() {
528 return $this->orig ? sizeof($this->orig) : 0;
531 function nclosing() {
532 return $this->closing ? sizeof($this->closing) : 0;
537 * @todo document
538 * @access private
539 * @package MediaWiki
540 * @subpackage DifferenceEngine
542 class _DiffOp_Copy extends _DiffOp {
543 var $type = 'copy';
545 function _DiffOp_Copy ($orig, $closing = false) {
546 if (!is_array($closing))
547 $closing = $orig;
548 $this->orig = $orig;
549 $this->closing = $closing;
552 function reverse() {
553 return new _DiffOp_Copy($this->closing, $this->orig);
558 * @todo document
559 * @access private
560 * @package MediaWiki
561 * @subpackage DifferenceEngine
563 class _DiffOp_Delete extends _DiffOp {
564 var $type = 'delete';
566 function _DiffOp_Delete ($lines) {
567 $this->orig = $lines;
568 $this->closing = false;
571 function reverse() {
572 return new _DiffOp_Add($this->orig);
577 * @todo document
578 * @access private
579 * @package MediaWiki
580 * @subpackage DifferenceEngine
582 class _DiffOp_Add extends _DiffOp {
583 var $type = 'add';
585 function _DiffOp_Add ($lines) {
586 $this->closing = $lines;
587 $this->orig = false;
590 function reverse() {
591 return new _DiffOp_Delete($this->closing);
596 * @todo document
597 * @access private
598 * @package MediaWiki
599 * @subpackage DifferenceEngine
601 class _DiffOp_Change extends _DiffOp {
602 var $type = 'change';
604 function _DiffOp_Change ($orig, $closing) {
605 $this->orig = $orig;
606 $this->closing = $closing;
609 function reverse() {
610 return new _DiffOp_Change($this->closing, $this->orig);
616 * Class used internally by Diff to actually compute the diffs.
618 * The algorithm used here is mostly lifted from the perl module
619 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
620 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
622 * More ideas are taken from:
623 * http://www.ics.uci.edu/~eppstein/161/960229.html
625 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
626 * diffutils-2.7, which can be found at:
627 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
629 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
630 * are my own.
632 * Line length limits for robustness added by Tim Starling, 2005-08-31
634 * @author Geoffrey T. Dairiki, Tim Starling
635 * @access private
636 * @package MediaWiki
637 * @subpackage DifferenceEngine
639 class _DiffEngine
641 function diff ($from_lines, $to_lines) {
642 $fname = '_DiffEngine::diff';
643 wfProfileIn( $fname );
645 $n_from = sizeof($from_lines);
646 $n_to = sizeof($to_lines);
648 $this->xchanged = $this->ychanged = array();
649 $this->xv = $this->yv = array();
650 $this->xind = $this->yind = array();
651 unset($this->seq);
652 unset($this->in_seq);
653 unset($this->lcs);
655 // Skip leading common lines.
656 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
657 if ($from_lines[$skip] !== $to_lines[$skip])
658 break;
659 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
661 // Skip trailing common lines.
662 $xi = $n_from; $yi = $n_to;
663 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
664 if ($from_lines[$xi] !== $to_lines[$yi])
665 break;
666 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
669 // Ignore lines which do not exist in both files.
670 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
671 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
674 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
675 $line = $to_lines[$yi];
676 if ( ($this->ychanged[$yi] = empty($xhash[$this->_line_hash($line)])) )
677 continue;
678 $yhash[$this->_line_hash($line)] = 1;
679 $this->yv[] = $line;
680 $this->yind[] = $yi;
682 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
683 $line = $from_lines[$xi];
684 if ( ($this->xchanged[$xi] = empty($yhash[$this->_line_hash($line)])) )
685 continue;
686 $this->xv[] = $line;
687 $this->xind[] = $xi;
690 // Find the LCS.
691 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
693 // Merge edits when possible
694 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
695 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
697 // Compute the edit operations.
698 $edits = array();
699 $xi = $yi = 0;
700 while ($xi < $n_from || $yi < $n_to) {
701 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
702 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
704 // Skip matching "snake".
705 $copy = array();
706 while ( $xi < $n_from && $yi < $n_to
707 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
708 $copy[] = $from_lines[$xi++];
709 ++$yi;
711 if ($copy)
712 $edits[] = new _DiffOp_Copy($copy);
714 // Find deletes & adds.
715 $delete = array();
716 while ($xi < $n_from && $this->xchanged[$xi])
717 $delete[] = $from_lines[$xi++];
719 $add = array();
720 while ($yi < $n_to && $this->ychanged[$yi])
721 $add[] = $to_lines[$yi++];
723 if ($delete && $add)
724 $edits[] = new _DiffOp_Change($delete, $add);
725 elseif ($delete)
726 $edits[] = new _DiffOp_Delete($delete);
727 elseif ($add)
728 $edits[] = new _DiffOp_Add($add);
730 wfProfileOut( $fname );
731 return $edits;
735 * Returns the whole line if it's small enough, or the MD5 hash otherwise
737 function _line_hash( $line ) {
738 if ( strlen( $line ) > MAX_DIFF_XREF_LENGTH ) {
739 return md5( $line );
740 } else {
741 return $line;
746 /* Divide the Largest Common Subsequence (LCS) of the sequences
747 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
748 * sized segments.
750 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
751 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
752 * sub sequences. The first sub-sequence is contained in [X0, X1),
753 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
754 * that (X0, Y0) == (XOFF, YOFF) and
755 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
757 * This function assumes that the first lines of the specified portions
758 * of the two files do not match, and likewise that the last lines do not
759 * match. The caller must trim matching lines from the beginning and end
760 * of the portions it is going to specify.
762 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
763 $fname = '_DiffEngine::_diag';
764 wfProfileIn( $fname );
765 $flip = false;
767 if ($xlim - $xoff > $ylim - $yoff) {
768 // Things seems faster (I'm not sure I understand why)
769 // when the shortest sequence in X.
770 $flip = true;
771 list ($xoff, $xlim, $yoff, $ylim)
772 = array( $yoff, $ylim, $xoff, $xlim);
775 if ($flip)
776 for ($i = $ylim - 1; $i >= $yoff; $i--)
777 $ymatches[$this->xv[$i]][] = $i;
778 else
779 for ($i = $ylim - 1; $i >= $yoff; $i--)
780 $ymatches[$this->yv[$i]][] = $i;
782 $this->lcs = 0;
783 $this->seq[0]= $yoff - 1;
784 $this->in_seq = array();
785 $ymids[0] = array();
787 $numer = $xlim - $xoff + $nchunks - 1;
788 $x = $xoff;
789 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
790 wfProfileIn( "$fname-chunk" );
791 if ($chunk > 0)
792 for ($i = 0; $i <= $this->lcs; $i++)
793 $ymids[$i][$chunk-1] = $this->seq[$i];
795 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
796 for ( ; $x < $x1; $x++) {
797 $line = $flip ? $this->yv[$x] : $this->xv[$x];
798 if (empty($ymatches[$line]))
799 continue;
800 $matches = $ymatches[$line];
801 reset($matches);
802 while (list ($junk, $y) = each($matches))
803 if (empty($this->in_seq[$y])) {
804 $k = $this->_lcs_pos($y);
805 USE_ASSERTS && assert($k > 0);
806 $ymids[$k] = $ymids[$k-1];
807 break;
809 while (list ($junk, $y) = each($matches)) {
810 if ($y > $this->seq[$k-1]) {
811 USE_ASSERTS && assert($y < $this->seq[$k]);
812 // Optimization: this is a common case:
813 // next match is just replacing previous match.
814 $this->in_seq[$this->seq[$k]] = false;
815 $this->seq[$k] = $y;
816 $this->in_seq[$y] = 1;
817 } else if (empty($this->in_seq[$y])) {
818 $k = $this->_lcs_pos($y);
819 USE_ASSERTS && assert($k > 0);
820 $ymids[$k] = $ymids[$k-1];
824 wfProfileOut( "$fname-chunk" );
827 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
828 $ymid = $ymids[$this->lcs];
829 for ($n = 0; $n < $nchunks - 1; $n++) {
830 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
831 $y1 = $ymid[$n] + 1;
832 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
834 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
836 wfProfileOut( $fname );
837 return array($this->lcs, $seps);
840 function _lcs_pos ($ypos) {
841 $fname = '_DiffEngine::_lcs_pos';
842 wfProfileIn( $fname );
844 $end = $this->lcs;
845 if ($end == 0 || $ypos > $this->seq[$end]) {
846 $this->seq[++$this->lcs] = $ypos;
847 $this->in_seq[$ypos] = 1;
848 wfProfileOut( $fname );
849 return $this->lcs;
852 $beg = 1;
853 while ($beg < $end) {
854 $mid = (int)(($beg + $end) / 2);
855 if ( $ypos > $this->seq[$mid] )
856 $beg = $mid + 1;
857 else
858 $end = $mid;
861 USE_ASSERTS && assert($ypos != $this->seq[$end]);
863 $this->in_seq[$this->seq[$end]] = false;
864 $this->seq[$end] = $ypos;
865 $this->in_seq[$ypos] = 1;
866 wfProfileOut( $fname );
867 return $end;
870 /* Find LCS of two sequences.
872 * The results are recorded in the vectors $this->{x,y}changed[], by
873 * storing a 1 in the element for each line that is an insertion
874 * or deletion (ie. is not in the LCS).
876 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
878 * Note that XLIM, YLIM are exclusive bounds.
879 * All line numbers are origin-0 and discarded lines are not counted.
881 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
882 $fname = '_DiffEngine::_compareseq';
883 wfProfileIn( $fname );
885 // Slide down the bottom initial diagonal.
886 while ($xoff < $xlim && $yoff < $ylim
887 && $this->xv[$xoff] == $this->yv[$yoff]) {
888 ++$xoff;
889 ++$yoff;
892 // Slide up the top initial diagonal.
893 while ($xlim > $xoff && $ylim > $yoff
894 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
895 --$xlim;
896 --$ylim;
899 if ($xoff == $xlim || $yoff == $ylim)
900 $lcs = 0;
901 else {
902 // This is ad hoc but seems to work well.
903 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
904 //$nchunks = max(2,min(8,(int)$nchunks));
905 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
906 list ($lcs, $seps)
907 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
910 if ($lcs == 0) {
911 // X and Y sequences have no common subsequence:
912 // mark all changed.
913 while ($yoff < $ylim)
914 $this->ychanged[$this->yind[$yoff++]] = 1;
915 while ($xoff < $xlim)
916 $this->xchanged[$this->xind[$xoff++]] = 1;
917 } else {
918 // Use the partitions to split this problem into subproblems.
919 reset($seps);
920 $pt1 = $seps[0];
921 while ($pt2 = next($seps)) {
922 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
923 $pt1 = $pt2;
926 wfProfileOut( $fname );
929 /* Adjust inserts/deletes of identical lines to join changes
930 * as much as possible.
932 * We do something when a run of changed lines include a
933 * line at one end and has an excluded, identical line at the other.
934 * We are free to choose which identical line is included.
935 * `compareseq' usually chooses the one at the beginning,
936 * but usually it is cleaner to consider the following identical line
937 * to be the "change".
939 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
941 function _shift_boundaries ($lines, &$changed, $other_changed) {
942 $fname = '_DiffEngine::_shift_boundaries';
943 wfProfileIn( $fname );
944 $i = 0;
945 $j = 0;
947 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
948 $len = sizeof($lines);
949 $other_len = sizeof($other_changed);
951 while (1) {
953 * Scan forwards to find beginning of another run of changes.
954 * Also keep track of the corresponding point in the other file.
956 * Throughout this code, $i and $j are adjusted together so that
957 * the first $i elements of $changed and the first $j elements
958 * of $other_changed both contain the same number of zeros
959 * (unchanged lines).
960 * Furthermore, $j is always kept so that $j == $other_len or
961 * $other_changed[$j] == false.
963 while ($j < $other_len && $other_changed[$j])
964 $j++;
966 while ($i < $len && ! $changed[$i]) {
967 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
968 $i++; $j++;
969 while ($j < $other_len && $other_changed[$j])
970 $j++;
973 if ($i == $len)
974 break;
976 $start = $i;
978 // Find the end of this run of changes.
979 while (++$i < $len && $changed[$i])
980 continue;
982 do {
984 * Record the length of this run of changes, so that
985 * we can later determine whether the run has grown.
987 $runlength = $i - $start;
990 * Move the changed region back, so long as the
991 * previous unchanged line matches the last changed one.
992 * This merges with previous changed regions.
994 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
995 $changed[--$start] = 1;
996 $changed[--$i] = false;
997 while ($start > 0 && $changed[$start - 1])
998 $start--;
999 USE_ASSERTS && assert('$j > 0');
1000 while ($other_changed[--$j])
1001 continue;
1002 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1006 * Set CORRESPONDING to the end of the changed run, at the last
1007 * point where it corresponds to a changed run in the other file.
1008 * CORRESPONDING == LEN means no such point has been found.
1010 $corresponding = $j < $other_len ? $i : $len;
1013 * Move the changed region forward, so long as the
1014 * first changed line matches the following unchanged one.
1015 * This merges with following changed regions.
1016 * Do this second, so that if there are no merges,
1017 * the changed region is moved forward as far as possible.
1019 while ($i < $len && $lines[$start] == $lines[$i]) {
1020 $changed[$start++] = false;
1021 $changed[$i++] = 1;
1022 while ($i < $len && $changed[$i])
1023 $i++;
1025 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1026 $j++;
1027 if ($j < $other_len && $other_changed[$j]) {
1028 $corresponding = $i;
1029 while ($j < $other_len && $other_changed[$j])
1030 $j++;
1033 } while ($runlength != $i - $start);
1036 * If possible, move the fully-merged run of changes
1037 * back to a corresponding run in the other file.
1039 while ($corresponding < $i) {
1040 $changed[--$start] = 1;
1041 $changed[--$i] = 0;
1042 USE_ASSERTS && assert('$j > 0');
1043 while ($other_changed[--$j])
1044 continue;
1045 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1048 wfProfileOut( $fname );
1053 * Class representing a 'diff' between two sequences of strings.
1054 * @todo document
1055 * @access private
1056 * @package MediaWiki
1057 * @subpackage DifferenceEngine
1059 class Diff
1061 var $edits;
1064 * Constructor.
1065 * Computes diff between sequences of strings.
1067 * @param $from_lines array An array of strings.
1068 * (Typically these are lines from a file.)
1069 * @param $to_lines array An array of strings.
1071 function Diff($from_lines, $to_lines) {
1072 $eng = new _DiffEngine;
1073 $this->edits = $eng->diff($from_lines, $to_lines);
1074 //$this->_check($from_lines, $to_lines);
1078 * Compute reversed Diff.
1080 * SYNOPSIS:
1082 * $diff = new Diff($lines1, $lines2);
1083 * $rev = $diff->reverse();
1084 * @return object A Diff object representing the inverse of the
1085 * original diff.
1087 function reverse () {
1088 $rev = $this;
1089 $rev->edits = array();
1090 foreach ($this->edits as $edit) {
1091 $rev->edits[] = $edit->reverse();
1093 return $rev;
1097 * Check for empty diff.
1099 * @return bool True iff two sequences were identical.
1101 function isEmpty () {
1102 foreach ($this->edits as $edit) {
1103 if ($edit->type != 'copy')
1104 return false;
1106 return true;
1110 * Compute the length of the Longest Common Subsequence (LCS).
1112 * This is mostly for diagnostic purposed.
1114 * @return int The length of the LCS.
1116 function lcs () {
1117 $lcs = 0;
1118 foreach ($this->edits as $edit) {
1119 if ($edit->type == 'copy')
1120 $lcs += sizeof($edit->orig);
1122 return $lcs;
1126 * Get the original set of lines.
1128 * This reconstructs the $from_lines parameter passed to the
1129 * constructor.
1131 * @return array The original sequence of strings.
1133 function orig() {
1134 $lines = array();
1136 foreach ($this->edits as $edit) {
1137 if ($edit->orig)
1138 array_splice($lines, sizeof($lines), 0, $edit->orig);
1140 return $lines;
1144 * Get the closing set of lines.
1146 * This reconstructs the $to_lines parameter passed to the
1147 * constructor.
1149 * @return array The sequence of strings.
1151 function closing() {
1152 $lines = array();
1154 foreach ($this->edits as $edit) {
1155 if ($edit->closing)
1156 array_splice($lines, sizeof($lines), 0, $edit->closing);
1158 return $lines;
1162 * Check a Diff for validity.
1164 * This is here only for debugging purposes.
1166 function _check ($from_lines, $to_lines) {
1167 $fname = 'Diff::_check';
1168 wfProfileIn( $fname );
1169 if (serialize($from_lines) != serialize($this->orig()))
1170 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
1171 if (serialize($to_lines) != serialize($this->closing()))
1172 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
1174 $rev = $this->reverse();
1175 if (serialize($to_lines) != serialize($rev->orig()))
1176 trigger_error("Reversed original doesn't match", E_USER_ERROR);
1177 if (serialize($from_lines) != serialize($rev->closing()))
1178 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
1181 $prevtype = 'none';
1182 foreach ($this->edits as $edit) {
1183 if ( $prevtype == $edit->type )
1184 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
1185 $prevtype = $edit->type;
1188 $lcs = $this->lcs();
1189 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
1190 wfProfileOut( $fname );
1195 * FIXME: bad name.
1196 * @todo document
1197 * @access private
1198 * @package MediaWiki
1199 * @subpackage DifferenceEngine
1201 class MappedDiff extends Diff
1204 * Constructor.
1206 * Computes diff between sequences of strings.
1208 * This can be used to compute things like
1209 * case-insensitve diffs, or diffs which ignore
1210 * changes in white-space.
1212 * @param $from_lines array An array of strings.
1213 * (Typically these are lines from a file.)
1215 * @param $to_lines array An array of strings.
1217 * @param $mapped_from_lines array This array should
1218 * have the same size number of elements as $from_lines.
1219 * The elements in $mapped_from_lines and
1220 * $mapped_to_lines are what is actually compared
1221 * when computing the diff.
1223 * @param $mapped_to_lines array This array should
1224 * have the same number of elements as $to_lines.
1226 function MappedDiff($from_lines, $to_lines,
1227 $mapped_from_lines, $mapped_to_lines) {
1228 $fname = 'MappedDiff::MappedDiff';
1229 wfProfileIn( $fname );
1231 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1232 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1234 $this->Diff($mapped_from_lines, $mapped_to_lines);
1236 $xi = $yi = 0;
1237 for ($i = 0; $i < sizeof($this->edits); $i++) {
1238 $orig = &$this->edits[$i]->orig;
1239 if (is_array($orig)) {
1240 $orig = array_slice($from_lines, $xi, sizeof($orig));
1241 $xi += sizeof($orig);
1244 $closing = &$this->edits[$i]->closing;
1245 if (is_array($closing)) {
1246 $closing = array_slice($to_lines, $yi, sizeof($closing));
1247 $yi += sizeof($closing);
1250 wfProfileOut( $fname );
1255 * A class to format Diffs
1257 * This class formats the diff in classic diff format.
1258 * It is intended that this class be customized via inheritance,
1259 * to obtain fancier outputs.
1260 * @todo document
1261 * @access private
1262 * @package MediaWiki
1263 * @subpackage DifferenceEngine
1265 class DiffFormatter
1268 * Number of leading context "lines" to preserve.
1270 * This should be left at zero for this class, but subclasses
1271 * may want to set this to other values.
1273 var $leading_context_lines = 0;
1276 * Number of trailing context "lines" to preserve.
1278 * This should be left at zero for this class, but subclasses
1279 * may want to set this to other values.
1281 var $trailing_context_lines = 0;
1284 * Format a diff.
1286 * @param $diff object A Diff object.
1287 * @return string The formatted output.
1289 function format($diff) {
1290 $fname = 'DiffFormatter::format';
1291 wfProfileIn( $fname );
1293 $xi = $yi = 1;
1294 $block = false;
1295 $context = array();
1297 $nlead = $this->leading_context_lines;
1298 $ntrail = $this->trailing_context_lines;
1300 $this->_start_diff();
1302 foreach ($diff->edits as $edit) {
1303 if ($edit->type == 'copy') {
1304 if (is_array($block)) {
1305 if (sizeof($edit->orig) <= $nlead + $ntrail) {
1306 $block[] = $edit;
1308 else{
1309 if ($ntrail) {
1310 $context = array_slice($edit->orig, 0, $ntrail);
1311 $block[] = new _DiffOp_Copy($context);
1313 $this->_block($x0, $ntrail + $xi - $x0,
1314 $y0, $ntrail + $yi - $y0,
1315 $block);
1316 $block = false;
1319 $context = $edit->orig;
1321 else {
1322 if (! is_array($block)) {
1323 $context = array_slice($context, sizeof($context) - $nlead);
1324 $x0 = $xi - sizeof($context);
1325 $y0 = $yi - sizeof($context);
1326 $block = array();
1327 if ($context)
1328 $block[] = new _DiffOp_Copy($context);
1330 $block[] = $edit;
1333 if ($edit->orig)
1334 $xi += sizeof($edit->orig);
1335 if ($edit->closing)
1336 $yi += sizeof($edit->closing);
1339 if (is_array($block))
1340 $this->_block($x0, $xi - $x0,
1341 $y0, $yi - $y0,
1342 $block);
1344 $end = $this->_end_diff();
1345 wfProfileOut( $fname );
1346 return $end;
1349 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1350 $fname = 'DiffFormatter::_block';
1351 wfProfileIn( $fname );
1352 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1353 foreach ($edits as $edit) {
1354 if ($edit->type == 'copy')
1355 $this->_context($edit->orig);
1356 elseif ($edit->type == 'add')
1357 $this->_added($edit->closing);
1358 elseif ($edit->type == 'delete')
1359 $this->_deleted($edit->orig);
1360 elseif ($edit->type == 'change')
1361 $this->_changed($edit->orig, $edit->closing);
1362 else
1363 trigger_error('Unknown edit type', E_USER_ERROR);
1365 $this->_end_block();
1366 wfProfileOut( $fname );
1369 function _start_diff() {
1370 ob_start();
1373 function _end_diff() {
1374 $val = ob_get_contents();
1375 ob_end_clean();
1376 return $val;
1379 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1380 if ($xlen > 1)
1381 $xbeg .= "," . ($xbeg + $xlen - 1);
1382 if ($ylen > 1)
1383 $ybeg .= "," . ($ybeg + $ylen - 1);
1385 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
1388 function _start_block($header) {
1389 echo $header;
1392 function _end_block() {
1395 function _lines($lines, $prefix = ' ') {
1396 foreach ($lines as $line)
1397 echo "$prefix $line\n";
1400 function _context($lines) {
1401 $this->_lines($lines);
1404 function _added($lines) {
1405 $this->_lines($lines, '>');
1407 function _deleted($lines) {
1408 $this->_lines($lines, '<');
1411 function _changed($orig, $closing) {
1412 $this->_deleted($orig);
1413 echo "---\n";
1414 $this->_added($closing);
1420 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1424 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1427 * @todo document
1428 * @access private
1429 * @package MediaWiki
1430 * @subpackage DifferenceEngine
1432 class _HWLDF_WordAccumulator {
1433 function _HWLDF_WordAccumulator () {
1434 $this->_lines = array();
1435 $this->_line = '';
1436 $this->_group = '';
1437 $this->_tag = '';
1440 function _flushGroup ($new_tag) {
1441 if ($this->_group !== '') {
1442 if ($this->_tag == 'mark')
1443 $this->_line .= '<span class="diffchange">' .
1444 htmlspecialchars ( $this->_group ) . '</span>';
1445 else
1446 $this->_line .= htmlspecialchars ( $this->_group );
1448 $this->_group = '';
1449 $this->_tag = $new_tag;
1452 function _flushLine ($new_tag) {
1453 $this->_flushGroup($new_tag);
1454 if ($this->_line != '')
1455 array_push ( $this->_lines, $this->_line );
1456 else
1457 # make empty lines visible by inserting an NBSP
1458 array_push ( $this->_lines, NBSP );
1459 $this->_line = '';
1462 function addWords ($words, $tag = '') {
1463 if ($tag != $this->_tag)
1464 $this->_flushGroup($tag);
1466 foreach ($words as $word) {
1467 // new-line should only come as first char of word.
1468 if ($word == '')
1469 continue;
1470 if ($word[0] == "\n") {
1471 $this->_flushLine($tag);
1472 $word = substr($word, 1);
1474 assert(!strstr($word, "\n"));
1475 $this->_group .= $word;
1479 function getLines() {
1480 $this->_flushLine('~done');
1481 return $this->_lines;
1486 * @todo document
1487 * @access private
1488 * @package MediaWiki
1489 * @subpackage DifferenceEngine
1491 class WordLevelDiff extends MappedDiff
1493 function WordLevelDiff ($orig_lines, $closing_lines) {
1494 $fname = 'WordLevelDiff::WordLevelDiff';
1495 wfProfileIn( $fname );
1497 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1498 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1500 $this->MappedDiff($orig_words, $closing_words,
1501 $orig_stripped, $closing_stripped);
1502 wfProfileOut( $fname );
1505 function _split($lines) {
1506 $fname = 'WordLevelDiff::_split';
1507 wfProfileIn( $fname );
1509 $words = array();
1510 $stripped = array();
1511 $first = true;
1512 foreach ( $lines as $line ) {
1513 # If the line is too long, just pretend the entire line is one big word
1514 # This prevents resource exhaustion problems
1515 if ( $first ) {
1516 $first = false;
1517 } else {
1518 $words[] = "\n";
1519 $stripped[] = "\n";
1521 if ( strlen( $line ) > MAX_DIFF_LINE ) {
1522 $words[] = $line;
1523 $stripped[] = $line;
1524 } else {
1525 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1526 $line, $m))
1528 $words = array_merge( $words, $m[0] );
1529 $stripped = array_merge( $stripped, $m[1] );
1533 wfProfileOut( $fname );
1534 return array($words, $stripped);
1537 function orig () {
1538 $fname = 'WordLevelDiff::orig';
1539 wfProfileIn( $fname );
1540 $orig = new _HWLDF_WordAccumulator;
1542 foreach ($this->edits as $edit) {
1543 if ($edit->type == 'copy')
1544 $orig->addWords($edit->orig);
1545 elseif ($edit->orig)
1546 $orig->addWords($edit->orig, 'mark');
1548 $lines = $orig->getLines();
1549 wfProfileOut( $fname );
1550 return $lines;
1553 function closing () {
1554 $fname = 'WordLevelDiff::closing';
1555 wfProfileIn( $fname );
1556 $closing = new _HWLDF_WordAccumulator;
1558 foreach ($this->edits as $edit) {
1559 if ($edit->type == 'copy')
1560 $closing->addWords($edit->closing);
1561 elseif ($edit->closing)
1562 $closing->addWords($edit->closing, 'mark');
1564 $lines = $closing->getLines();
1565 wfProfileOut( $fname );
1566 return $lines;
1571 * Wikipedia Table style diff formatter.
1572 * @todo document
1573 * @access private
1574 * @package MediaWiki
1575 * @subpackage DifferenceEngine
1577 class TableDiffFormatter extends DiffFormatter
1579 function TableDiffFormatter() {
1580 $this->leading_context_lines = 2;
1581 $this->trailing_context_lines = 2;
1584 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1585 $l1 = wfMsg( 'lineno', $xbeg );
1586 $l2 = wfMsg( 'lineno', $ybeg );
1588 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1589 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1590 return $r;
1593 function _start_block( $header ) {
1594 global $wgOut;
1595 echo $header;
1598 function _end_block() {
1601 function _lines( $lines, $prefix=' ', $color='white' ) {
1604 # HTML-escape parameter before calling this
1605 function addedLine( $line ) {
1606 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1609 # HTML-escape parameter before calling this
1610 function deletedLine( $line ) {
1611 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1614 # HTML-escape parameter before calling this
1615 function contextLine( $line ) {
1616 return "<td> </td><td class='diff-context'>{$line}</td>";
1619 function emptyLine() {
1620 return '<td colspan="2">&nbsp;</td>';
1623 function _added( $lines ) {
1624 foreach ($lines as $line) {
1625 echo '<tr>' . $this->emptyLine() .
1626 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1630 function _deleted($lines) {
1631 foreach ($lines as $line) {
1632 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1633 $this->emptyLine() . "</tr>\n";
1637 function _context( $lines ) {
1638 foreach ($lines as $line) {
1639 echo '<tr>' .
1640 $this->contextLine( htmlspecialchars ( $line ) ) .
1641 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1645 function _changed( $orig, $closing ) {
1646 $fname = 'TableDiffFormatter::_changed';
1647 wfProfileIn( $fname );
1649 $diff = new WordLevelDiff( $orig, $closing );
1650 $del = $diff->orig();
1651 $add = $diff->closing();
1653 # Notice that WordLevelDiff returns HTML-escaped output.
1654 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1656 while ( $line = array_shift( $del ) ) {
1657 $aline = array_shift( $add );
1658 echo '<tr>' . $this->deletedLine( $line ) .
1659 $this->addedLine( $aline ) . "</tr>\n";
1661 foreach ($add as $line) { # If any leftovers
1662 echo '<tr>' . $this->emptyLine() .
1663 $this->addedLine( $line ) . "</tr>\n";
1665 wfProfileOut( $fname );