Moved image metadata to the database. Changed Image object to have lightweight constr...
[mediawiki.git] / includes / DifferenceEngine.php
blob66edfa9fd6e9f39935b1d4d29f67384dbb20644b
1 <?php
2 /**
3 * See diff.doc
4 * @package MediaWiki
5 * @subpackage DifferenceEngine
6 */
8 /** */
9 require_once( 'Revision.php' );
11 /**
12 * @todo document
13 * @access public
14 * @package MediaWiki
15 * @subpackage DifferenceEngine
17 class DifferenceEngine {
18 /**#@+
19 * @access private
21 var $mOldid, $mNewid;
22 var $mOldtitle, $mNewtitle, $mPagetitle;
23 var $mOldtext, $mNewtext;
24 var $mOldUser, $mNewUser;
25 var $mOldComment, $mNewComment;
26 var $mOldPage, $mNewPage;
27 var $mRcidMarkPatrolled;
28 /**#@-*/
30 /**
31 * Constructor
32 * @param integer $old Old ID we want to show and diff with.
33 * @param string $new Either 'prev' or 'next'.
34 * @param integer $rcid ??? (default 0)
36 function DifferenceEngine( $old, $new, $rcid = 0 ) {
37 global $wgTitle;
39 if ( 'prev' == $new ) {
40 # Show diff between revision $old and the previous one.
41 # Get previous one from DB.
43 $this->mNewid = intval($old);
45 $this->mOldid = $wgTitle->getPreviousRevisionID( $this->mNewid );
47 } elseif ( 'next' == $new ) {
48 # Show diff between revision $old and the previous one.
49 # Get previous one from DB.
51 $this->mOldid = intval($old);
52 $this->mNewid = $wgTitle->getNextRevisionID( $this->mOldid );
53 if ( false === $this->mNewid ) {
54 # if no result, NewId points to the newest old revision. The only newer
55 # revision is cur, which is "0".
56 $this->mNewid = 0;
59 } else {
60 $this->mOldid = intval($old);
61 $this->mNewid = intval($new);
63 $this->mRcidMarkPatrolled = intval($rcid); # force it to be an integer
66 function showDiffPage() {
67 global $wgUser, $wgTitle, $wgOut, $wgContLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
68 $fname = 'DifferenceEngine::showDiffPage';
69 wfProfileIn( $fname );
71 # mOldid is false if the difference engine is called with a "vague" query for
72 # a diff between a version V and its previous version V' AND the version V
73 # is the first version of that article. In that case, V' does not exist.
74 if ( $this->mOldid === false ) {
75 $this->showFirstRevision();
76 wfProfileOut( $fname );
77 return;
80 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
81 "{$this->mNewid})";
82 $mtext = wfMsg( 'missingarticle', $t );
84 $wgOut->setArticleFlag( false );
85 if ( ! $this->loadText() ) {
86 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
87 $wgOut->addHTML( $mtext );
88 wfProfileOut( $fname );
89 return;
91 $wgOut->suppressQuickbar();
93 $oldTitle = $this->mOldPage->getPrefixedText();
94 $newTitle = $this->mNewPage->getPrefixedText();
95 if( $oldTitle == $newTitle ) {
96 $wgOut->setPageTitle( $newTitle );
97 } else {
98 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
100 $wgOut->setSubtitle( wfMsg( 'difference' ) );
101 $wgOut->setRobotpolicy( 'noindex,follow' );
103 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
104 $wgOut->loginToUse();
105 $wgOut->output();
106 wfProfileOut( $fname );
107 exit;
110 $sk = $wgUser->getSkin();
111 $talk = $wgContLang->getNsText( NS_TALK );
112 $contribs = wfMsg( 'contribslink' );
114 $this->mOldComment = $sk->formatComment($this->mOldComment);
115 $this->mNewComment = $sk->formatComment($this->mNewComment);
117 $oldUserLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER, $this->mOldUser ), $this->mOldUser );
118 $newUserLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER, $this->mNewUser ), $this->mNewUser );
119 $oldUTLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER_TALK, $this->mOldUser ), $talk );
120 $newUTLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER_TALK, $this->mNewUser ), $talk );
121 $oldContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, 'Contributions' ), $contribs,
122 'target=' . urlencode($this->mOldUser) );
123 $newContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, 'Contributions' ), $contribs,
124 'target=' . urlencode($this->mNewUser) );
125 if ( !$this->mNewid && $wgUser->isAllowed('rollback') ) {
126 $rollback = '&nbsp;&nbsp;&nbsp;<strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
127 'action=rollback&from=' . urlencode($this->mNewUser) .
128 '&token=' . urlencode( $wgUser->editToken( array( $wgTitle->getPrefixedText(), $this->mNewUser ) ) ) ) .
129 ']</strong>';
130 } else {
131 $rollback = '';
133 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled != 0 && $wgUser->isLoggedIn() &&
134 ( $wgUser->isAllowed('rollback') || !$wgOnlySysopsCanPatrol ) )
136 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
137 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
138 } else {
139 $patrol = '';
142 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid );
143 if ( $this->mNewid == 0 ) {
144 $nextlink = '';
145 } else {
146 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid );
149 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
150 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment .
151 '<br />' . $prevlink;
152 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
153 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment .
154 '<br />' . $nextlink . $patrol;
156 DifferenceEngine::showDiff( $this->mOldtext, $this->mNewtext,
157 $oldHeader, $newHeader );
158 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
159 $wgOut->addWikiText( $this->mNewtext );
161 wfProfileOut( $fname );
165 * Show the first revision of an article. Uses normal diff headers in
166 * contrast to normal "old revision" display style.
168 function showFirstRevision() {
169 global $wgOut, $wgTitle, $wgUser, $wgLang;
171 $fname = 'DifferenceEngine::showFirstRevision';
172 wfProfileIn( $fname );
175 $this->mOldid = $this->mNewid; # hack to make loadText() work.
177 # Get article text from the DB
179 if ( ! $this->loadText() ) {
180 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
181 "{$this->mNewid})";
182 $mtext = wfMsg( 'missingarticle', $t );
183 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
184 $wgOut->addHTML( $mtext );
185 wfProfileOut( $fname );
186 return;
189 # Check if user is allowed to look at this page. If not, bail out.
191 if ( !( $this->mOldPage->userCanRead() ) ) {
192 $wgOut->loginToUse();
193 $wgOut->output();
194 wfProfileOut( $fname );
195 exit;
198 # Prepare the header box
200 $sk = $wgUser->getSkin();
202 $uTLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER_TALK, $this->mOldUser ), $wgLang->getNsText( NS_TALK ) );
203 $userLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER, $this->mOldUser ), $this->mOldUser );
204 $contribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, 'Contributions' ), wfMsg( 'contribslink' ),
205 'target=' . urlencode($this->mOldUser) );
206 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid );
207 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
208 "($uTLink | $contribs)<br />" . $this->mOldComment .
209 '<br />' . $nextlink. "</div>\n";
211 $wgOut->addHTML( $header );
213 $wgOut->setSubtitle( wfMsg( 'difference' ) );
214 $wgOut->setRobotpolicy( 'noindex,follow' );
217 # Show current revision
219 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
220 $wgOut->addWikiText( $this->mNewtext );
222 wfProfileOut( $fname );
225 function showDiff( $otext, $ntext, $otitle, $ntitle ) {
226 global $wgOut;
227 $wgOut->addHTML( DifferenceEngine::getDiff( $otext, $ntext, $otitle, $ntitle ) );
230 function getDiff( $otext, $ntext, $otitle, $ntitle ) {
231 global $wgUseExternalDiffEngine, $wgContLang;
232 $out = "
233 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
234 <tr>
235 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
236 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
237 </tr>
239 $otext = $wgContLang->segmentForDiff($otext);
240 $ntext = $wgContLang->segmentForDiff($ntext);
241 $difftext='';
242 if ( $wgUseExternalDiffEngine ) {
243 # For historical reasons, external diff engine expects
244 # input text to be HTML-escaped already
245 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
246 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
247 if( !function_exists( 'wikidiff_do_diff' ) ) {
248 dl('php_wikidiff.so');
250 $difftext = wikidiff_do_diff( $otext, $ntext, 2 );
251 } else {
252 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
253 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
254 $diffs =& new Diff( $ota, $nta );
255 $formatter =& new TableDiffFormatter();
256 $difftext = $formatter->format( $diffs );
258 $difftext = $wgContLang->unsegmentForDiff($difftext);
259 $out .= $difftext."</table>\n";
260 return $out;
264 * Load the text of the articles to compare. If newid is 0, then compare
265 * the old article in oldid to the current article; if oldid is 0, then
266 * compare the current article to the immediately previous one (ignoring the
267 * value of newid).
269 function loadText() {
270 global $wgTitle, $wgOut, $wgLang;
271 $fname = 'DifferenceEngine::loadText';
273 $dbr =& wfGetDB( DB_SLAVE );
274 if( $this->mNewid ) {
275 $this->newRev =& Revision::newFromId( $this->mNewid );
276 } else {
277 $this->newRev =& Revision::newFromTitle( $wgTitle );
279 if( is_null( $this->newRev ) ) {
280 return false;
283 if( $this->newRev->isCurrent() ) {
284 $this->mPagetitle = htmlspecialchars( wfMsg( 'currentrev' ) );
285 $this->mNewPage = $wgTitle;
286 $newLink = $this->mNewPage->escapeLocalUrl();
287 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
288 } else {
289 $this->mNewPage = $this->newRev->getTitle();
290 $newLink = $this->mNewPage->escapeLocalUrl ('oldid=' . $this->mNewid );
291 $t = $wgLang->timeanddate( $this->newRev->getTimestamp(), true );
292 $this->mPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $t ) );
293 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
296 if( $this->mOldid ) {
297 $this->oldRev =& Revision::newFromId( $this->mOldid );
298 } else {
299 $this->oldRev =& $this->newRev->getPrevious();
300 $this->mOldid = $this->oldRev->getId();
302 if( is_null( $this->oldRev ) ) {
303 return false;
306 $this->mOldPage = $this->oldRev->getTitle();
308 $t = $wgLang->timeanddate( $this->oldRev->getTimestamp(), true );
309 $oldLink = $this->mOldPage->escapeLocalUrl( 'oldid=' . $this->mOldid );
310 $this->mOldtitle = "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
312 $this->mNewUser = $this->newRev->getUserText();
313 $this->mNewComment = $this->newRev->getComment();
314 $this->mNewtext = $this->newRev->getText();
316 $this->mOldUser = $this->oldRev->getUserText();
317 $this->mOldComment = $this->oldRev->getComment();
318 $this->mOldtext = $this->oldRev->getText();
320 return true;
324 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
326 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
327 // You may copy this code freely under the conditions of the GPL.
330 define('USE_ASSERTS', function_exists('assert'));
333 * @todo document
334 * @access private
335 * @package MediaWiki
336 * @subpackage DifferenceEngine
338 class _DiffOp {
339 var $type;
340 var $orig;
341 var $closing;
343 function reverse() {
344 trigger_error('pure virtual', E_USER_ERROR);
347 function norig() {
348 return $this->orig ? sizeof($this->orig) : 0;
351 function nclosing() {
352 return $this->closing ? sizeof($this->closing) : 0;
357 * @todo document
358 * @access private
359 * @package MediaWiki
360 * @subpackage DifferenceEngine
362 class _DiffOp_Copy extends _DiffOp {
363 var $type = 'copy';
365 function _DiffOp_Copy ($orig, $closing = false) {
366 if (!is_array($closing))
367 $closing = $orig;
368 $this->orig = $orig;
369 $this->closing = $closing;
372 function reverse() {
373 return new _DiffOp_Copy($this->closing, $this->orig);
378 * @todo document
379 * @access private
380 * @package MediaWiki
381 * @subpackage DifferenceEngine
383 class _DiffOp_Delete extends _DiffOp {
384 var $type = 'delete';
386 function _DiffOp_Delete ($lines) {
387 $this->orig = $lines;
388 $this->closing = false;
391 function reverse() {
392 return new _DiffOp_Add($this->orig);
397 * @todo document
398 * @access private
399 * @package MediaWiki
400 * @subpackage DifferenceEngine
402 class _DiffOp_Add extends _DiffOp {
403 var $type = 'add';
405 function _DiffOp_Add ($lines) {
406 $this->closing = $lines;
407 $this->orig = false;
410 function reverse() {
411 return new _DiffOp_Delete($this->closing);
416 * @todo document
417 * @access private
418 * @package MediaWiki
419 * @subpackage DifferenceEngine
421 class _DiffOp_Change extends _DiffOp {
422 var $type = 'change';
424 function _DiffOp_Change ($orig, $closing) {
425 $this->orig = $orig;
426 $this->closing = $closing;
429 function reverse() {
430 return new _DiffOp_Change($this->closing, $this->orig);
436 * Class used internally by Diff to actually compute the diffs.
438 * The algorithm used here is mostly lifted from the perl module
439 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
440 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
442 * More ideas are taken from:
443 * http://www.ics.uci.edu/~eppstein/161/960229.html
445 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
446 * diffutils-2.7, which can be found at:
447 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
449 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
450 * are my own.
452 * @author Geoffrey T. Dairiki
453 * @access private
454 * @package MediaWiki
455 * @subpackage DifferenceEngine
457 class _DiffEngine
459 function diff ($from_lines, $to_lines) {
460 $fname = '_DiffEngine::diff';
461 wfProfileIn( $fname );
463 $n_from = sizeof($from_lines);
464 $n_to = sizeof($to_lines);
466 $this->xchanged = $this->ychanged = array();
467 $this->xv = $this->yv = array();
468 $this->xind = $this->yind = array();
469 unset($this->seq);
470 unset($this->in_seq);
471 unset($this->lcs);
473 // Skip leading common lines.
474 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
475 if ($from_lines[$skip] != $to_lines[$skip])
476 break;
477 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
479 // Skip trailing common lines.
480 $xi = $n_from; $yi = $n_to;
481 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
482 if ($from_lines[$xi] != $to_lines[$yi])
483 break;
484 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
487 // Ignore lines which do not exist in both files.
488 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
489 $xhash[$from_lines[$xi]] = 1;
490 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
491 $line = $to_lines[$yi];
492 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
493 continue;
494 $yhash[$line] = 1;
495 $this->yv[] = $line;
496 $this->yind[] = $yi;
498 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
499 $line = $from_lines[$xi];
500 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
501 continue;
502 $this->xv[] = $line;
503 $this->xind[] = $xi;
506 // Find the LCS.
507 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
509 // Merge edits when possible
510 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
511 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
513 // Compute the edit operations.
514 $edits = array();
515 $xi = $yi = 0;
516 while ($xi < $n_from || $yi < $n_to) {
517 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
518 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
520 // Skip matching "snake".
521 $copy = array();
522 while ( $xi < $n_from && $yi < $n_to
523 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
524 $copy[] = $from_lines[$xi++];
525 ++$yi;
527 if ($copy)
528 $edits[] = new _DiffOp_Copy($copy);
530 // Find deletes & adds.
531 $delete = array();
532 while ($xi < $n_from && $this->xchanged[$xi])
533 $delete[] = $from_lines[$xi++];
535 $add = array();
536 while ($yi < $n_to && $this->ychanged[$yi])
537 $add[] = $to_lines[$yi++];
539 if ($delete && $add)
540 $edits[] = new _DiffOp_Change($delete, $add);
541 elseif ($delete)
542 $edits[] = new _DiffOp_Delete($delete);
543 elseif ($add)
544 $edits[] = new _DiffOp_Add($add);
546 wfProfileOut( $fname );
547 return $edits;
551 /* Divide the Largest Common Subsequence (LCS) of the sequences
552 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
553 * sized segments.
555 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
556 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
557 * sub sequences. The first sub-sequence is contained in [X0, X1),
558 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
559 * that (X0, Y0) == (XOFF, YOFF) and
560 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
562 * This function assumes that the first lines of the specified portions
563 * of the two files do not match, and likewise that the last lines do not
564 * match. The caller must trim matching lines from the beginning and end
565 * of the portions it is going to specify.
567 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
568 $fname = '_DiffEngine::_diag';
569 wfProfileIn( $fname );
570 $flip = false;
572 if ($xlim - $xoff > $ylim - $yoff) {
573 // Things seems faster (I'm not sure I understand why)
574 // when the shortest sequence in X.
575 $flip = true;
576 list ($xoff, $xlim, $yoff, $ylim)
577 = array( $yoff, $ylim, $xoff, $xlim);
580 if ($flip)
581 for ($i = $ylim - 1; $i >= $yoff; $i--)
582 $ymatches[$this->xv[$i]][] = $i;
583 else
584 for ($i = $ylim - 1; $i >= $yoff; $i--)
585 $ymatches[$this->yv[$i]][] = $i;
587 $this->lcs = 0;
588 $this->seq[0]= $yoff - 1;
589 $this->in_seq = array();
590 $ymids[0] = array();
592 $numer = $xlim - $xoff + $nchunks - 1;
593 $x = $xoff;
594 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
595 wfProfileIn( "$fname-chunk" );
596 if ($chunk > 0)
597 for ($i = 0; $i <= $this->lcs; $i++)
598 $ymids[$i][$chunk-1] = $this->seq[$i];
600 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
601 for ( ; $x < $x1; $x++) {
602 $line = $flip ? $this->yv[$x] : $this->xv[$x];
603 if (empty($ymatches[$line]))
604 continue;
605 $matches = $ymatches[$line];
606 reset($matches);
607 while (list ($junk, $y) = each($matches))
608 if (empty($this->in_seq[$y])) {
609 $k = $this->_lcs_pos($y);
610 USE_ASSERTS && assert($k > 0);
611 $ymids[$k] = $ymids[$k-1];
612 break;
614 while (list ($junk, $y) = each($matches)) {
615 if ($y > $this->seq[$k-1]) {
616 USE_ASSERTS && assert($y < $this->seq[$k]);
617 // Optimization: this is a common case:
618 // next match is just replacing previous match.
619 $this->in_seq[$this->seq[$k]] = false;
620 $this->seq[$k] = $y;
621 $this->in_seq[$y] = 1;
622 } else if (empty($this->in_seq[$y])) {
623 $k = $this->_lcs_pos($y);
624 USE_ASSERTS && assert($k > 0);
625 $ymids[$k] = $ymids[$k-1];
629 wfProfileOut( "$fname-chunk" );
632 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
633 $ymid = $ymids[$this->lcs];
634 for ($n = 0; $n < $nchunks - 1; $n++) {
635 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
636 $y1 = $ymid[$n] + 1;
637 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
639 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
641 wfProfileOut( $fname );
642 return array($this->lcs, $seps);
645 function _lcs_pos ($ypos) {
646 $fname = '_DiffEngine::_lcs_pos';
647 wfProfileIn( $fname );
649 $end = $this->lcs;
650 if ($end == 0 || $ypos > $this->seq[$end]) {
651 $this->seq[++$this->lcs] = $ypos;
652 $this->in_seq[$ypos] = 1;
653 wfProfileOut( $fname );
654 return $this->lcs;
657 $beg = 1;
658 while ($beg < $end) {
659 $mid = (int)(($beg + $end) / 2);
660 if ( $ypos > $this->seq[$mid] )
661 $beg = $mid + 1;
662 else
663 $end = $mid;
666 USE_ASSERTS && assert($ypos != $this->seq[$end]);
668 $this->in_seq[$this->seq[$end]] = false;
669 $this->seq[$end] = $ypos;
670 $this->in_seq[$ypos] = 1;
671 wfProfileOut( $fname );
672 return $end;
675 /* Find LCS of two sequences.
677 * The results are recorded in the vectors $this->{x,y}changed[], by
678 * storing a 1 in the element for each line that is an insertion
679 * or deletion (ie. is not in the LCS).
681 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
683 * Note that XLIM, YLIM are exclusive bounds.
684 * All line numbers are origin-0 and discarded lines are not counted.
686 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
687 $fname = '_DiffEngine::_compareseq';
688 wfProfileIn( $fname );
690 // Slide down the bottom initial diagonal.
691 while ($xoff < $xlim && $yoff < $ylim
692 && $this->xv[$xoff] == $this->yv[$yoff]) {
693 ++$xoff;
694 ++$yoff;
697 // Slide up the top initial diagonal.
698 while ($xlim > $xoff && $ylim > $yoff
699 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
700 --$xlim;
701 --$ylim;
704 if ($xoff == $xlim || $yoff == $ylim)
705 $lcs = 0;
706 else {
707 // This is ad hoc but seems to work well.
708 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
709 //$nchunks = max(2,min(8,(int)$nchunks));
710 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
711 list ($lcs, $seps)
712 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
715 if ($lcs == 0) {
716 // X and Y sequences have no common subsequence:
717 // mark all changed.
718 while ($yoff < $ylim)
719 $this->ychanged[$this->yind[$yoff++]] = 1;
720 while ($xoff < $xlim)
721 $this->xchanged[$this->xind[$xoff++]] = 1;
722 } else {
723 // Use the partitions to split this problem into subproblems.
724 reset($seps);
725 $pt1 = $seps[0];
726 while ($pt2 = next($seps)) {
727 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
728 $pt1 = $pt2;
731 wfProfileOut( $fname );
734 /* Adjust inserts/deletes of identical lines to join changes
735 * as much as possible.
737 * We do something when a run of changed lines include a
738 * line at one end and has an excluded, identical line at the other.
739 * We are free to choose which identical line is included.
740 * `compareseq' usually chooses the one at the beginning,
741 * but usually it is cleaner to consider the following identical line
742 * to be the "change".
744 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
746 function _shift_boundaries ($lines, &$changed, $other_changed) {
747 $fname = '_DiffEngine::_shift_boundaries';
748 wfProfileIn( $fname );
749 $i = 0;
750 $j = 0;
752 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
753 $len = sizeof($lines);
754 $other_len = sizeof($other_changed);
756 while (1) {
758 * Scan forwards to find beginning of another run of changes.
759 * Also keep track of the corresponding point in the other file.
761 * Throughout this code, $i and $j are adjusted together so that
762 * the first $i elements of $changed and the first $j elements
763 * of $other_changed both contain the same number of zeros
764 * (unchanged lines).
765 * Furthermore, $j is always kept so that $j == $other_len or
766 * $other_changed[$j] == false.
768 while ($j < $other_len && $other_changed[$j])
769 $j++;
771 while ($i < $len && ! $changed[$i]) {
772 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
773 $i++; $j++;
774 while ($j < $other_len && $other_changed[$j])
775 $j++;
778 if ($i == $len)
779 break;
781 $start = $i;
783 // Find the end of this run of changes.
784 while (++$i < $len && $changed[$i])
785 continue;
787 do {
789 * Record the length of this run of changes, so that
790 * we can later determine whether the run has grown.
792 $runlength = $i - $start;
795 * Move the changed region back, so long as the
796 * previous unchanged line matches the last changed one.
797 * This merges with previous changed regions.
799 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
800 $changed[--$start] = 1;
801 $changed[--$i] = false;
802 while ($start > 0 && $changed[$start - 1])
803 $start--;
804 USE_ASSERTS && assert('$j > 0');
805 while ($other_changed[--$j])
806 continue;
807 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
811 * Set CORRESPONDING to the end of the changed run, at the last
812 * point where it corresponds to a changed run in the other file.
813 * CORRESPONDING == LEN means no such point has been found.
815 $corresponding = $j < $other_len ? $i : $len;
818 * Move the changed region forward, so long as the
819 * first changed line matches the following unchanged one.
820 * This merges with following changed regions.
821 * Do this second, so that if there are no merges,
822 * the changed region is moved forward as far as possible.
824 while ($i < $len && $lines[$start] == $lines[$i]) {
825 $changed[$start++] = false;
826 $changed[$i++] = 1;
827 while ($i < $len && $changed[$i])
828 $i++;
830 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
831 $j++;
832 if ($j < $other_len && $other_changed[$j]) {
833 $corresponding = $i;
834 while ($j < $other_len && $other_changed[$j])
835 $j++;
838 } while ($runlength != $i - $start);
841 * If possible, move the fully-merged run of changes
842 * back to a corresponding run in the other file.
844 while ($corresponding < $i) {
845 $changed[--$start] = 1;
846 $changed[--$i] = 0;
847 USE_ASSERTS && assert('$j > 0');
848 while ($other_changed[--$j])
849 continue;
850 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
853 wfProfileOut( $fname );
858 * Class representing a 'diff' between two sequences of strings.
859 * @todo document
860 * @access private
861 * @package MediaWiki
862 * @subpackage DifferenceEngine
864 class Diff
866 var $edits;
869 * Constructor.
870 * Computes diff between sequences of strings.
872 * @param $from_lines array An array of strings.
873 * (Typically these are lines from a file.)
874 * @param $to_lines array An array of strings.
876 function Diff($from_lines, $to_lines) {
877 $eng = new _DiffEngine;
878 $this->edits = $eng->diff($from_lines, $to_lines);
879 //$this->_check($from_lines, $to_lines);
883 * Compute reversed Diff.
885 * SYNOPSIS:
887 * $diff = new Diff($lines1, $lines2);
888 * $rev = $diff->reverse();
889 * @return object A Diff object representing the inverse of the
890 * original diff.
892 function reverse () {
893 $rev = $this;
894 $rev->edits = array();
895 foreach ($this->edits as $edit) {
896 $rev->edits[] = $edit->reverse();
898 return $rev;
902 * Check for empty diff.
904 * @return bool True iff two sequences were identical.
906 function isEmpty () {
907 foreach ($this->edits as $edit) {
908 if ($edit->type != 'copy')
909 return false;
911 return true;
915 * Compute the length of the Longest Common Subsequence (LCS).
917 * This is mostly for diagnostic purposed.
919 * @return int The length of the LCS.
921 function lcs () {
922 $lcs = 0;
923 foreach ($this->edits as $edit) {
924 if ($edit->type == 'copy')
925 $lcs += sizeof($edit->orig);
927 return $lcs;
931 * Get the original set of lines.
933 * This reconstructs the $from_lines parameter passed to the
934 * constructor.
936 * @return array The original sequence of strings.
938 function orig() {
939 $lines = array();
941 foreach ($this->edits as $edit) {
942 if ($edit->orig)
943 array_splice($lines, sizeof($lines), 0, $edit->orig);
945 return $lines;
949 * Get the closing set of lines.
951 * This reconstructs the $to_lines parameter passed to the
952 * constructor.
954 * @return array The sequence of strings.
956 function closing() {
957 $lines = array();
959 foreach ($this->edits as $edit) {
960 if ($edit->closing)
961 array_splice($lines, sizeof($lines), 0, $edit->closing);
963 return $lines;
967 * Check a Diff for validity.
969 * This is here only for debugging purposes.
971 function _check ($from_lines, $to_lines) {
972 $fname = 'Diff::_check';
973 wfProfileIn( $fname );
974 if (serialize($from_lines) != serialize($this->orig()))
975 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
976 if (serialize($to_lines) != serialize($this->closing()))
977 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
979 $rev = $this->reverse();
980 if (serialize($to_lines) != serialize($rev->orig()))
981 trigger_error("Reversed original doesn't match", E_USER_ERROR);
982 if (serialize($from_lines) != serialize($rev->closing()))
983 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
986 $prevtype = 'none';
987 foreach ($this->edits as $edit) {
988 if ( $prevtype == $edit->type )
989 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
990 $prevtype = $edit->type;
993 $lcs = $this->lcs();
994 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
995 wfProfileOut( $fname );
1000 * FIXME: bad name.
1001 * @todo document
1002 * @access private
1003 * @package MediaWiki
1004 * @subpackage DifferenceEngine
1006 class MappedDiff extends Diff
1009 * Constructor.
1011 * Computes diff between sequences of strings.
1013 * This can be used to compute things like
1014 * case-insensitve diffs, or diffs which ignore
1015 * changes in white-space.
1017 * @param $from_lines array An array of strings.
1018 * (Typically these are lines from a file.)
1020 * @param $to_lines array An array of strings.
1022 * @param $mapped_from_lines array This array should
1023 * have the same size number of elements as $from_lines.
1024 * The elements in $mapped_from_lines and
1025 * $mapped_to_lines are what is actually compared
1026 * when computing the diff.
1028 * @param $mapped_to_lines array This array should
1029 * have the same number of elements as $to_lines.
1031 function MappedDiff($from_lines, $to_lines,
1032 $mapped_from_lines, $mapped_to_lines) {
1033 $fname = 'MappedDiff::MappedDiff';
1034 wfProfileIn( $fname );
1036 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1037 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1039 $this->Diff($mapped_from_lines, $mapped_to_lines);
1041 $xi = $yi = 0;
1042 for ($i = 0; $i < sizeof($this->edits); $i++) {
1043 $orig = &$this->edits[$i]->orig;
1044 if (is_array($orig)) {
1045 $orig = array_slice($from_lines, $xi, sizeof($orig));
1046 $xi += sizeof($orig);
1049 $closing = &$this->edits[$i]->closing;
1050 if (is_array($closing)) {
1051 $closing = array_slice($to_lines, $yi, sizeof($closing));
1052 $yi += sizeof($closing);
1055 wfProfileOut( $fname );
1060 * A class to format Diffs
1062 * This class formats the diff in classic diff format.
1063 * It is intended that this class be customized via inheritance,
1064 * to obtain fancier outputs.
1065 * @todo document
1066 * @access private
1067 * @package MediaWiki
1068 * @subpackage DifferenceEngine
1070 class DiffFormatter
1073 * Number of leading context "lines" to preserve.
1075 * This should be left at zero for this class, but subclasses
1076 * may want to set this to other values.
1078 var $leading_context_lines = 0;
1081 * Number of trailing context "lines" to preserve.
1083 * This should be left at zero for this class, but subclasses
1084 * may want to set this to other values.
1086 var $trailing_context_lines = 0;
1089 * Format a diff.
1091 * @param $diff object A Diff object.
1092 * @return string The formatted output.
1094 function format($diff) {
1095 $fname = 'DiffFormatter::format';
1096 wfProfileIn( $fname );
1098 $xi = $yi = 1;
1099 $block = false;
1100 $context = array();
1102 $nlead = $this->leading_context_lines;
1103 $ntrail = $this->trailing_context_lines;
1105 $this->_start_diff();
1107 foreach ($diff->edits as $edit) {
1108 if ($edit->type == 'copy') {
1109 if (is_array($block)) {
1110 if (sizeof($edit->orig) <= $nlead + $ntrail) {
1111 $block[] = $edit;
1113 else{
1114 if ($ntrail) {
1115 $context = array_slice($edit->orig, 0, $ntrail);
1116 $block[] = new _DiffOp_Copy($context);
1118 $this->_block($x0, $ntrail + $xi - $x0,
1119 $y0, $ntrail + $yi - $y0,
1120 $block);
1121 $block = false;
1124 $context = $edit->orig;
1126 else {
1127 if (! is_array($block)) {
1128 $context = array_slice($context, sizeof($context) - $nlead);
1129 $x0 = $xi - sizeof($context);
1130 $y0 = $yi - sizeof($context);
1131 $block = array();
1132 if ($context)
1133 $block[] = new _DiffOp_Copy($context);
1135 $block[] = $edit;
1138 if ($edit->orig)
1139 $xi += sizeof($edit->orig);
1140 if ($edit->closing)
1141 $yi += sizeof($edit->closing);
1144 if (is_array($block))
1145 $this->_block($x0, $xi - $x0,
1146 $y0, $yi - $y0,
1147 $block);
1149 $end = $this->_end_diff();
1150 wfProfileOut( $fname );
1151 return $end;
1154 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1155 $fname = 'DiffFormatter::_block';
1156 wfProfileIn( $fname );
1157 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1158 foreach ($edits as $edit) {
1159 if ($edit->type == 'copy')
1160 $this->_context($edit->orig);
1161 elseif ($edit->type == 'add')
1162 $this->_added($edit->closing);
1163 elseif ($edit->type == 'delete')
1164 $this->_deleted($edit->orig);
1165 elseif ($edit->type == 'change')
1166 $this->_changed($edit->orig, $edit->closing);
1167 else
1168 trigger_error('Unknown edit type', E_USER_ERROR);
1170 $this->_end_block();
1171 wfProfileOut( $fname );
1174 function _start_diff() {
1175 ob_start();
1178 function _end_diff() {
1179 $val = ob_get_contents();
1180 ob_end_clean();
1181 return $val;
1184 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1185 if ($xlen > 1)
1186 $xbeg .= "," . ($xbeg + $xlen - 1);
1187 if ($ylen > 1)
1188 $ybeg .= "," . ($ybeg + $ylen - 1);
1190 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
1193 function _start_block($header) {
1194 echo $header;
1197 function _end_block() {
1200 function _lines($lines, $prefix = ' ') {
1201 foreach ($lines as $line)
1202 echo "$prefix $line\n";
1205 function _context($lines) {
1206 $this->_lines($lines);
1209 function _added($lines) {
1210 $this->_lines($lines, '>');
1212 function _deleted($lines) {
1213 $this->_lines($lines, '<');
1216 function _changed($orig, $closing) {
1217 $this->_deleted($orig);
1218 echo "---\n";
1219 $this->_added($closing);
1225 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1229 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1232 * @todo document
1233 * @access private
1234 * @package MediaWiki
1235 * @subpackage DifferenceEngine
1237 class _HWLDF_WordAccumulator {
1238 function _HWLDF_WordAccumulator () {
1239 $this->_lines = array();
1240 $this->_line = '';
1241 $this->_group = '';
1242 $this->_tag = '';
1245 function _flushGroup ($new_tag) {
1246 if ($this->_group !== '') {
1247 if ($this->_tag == 'mark')
1248 $this->_line .= '<span class="diffchange">' .
1249 htmlspecialchars ( $this->_group ) . '</span>';
1250 else
1251 $this->_line .= htmlspecialchars ( $this->_group );
1253 $this->_group = '';
1254 $this->_tag = $new_tag;
1257 function _flushLine ($new_tag) {
1258 $this->_flushGroup($new_tag);
1259 if ($this->_line != '')
1260 array_push ( $this->_lines, $this->_line );
1261 else
1262 # make empty lines visible by inserting an NBSP
1263 array_push ( $this->_lines, NBSP );
1264 $this->_line = '';
1267 function addWords ($words, $tag = '') {
1268 if ($tag != $this->_tag)
1269 $this->_flushGroup($tag);
1271 foreach ($words as $word) {
1272 // new-line should only come as first char of word.
1273 if ($word == '')
1274 continue;
1275 if ($word[0] == "\n") {
1276 $this->_flushLine($tag);
1277 $word = substr($word, 1);
1279 assert(!strstr($word, "\n"));
1280 $this->_group .= $word;
1284 function getLines() {
1285 $this->_flushLine('~done');
1286 return $this->_lines;
1291 * @todo document
1292 * @access private
1293 * @package MediaWiki
1294 * @subpackage DifferenceEngine
1296 class WordLevelDiff extends MappedDiff
1298 function WordLevelDiff ($orig_lines, $closing_lines) {
1299 $fname = 'WordLevelDiff::WordLevelDiff';
1300 wfProfileIn( $fname );
1302 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1303 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1306 $this->MappedDiff($orig_words, $closing_words,
1307 $orig_stripped, $closing_stripped);
1308 wfProfileOut( $fname );
1311 function _split($lines) {
1312 $fname = 'WordLevelDiff::_split';
1313 wfProfileIn( $fname );
1314 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1315 implode("\n", $lines),
1316 $m)) {
1317 wfProfileOut( $fname );
1318 return array(array(''), array(''));
1320 wfProfileOut( $fname );
1321 return array($m[0], $m[1]);
1324 function orig () {
1325 $fname = 'WordLevelDiff::orig';
1326 wfProfileIn( $fname );
1327 $orig = new _HWLDF_WordAccumulator;
1329 foreach ($this->edits as $edit) {
1330 if ($edit->type == 'copy')
1331 $orig->addWords($edit->orig);
1332 elseif ($edit->orig)
1333 $orig->addWords($edit->orig, 'mark');
1335 $lines = $orig->getLines();
1336 wfProfileOut( $fname );
1337 return $lines;
1340 function closing () {
1341 $fname = 'WordLevelDiff::closing';
1342 wfProfileIn( $fname );
1343 $closing = new _HWLDF_WordAccumulator;
1345 foreach ($this->edits as $edit) {
1346 if ($edit->type == 'copy')
1347 $closing->addWords($edit->closing);
1348 elseif ($edit->closing)
1349 $closing->addWords($edit->closing, 'mark');
1351 $lines = $closing->getLines();
1352 wfProfileOut( $fname );
1353 return $lines;
1358 * Wikipedia Table style diff formatter.
1359 * @todo document
1360 * @access private
1361 * @package MediaWiki
1362 * @subpackage DifferenceEngine
1364 class TableDiffFormatter extends DiffFormatter
1366 function TableDiffFormatter() {
1367 $this->leading_context_lines = 2;
1368 $this->trailing_context_lines = 2;
1371 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1372 $l1 = wfMsg( 'lineno', $xbeg );
1373 $l2 = wfMsg( 'lineno', $ybeg );
1375 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1376 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1377 return $r;
1380 function _start_block( $header ) {
1381 global $wgOut;
1382 echo $header;
1385 function _end_block() {
1388 function _lines( $lines, $prefix=' ', $color='white' ) {
1391 # HTML-escape parameter before calling this
1392 function addedLine( $line ) {
1393 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1396 # HTML-escape parameter before calling this
1397 function deletedLine( $line ) {
1398 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1401 # HTML-escape parameter before calling this
1402 function contextLine( $line ) {
1403 return "<td> </td><td class='diff-context'>{$line}</td>";
1406 function emptyLine() {
1407 return '<td colspan="2">&nbsp;</td>';
1410 function _added( $lines ) {
1411 foreach ($lines as $line) {
1412 echo '<tr>' . $this->emptyLine() .
1413 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1417 function _deleted($lines) {
1418 foreach ($lines as $line) {
1419 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1420 $this->emptyLine() . "</tr>\n";
1424 function _context( $lines ) {
1425 foreach ($lines as $line) {
1426 echo '<tr>' .
1427 $this->contextLine( htmlspecialchars ( $line ) ) .
1428 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1432 function _changed( $orig, $closing ) {
1433 $fname = 'TableDiffFormatter::_changed';
1434 wfProfileIn( $fname );
1436 $diff = new WordLevelDiff( $orig, $closing );
1437 $del = $diff->orig();
1438 $add = $diff->closing();
1440 # Notice that WordLevelDiff returns HTML-escaped output.
1441 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1443 while ( $line = array_shift( $del ) ) {
1444 $aline = array_shift( $add );
1445 echo '<tr>' . $this->deletedLine( $line ) .
1446 $this->addedLine( $aline ) . "</tr>\n";
1448 foreach ($add as $line) { # If any leftovers
1449 echo '<tr>' . $this->emptyLine() .
1450 $this->addedLine( $line ) . "</tr>\n";
1452 wfProfileOut( $fname );