* double quotes to single quotes
[mediawiki.git] / includes / DifferenceEngine.php
blobe2e5180b87dc7dc4b1de4c0e529d6e520721e139
1 <?php
2 /**
3 * See diff.doc
4 * @package MediaWiki
5 */
7 /**
8 * @todo document
9 * @package MediaWiki
11 class DifferenceEngine {
12 /* private */ var $mOldid, $mNewid;
13 /* private */ var $mOldtitle, $mNewtitle, $mPagetitle;
14 /* private */ var $mOldtext, $mNewtext;
15 /* private */ var $mOldUser, $mNewUser;
16 /* private */ var $mOldComment, $mNewComment;
17 /* private */ var $mOldPage, $mNewPage;
18 /* private */ var $mRcidMarkPatrolled;
20 function DifferenceEngine( $old, $new, $rcid = 0 )
22 global $wgTitle;
23 if ( 'prev' == $new ) {
24 # Show diff between revision $old and the previous one.
25 # Get previous one from DB.
27 $this->mNewid = intval($old);
28 $dbr =& wfGetDB( DB_SLAVE );
29 $this->mOldid = $dbr->selectField( 'old', 'old_id',
30 "old_title='" . $wgTitle->getDBkey() . "'" .
31 ' AND old_namespace=' . $wgTitle->getNamespace() .
32 " AND old_id<{$this->mNewid} ORDER BY old_id DESC" );
34 } elseif ( 'next' == $new ) {
36 # Show diff between revision $old and the previous one.
37 # Get previous one from DB.
39 $this->mOldid = intval($old);
40 $dbr =& wfGetDB( DB_SLAVE );
41 $this->mNewid = $dbr->selectField( 'old', 'old_id',
42 "old_title='" . $wgTitle->getDBkey() . "'" .
43 ' AND old_namespace=' . $wgTitle->getNamespace() .
44 " AND old_id>{$this->mOldid} ORDER BY old_id " );
45 if ( false === $this->mNewid ) {
46 # if no result, NewId points to the newest old revision. The only newer
47 # revision is cur, which is "0".
48 $this->mNewid = 0;
51 } else {
53 $this->mOldid = intval($old);
54 $this->mNewid = intval($new);
56 $this->mRcidMarkPatrolled = intval($rcid); # force it to be an integer
59 function showDiffPage()
61 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgOnlySysopsCanPatrol, $wgUseRCPatrol;
62 $fname = 'DifferenceEngine::showDiffPage';
63 wfProfileIn( $fname );
65 # mOldid is false if the difference engine is called with a "vague" query for
66 # a diff between a version V and its previous version V' AND the version V
67 # is the first version of that article. In that case, V' does not exist.
68 if ( $this->mOldid === false ) {
69 $this->showFirstRevision();
70 wfProfileOut( $fname );
71 return;
74 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
75 "{$this->mNewid})";
76 $mtext = wfMsg( 'missingarticle', $t );
78 $wgOut->setArticleFlag( false );
79 if ( ! $this->loadText() ) {
80 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
81 $wgOut->addHTML( $mtext );
82 wfProfileOut( $fname );
83 return;
85 $wgOut->suppressQuickbar();
87 $oldTitle = $this->mOldPage->getPrefixedText();
88 $newTitle = $this->mNewPage->getPrefixedText();
89 if( $oldTitle == $newTitle ) {
90 $wgOut->setPageTitle( $newTitle );
91 } else {
92 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
94 $wgOut->setSubtitle( wfMsg( 'difference' ) );
95 $wgOut->setRobotpolicy( 'noindex,follow' );
97 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
98 $wgOut->loginToUse();
99 $wgOut->output();
100 wfProfileOut( $fname );
101 exit;
104 $sk = $wgUser->getSkin();
105 $talk = $wgLang->getNsText( NS_TALK );
106 $contribs = wfMsg( 'contribslink' );
108 $this->mOldComment = $sk->formatComment($this->mOldComment);
109 $this->mNewComment = $sk->formatComment($this->mNewComment);
111 $oldUserLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER, $this->mOldUser ), $this->mOldUser );
112 $newUserLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER, $this->mNewUser ), $this->mNewUser );
113 $oldUTLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER_TALK, $this->mOldUser ), $talk );
114 $newUTLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER_TALK, $this->mNewUser ), $talk );
115 $oldContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, 'Contributions' ), $contribs,
116 'target=' . urlencode($this->mOldUser) );
117 $newContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, 'Contributions' ), $contribs,
118 'target=' . urlencode($this->mNewUser) );
119 if ( !$this->mNewid && $wgUser->isSysop() ) {
120 $rollback = '&nbsp;&nbsp;&nbsp;<strong>[' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'rollbacklink' ),
121 'action=rollback&from=' . urlencode($this->mNewUser) ) . ']</strong>';
122 } else {
123 $rollback = '';
125 if ( $wgUseRCPatrol && $this->mRcidMarkPatrolled != 0 && $wgUser->getID() != 0 &&
126 ( $wgUser->isSysop() || !$wgOnlySysopsCanPatrol ) )
128 $patrol = ' [' . $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'markaspatrolleddiff' ),
129 "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
130 } else {
131 $patrol = '';
134 $prevlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'previousdiff' ), 'diff=prev&oldid='.$this->mOldid );
135 if ( $this->mNewid == 0 ) {
136 $nextlink = '';
137 } else {
138 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid );
141 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink " .
142 "($oldUTLink | $oldContribs)<br />" . $this->mOldComment .
143 '<br />' . $prevlink;
144 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink " .
145 "($newUTLink | $newContribs) $rollback<br />" . $this->mNewComment .
146 '<br />' . $nextlink . $patrol;
148 DifferenceEngine::showDiff( $this->mOldtext, $this->mNewtext,
149 $oldHeader, $newHeader );
150 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
151 $wgOut->addWikiText( $this->mNewtext );
153 wfProfileOut( $fname );
156 # Show the first revision of an article. Uses normal diff headers in contrast to normal
157 # "old revision" display style.
159 function showFirstRevision()
161 global $wgOut, $wgTitle, $wgUser, $wgLang;
163 $fname = 'DifferenceEngine::showFirstRevision';
164 wfProfileIn( $fname );
167 $this->mOldid = $this->mNewid; # hack to make loadText() work.
169 # Get article text from the DB
171 if ( ! $this->loadText() ) {
172 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
173 "{$this->mNewid})";
174 $mtext = wfMsg( 'missingarticle', $t );
175 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
176 $wgOut->addHTML( $mtext );
177 wfProfileOut( $fname );
178 return;
181 # Check if user is allowed to look at this page. If not, bail out.
183 if ( !( $this->mOldPage->userCanRead() ) ) {
184 $wgOut->loginToUse();
185 $wgOut->output();
186 wfProfileOut( $fname );
187 exit;
190 # Prepare the header box
192 $sk = $wgUser->getSkin();
194 $uTLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER_TALK, $this->mOldUser ), $wgLang->getNsText( NS_TALK ) );
195 $userLink = $sk->makeLinkObj( Title::makeTitleSafe( NS_USER, $this->mOldUser ), $this->mOldUser );
196 $contribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, 'Contributions' ), wfMsg( 'contribslink' ),
197 'target=' . urlencode($this->mOldUser) );
198 $nextlink = $sk->makeKnownLinkObj( $wgTitle, wfMsg( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid );
199 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />$userLink " .
200 "($uTLink | $contribs)<br />" . $this->mOldComment .
201 '<br />' . $nextlink. "</div>\n";
203 $wgOut->addHTML( $header );
205 $wgOut->setSubtitle( wfMsg( 'difference' ) );
206 $wgOut->setRobotpolicy( 'noindex,follow' );
209 # Show current revision
211 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
212 $wgOut->addWikiText( $this->mNewtext );
214 wfProfileOut( $fname );
217 function showDiff( $otext, $ntext, $otitle, $ntitle )
219 global $wgOut, $wgUseExternalDiffEngine;
221 $wgOut->addHTML( "
222 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
223 <tr>
224 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
225 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
226 </tr>
227 " );
229 if ( $wgUseExternalDiffEngine ) {
230 # For historical reasons, external diff engine expects
231 # input text to be HTML-escaped already
232 $otext = str_replace( "\r\n", "\n", htmlspecialchars ( $otext ) );
233 $ntext = str_replace( "\r\n", "\n", htmlspecialchars ( $ntext ) );
234 dl('php_wikidiff.so');
235 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
236 } else {
237 $ota = explode( "\n", str_replace( "\r\n", "\n", $otext ) );
238 $nta = explode( "\n", str_replace( "\r\n", "\n", $ntext ) );
239 $diffs = new Diff( $ota, $nta );
240 $formatter = new TableDiffFormatter();
241 $formatter->format( $diffs );
243 $wgOut->addHTML( "</table>\n" );
246 # Load the text of the articles to compare. If newid is 0, then compare
247 # the old article in oldid to the current article; if oldid is 0, then
248 # compare the current article to the immediately previous one (ignoring
249 # the value of newid).
251 function loadText()
253 global $wgTitle, $wgOut, $wgLang;
254 $fname = 'DifferenceEngine::loadText';
256 $dbr =& wfGetDB( DB_SLAVE );
257 if ( 0 == $this->mNewid || 0 == $this->mOldid ) {
258 $wgOut->setArticleFlag( true );
259 $newLink = $wgTitle->getLocalUrl();
260 $this->mPagetitle = wfMsg( 'currentrev' );
261 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
262 $id = $wgTitle->getArticleID();
264 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
265 array( 'cur_id' => $id ), $fname );
266 if ( $s === false ) {
267 return false;
270 $this->mNewPage = &$wgTitle;
271 $this->mNewtext = $s->cur_text;
272 $this->mNewUser = $s->cur_user_text;
273 $this->mNewComment = $s->cur_comment;
274 } else {
275 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
276 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid ), $fname );
278 if ( $s === false ) {
279 return false;
282 $this->mNewtext = Article::getRevisionText( $s );
284 $t = $wgLang->timeanddate( $s->old_timestamp, true );
285 $this->mNewPage = Title::MakeTitle( $s->old_namespace, $s->old_title );
286 $newLink = $wgTitle->getLocalUrl ('oldid=' . $this->mNewid);
287 $this->mPagetitle = wfMsg( 'revisionasof', $t );
288 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
289 $this->mNewUser = $s->old_user_text;
290 $this->mNewComment = $s->old_comment;
292 if ( 0 == $this->mOldid ) {
293 $s = $dbr->getArray( 'old',
294 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
295 array( /* WHERE */
296 'old_namespace' => $this->mNewPage->getNamespace(),
297 'old_title' => $this->mNewPage->getDBkey()
298 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
300 } else {
301 $s = $dbr->getArray( 'old',
302 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
303 array( 'old_id' => $this->mOldid ),
304 $fname
307 if ( $s === false ) {
308 return false;
310 $this->mOldPage = Title::MakeTitle( $s->old_namespace, $s->old_title );
311 $this->mOldtext = Article::getRevisionText( $s );
313 $t = $wgLang->timeanddate( $s->old_timestamp, true );
314 $oldLink = $this->mOldPage->getLocalUrl ('oldid=' . $this->mOldid);
315 $this->mOldtitle = "<a href='$oldLink'>" . wfMsg( 'revisionasof', $t ) . '</a>';
316 $this->mOldUser = $s->old_user_text;
317 $this->mOldComment = $s->old_comment;
319 return true;
323 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
325 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
326 // You may copy this code freely under the conditions of the GPL.
329 define('USE_ASSERTS', function_exists('assert'));
332 * @todo document
333 * @package MediaWiki
335 class _DiffOp {
336 var $type;
337 var $orig;
338 var $closing;
340 function reverse() {
341 trigger_error('pure virtual', E_USER_ERROR);
344 function norig() {
345 return $this->orig ? sizeof($this->orig) : 0;
348 function nclosing() {
349 return $this->closing ? sizeof($this->closing) : 0;
354 * @todo document
355 * @package MediaWiki
357 class _DiffOp_Copy extends _DiffOp {
358 var $type = 'copy';
360 function _DiffOp_Copy ($orig, $closing = false) {
361 if (!is_array($closing))
362 $closing = $orig;
363 $this->orig = $orig;
364 $this->closing = $closing;
367 function reverse() {
368 return new _DiffOp_Copy($this->closing, $this->orig);
373 * @todo document
374 * @package MediaWiki
376 class _DiffOp_Delete extends _DiffOp {
377 var $type = 'delete';
379 function _DiffOp_Delete ($lines) {
380 $this->orig = $lines;
381 $this->closing = false;
384 function reverse() {
385 return new _DiffOp_Add($this->orig);
390 * @todo document
391 * @package MediaWiki
393 class _DiffOp_Add extends _DiffOp {
394 var $type = 'add';
396 function _DiffOp_Add ($lines) {
397 $this->closing = $lines;
398 $this->orig = false;
401 function reverse() {
402 return new _DiffOp_Delete($this->closing);
407 * @todo document
408 * @package MediaWiki
410 class _DiffOp_Change extends _DiffOp {
411 var $type = 'change';
413 function _DiffOp_Change ($orig, $closing) {
414 $this->orig = $orig;
415 $this->closing = $closing;
418 function reverse() {
419 return new _DiffOp_Change($this->closing, $this->orig);
425 * Class used internally by Diff to actually compute the diffs.
427 * The algorithm used here is mostly lifted from the perl module
428 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
429 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
431 * More ideas are taken from:
432 * http://www.ics.uci.edu/~eppstein/161/960229.html
434 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
435 * diffutils-2.7, which can be found at:
436 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
438 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
439 * are my own.
441 * @author Geoffrey T. Dairiki
442 * @package MediaWiki
443 * @access private
445 class _DiffEngine
447 function diff ($from_lines, $to_lines) {
448 $n_from = sizeof($from_lines);
449 $n_to = sizeof($to_lines);
451 $this->xchanged = $this->ychanged = array();
452 $this->xv = $this->yv = array();
453 $this->xind = $this->yind = array();
454 unset($this->seq);
455 unset($this->in_seq);
456 unset($this->lcs);
458 // Skip leading common lines.
459 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
460 if ($from_lines[$skip] != $to_lines[$skip])
461 break;
462 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
464 // Skip trailing common lines.
465 $xi = $n_from; $yi = $n_to;
466 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
467 if ($from_lines[$xi] != $to_lines[$yi])
468 break;
469 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
472 // Ignore lines which do not exist in both files.
473 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
474 $xhash[$from_lines[$xi]] = 1;
475 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
476 $line = $to_lines[$yi];
477 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
478 continue;
479 $yhash[$line] = 1;
480 $this->yv[] = $line;
481 $this->yind[] = $yi;
483 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
484 $line = $from_lines[$xi];
485 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
486 continue;
487 $this->xv[] = $line;
488 $this->xind[] = $xi;
491 // Find the LCS.
492 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
494 // Merge edits when possible
495 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
496 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
498 // Compute the edit operations.
499 $edits = array();
500 $xi = $yi = 0;
501 while ($xi < $n_from || $yi < $n_to) {
502 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
503 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
505 // Skip matching "snake".
506 $copy = array();
507 while ( $xi < $n_from && $yi < $n_to
508 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
509 $copy[] = $from_lines[$xi++];
510 ++$yi;
512 if ($copy)
513 $edits[] = new _DiffOp_Copy($copy);
515 // Find deletes & adds.
516 $delete = array();
517 while ($xi < $n_from && $this->xchanged[$xi])
518 $delete[] = $from_lines[$xi++];
520 $add = array();
521 while ($yi < $n_to && $this->ychanged[$yi])
522 $add[] = $to_lines[$yi++];
524 if ($delete && $add)
525 $edits[] = new _DiffOp_Change($delete, $add);
526 elseif ($delete)
527 $edits[] = new _DiffOp_Delete($delete);
528 elseif ($add)
529 $edits[] = new _DiffOp_Add($add);
531 return $edits;
535 /* Divide the Largest Common Subsequence (LCS) of the sequences
536 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
537 * sized segments.
539 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
540 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
541 * sub sequences. The first sub-sequence is contained in [X0, X1),
542 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
543 * that (X0, Y0) == (XOFF, YOFF) and
544 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
546 * This function assumes that the first lines of the specified portions
547 * of the two files do not match, and likewise that the last lines do not
548 * match. The caller must trim matching lines from the beginning and end
549 * of the portions it is going to specify.
551 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
552 $flip = false;
554 if ($xlim - $xoff > $ylim - $yoff) {
555 // Things seems faster (I'm not sure I understand why)
556 // when the shortest sequence in X.
557 $flip = true;
558 list ($xoff, $xlim, $yoff, $ylim)
559 = array( $yoff, $ylim, $xoff, $xlim);
562 if ($flip)
563 for ($i = $ylim - 1; $i >= $yoff; $i--)
564 $ymatches[$this->xv[$i]][] = $i;
565 else
566 for ($i = $ylim - 1; $i >= $yoff; $i--)
567 $ymatches[$this->yv[$i]][] = $i;
569 $this->lcs = 0;
570 $this->seq[0]= $yoff - 1;
571 $this->in_seq = array();
572 $ymids[0] = array();
574 $numer = $xlim - $xoff + $nchunks - 1;
575 $x = $xoff;
576 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
577 if ($chunk > 0)
578 for ($i = 0; $i <= $this->lcs; $i++)
579 $ymids[$i][$chunk-1] = $this->seq[$i];
581 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
582 for ( ; $x < $x1; $x++) {
583 $line = $flip ? $this->yv[$x] : $this->xv[$x];
584 if (empty($ymatches[$line]))
585 continue;
586 $matches = $ymatches[$line];
587 reset($matches);
588 while (list ($junk, $y) = each($matches))
589 if (empty($this->in_seq[$y])) {
590 $k = $this->_lcs_pos($y);
591 USE_ASSERTS && assert($k > 0);
592 $ymids[$k] = $ymids[$k-1];
593 break;
595 while (list ($junk, $y) = each($matches)) {
596 if ($y > $this->seq[$k-1]) {
597 USE_ASSERTS && assert($y < $this->seq[$k]);
598 // Optimization: this is a common case:
599 // next match is just replacing previous match.
600 $this->in_seq[$this->seq[$k]] = false;
601 $this->seq[$k] = $y;
602 $this->in_seq[$y] = 1;
604 else if (empty($this->in_seq[$y])) {
605 $k = $this->_lcs_pos($y);
606 USE_ASSERTS && assert($k > 0);
607 $ymids[$k] = $ymids[$k-1];
613 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
614 $ymid = $ymids[$this->lcs];
615 for ($n = 0; $n < $nchunks - 1; $n++) {
616 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
617 $y1 = $ymid[$n] + 1;
618 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
620 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
622 return array($this->lcs, $seps);
625 function _lcs_pos ($ypos) {
626 $end = $this->lcs;
627 if ($end == 0 || $ypos > $this->seq[$end]) {
628 $this->seq[++$this->lcs] = $ypos;
629 $this->in_seq[$ypos] = 1;
630 return $this->lcs;
633 $beg = 1;
634 while ($beg < $end) {
635 $mid = (int)(($beg + $end) / 2);
636 if ( $ypos > $this->seq[$mid] )
637 $beg = $mid + 1;
638 else
639 $end = $mid;
642 USE_ASSERTS && assert($ypos != $this->seq[$end]);
644 $this->in_seq[$this->seq[$end]] = false;
645 $this->seq[$end] = $ypos;
646 $this->in_seq[$ypos] = 1;
647 return $end;
650 /* Find LCS of two sequences.
652 * The results are recorded in the vectors $this->{x,y}changed[], by
653 * storing a 1 in the element for each line that is an insertion
654 * or deletion (ie. is not in the LCS).
656 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
658 * Note that XLIM, YLIM are exclusive bounds.
659 * All line numbers are origin-0 and discarded lines are not counted.
661 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
662 // Slide down the bottom initial diagonal.
663 while ($xoff < $xlim && $yoff < $ylim
664 && $this->xv[$xoff] == $this->yv[$yoff]) {
665 ++$xoff;
666 ++$yoff;
669 // Slide up the top initial diagonal.
670 while ($xlim > $xoff && $ylim > $yoff
671 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
672 --$xlim;
673 --$ylim;
676 if ($xoff == $xlim || $yoff == $ylim)
677 $lcs = 0;
678 else {
679 // This is ad hoc but seems to work well.
680 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
681 //$nchunks = max(2,min(8,(int)$nchunks));
682 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
683 list ($lcs, $seps)
684 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
687 if ($lcs == 0) {
688 // X and Y sequences have no common subsequence:
689 // mark all changed.
690 while ($yoff < $ylim)
691 $this->ychanged[$this->yind[$yoff++]] = 1;
692 while ($xoff < $xlim)
693 $this->xchanged[$this->xind[$xoff++]] = 1;
695 else {
696 // Use the partitions to split this problem into subproblems.
697 reset($seps);
698 $pt1 = $seps[0];
699 while ($pt2 = next($seps)) {
700 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
701 $pt1 = $pt2;
706 /* Adjust inserts/deletes of identical lines to join changes
707 * as much as possible.
709 * We do something when a run of changed lines include a
710 * line at one end and has an excluded, identical line at the other.
711 * We are free to choose which identical line is included.
712 * `compareseq' usually chooses the one at the beginning,
713 * but usually it is cleaner to consider the following identical line
714 * to be the "change".
716 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
718 function _shift_boundaries ($lines, &$changed, $other_changed) {
719 $i = 0;
720 $j = 0;
722 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
723 $len = sizeof($lines);
724 $other_len = sizeof($other_changed);
726 while (1) {
728 * Scan forwards to find beginning of another run of changes.
729 * Also keep track of the corresponding point in the other file.
731 * Throughout this code, $i and $j are adjusted together so that
732 * the first $i elements of $changed and the first $j elements
733 * of $other_changed both contain the same number of zeros
734 * (unchanged lines).
735 * Furthermore, $j is always kept so that $j == $other_len or
736 * $other_changed[$j] == false.
738 while ($j < $other_len && $other_changed[$j])
739 $j++;
741 while ($i < $len && ! $changed[$i]) {
742 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
743 $i++; $j++;
744 while ($j < $other_len && $other_changed[$j])
745 $j++;
748 if ($i == $len)
749 break;
751 $start = $i;
753 // Find the end of this run of changes.
754 while (++$i < $len && $changed[$i])
755 continue;
757 do {
759 * Record the length of this run of changes, so that
760 * we can later determine whether the run has grown.
762 $runlength = $i - $start;
765 * Move the changed region back, so long as the
766 * previous unchanged line matches the last changed one.
767 * This merges with previous changed regions.
769 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
770 $changed[--$start] = 1;
771 $changed[--$i] = false;
772 while ($start > 0 && $changed[$start - 1])
773 $start--;
774 USE_ASSERTS && assert('$j > 0');
775 while ($other_changed[--$j])
776 continue;
777 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
781 * Set CORRESPONDING to the end of the changed run, at the last
782 * point where it corresponds to a changed run in the other file.
783 * CORRESPONDING == LEN means no such point has been found.
785 $corresponding = $j < $other_len ? $i : $len;
788 * Move the changed region forward, so long as the
789 * first changed line matches the following unchanged one.
790 * This merges with following changed regions.
791 * Do this second, so that if there are no merges,
792 * the changed region is moved forward as far as possible.
794 while ($i < $len && $lines[$start] == $lines[$i]) {
795 $changed[$start++] = false;
796 $changed[$i++] = 1;
797 while ($i < $len && $changed[$i])
798 $i++;
800 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
801 $j++;
802 if ($j < $other_len && $other_changed[$j]) {
803 $corresponding = $i;
804 while ($j < $other_len && $other_changed[$j])
805 $j++;
808 } while ($runlength != $i - $start);
811 * If possible, move the fully-merged run of changes
812 * back to a corresponding run in the other file.
814 while ($corresponding < $i) {
815 $changed[--$start] = 1;
816 $changed[--$i] = 0;
817 USE_ASSERTS && assert('$j > 0');
818 while ($other_changed[--$j])
819 continue;
820 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
827 * Class representing a 'diff' between two sequences of strings.
828 * @todo document
829 * @package MediaWiki
831 class Diff
833 var $edits;
836 * Constructor.
837 * Computes diff between sequences of strings.
839 * @param $from_lines array An array of strings.
840 * (Typically these are lines from a file.)
841 * @param $to_lines array An array of strings.
843 function Diff($from_lines, $to_lines) {
844 $eng = new _DiffEngine;
845 $this->edits = $eng->diff($from_lines, $to_lines);
846 //$this->_check($from_lines, $to_lines);
850 * Compute reversed Diff.
852 * SYNOPSIS:
854 * $diff = new Diff($lines1, $lines2);
855 * $rev = $diff->reverse();
856 * @return object A Diff object representing the inverse of the
857 * original diff.
859 function reverse () {
860 $rev = $this;
861 $rev->edits = array();
862 foreach ($this->edits as $edit) {
863 $rev->edits[] = $edit->reverse();
865 return $rev;
869 * Check for empty diff.
871 * @return bool True iff two sequences were identical.
873 function isEmpty () {
874 foreach ($this->edits as $edit) {
875 if ($edit->type != 'copy')
876 return false;
878 return true;
882 * Compute the length of the Longest Common Subsequence (LCS).
884 * This is mostly for diagnostic purposed.
886 * @return int The length of the LCS.
888 function lcs () {
889 $lcs = 0;
890 foreach ($this->edits as $edit) {
891 if ($edit->type == 'copy')
892 $lcs += sizeof($edit->orig);
894 return $lcs;
898 * Get the original set of lines.
900 * This reconstructs the $from_lines parameter passed to the
901 * constructor.
903 * @return array The original sequence of strings.
905 function orig() {
906 $lines = array();
908 foreach ($this->edits as $edit) {
909 if ($edit->orig)
910 array_splice($lines, sizeof($lines), 0, $edit->orig);
912 return $lines;
916 * Get the closing set of lines.
918 * This reconstructs the $to_lines parameter passed to the
919 * constructor.
921 * @return array The sequence of strings.
923 function closing() {
924 $lines = array();
926 foreach ($this->edits as $edit) {
927 if ($edit->closing)
928 array_splice($lines, sizeof($lines), 0, $edit->closing);
930 return $lines;
934 * Check a Diff for validity.
936 * This is here only for debugging purposes.
938 function _check ($from_lines, $to_lines) {
939 if (serialize($from_lines) != serialize($this->orig()))
940 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
941 if (serialize($to_lines) != serialize($this->closing()))
942 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
944 $rev = $this->reverse();
945 if (serialize($to_lines) != serialize($rev->orig()))
946 trigger_error("Reversed original doesn't match", E_USER_ERROR);
947 if (serialize($from_lines) != serialize($rev->closing()))
948 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
951 $prevtype = 'none';
952 foreach ($this->edits as $edit) {
953 if ( $prevtype == $edit->type )
954 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
955 $prevtype = $edit->type;
958 $lcs = $this->lcs();
959 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
964 * FIXME: bad name.
965 * @todo document
966 * @package MediaWiki
968 class MappedDiff extends Diff
971 * Constructor.
973 * Computes diff between sequences of strings.
975 * This can be used to compute things like
976 * case-insensitve diffs, or diffs which ignore
977 * changes in white-space.
979 * @param $from_lines array An array of strings.
980 * (Typically these are lines from a file.)
982 * @param $to_lines array An array of strings.
984 * @param $mapped_from_lines array This array should
985 * have the same size number of elements as $from_lines.
986 * The elements in $mapped_from_lines and
987 * $mapped_to_lines are what is actually compared
988 * when computing the diff.
990 * @param $mapped_to_lines array This array should
991 * have the same number of elements as $to_lines.
993 function MappedDiff($from_lines, $to_lines,
994 $mapped_from_lines, $mapped_to_lines) {
996 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
997 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
999 $this->Diff($mapped_from_lines, $mapped_to_lines);
1001 $xi = $yi = 0;
1002 for ($i = 0; $i < sizeof($this->edits); $i++) {
1003 $orig = &$this->edits[$i]->orig;
1004 if (is_array($orig)) {
1005 $orig = array_slice($from_lines, $xi, sizeof($orig));
1006 $xi += sizeof($orig);
1009 $closing = &$this->edits[$i]->closing;
1010 if (is_array($closing)) {
1011 $closing = array_slice($to_lines, $yi, sizeof($closing));
1012 $yi += sizeof($closing);
1019 * A class to format Diffs
1021 * This class formats the diff in classic diff format.
1022 * It is intended that this class be customized via inheritance,
1023 * to obtain fancier outputs.
1024 * @todo document
1025 * @package MediaWiki
1027 class DiffFormatter
1030 * Number of leading context "lines" to preserve.
1032 * This should be left at zero for this class, but subclasses
1033 * may want to set this to other values.
1035 var $leading_context_lines = 0;
1038 * Number of trailing context "lines" to preserve.
1040 * This should be left at zero for this class, but subclasses
1041 * may want to set this to other values.
1043 var $trailing_context_lines = 0;
1046 * Format a diff.
1048 * @param $diff object A Diff object.
1049 * @return string The formatted output.
1051 function format($diff) {
1053 $xi = $yi = 1;
1054 $block = false;
1055 $context = array();
1057 $nlead = $this->leading_context_lines;
1058 $ntrail = $this->trailing_context_lines;
1060 $this->_start_diff();
1062 foreach ($diff->edits as $edit) {
1063 if ($edit->type == 'copy') {
1064 if (is_array($block)) {
1065 if (sizeof($edit->orig) <= $nlead + $ntrail) {
1066 $block[] = $edit;
1068 else{
1069 if ($ntrail) {
1070 $context = array_slice($edit->orig, 0, $ntrail);
1071 $block[] = new _DiffOp_Copy($context);
1073 $this->_block($x0, $ntrail + $xi - $x0,
1074 $y0, $ntrail + $yi - $y0,
1075 $block);
1076 $block = false;
1079 $context = $edit->orig;
1081 else {
1082 if (! is_array($block)) {
1083 $context = array_slice($context, sizeof($context) - $nlead);
1084 $x0 = $xi - sizeof($context);
1085 $y0 = $yi - sizeof($context);
1086 $block = array();
1087 if ($context)
1088 $block[] = new _DiffOp_Copy($context);
1090 $block[] = $edit;
1093 if ($edit->orig)
1094 $xi += sizeof($edit->orig);
1095 if ($edit->closing)
1096 $yi += sizeof($edit->closing);
1099 if (is_array($block))
1100 $this->_block($x0, $xi - $x0,
1101 $y0, $yi - $y0,
1102 $block);
1104 return $this->_end_diff();
1107 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1108 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1109 foreach ($edits as $edit) {
1110 if ($edit->type == 'copy')
1111 $this->_context($edit->orig);
1112 elseif ($edit->type == 'add')
1113 $this->_added($edit->closing);
1114 elseif ($edit->type == 'delete')
1115 $this->_deleted($edit->orig);
1116 elseif ($edit->type == 'change')
1117 $this->_changed($edit->orig, $edit->closing);
1118 else
1119 trigger_error('Unknown edit type', E_USER_ERROR);
1121 $this->_end_block();
1124 function _start_diff() {
1125 ob_start();
1128 function _end_diff() {
1129 $val = ob_get_contents();
1130 ob_end_clean();
1131 return $val;
1134 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1135 if ($xlen > 1)
1136 $xbeg .= "," . ($xbeg + $xlen - 1);
1137 if ($ylen > 1)
1138 $ybeg .= "," . ($ybeg + $ylen - 1);
1140 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
1143 function _start_block($header) {
1144 echo $header;
1147 function _end_block() {
1150 function _lines($lines, $prefix = ' ') {
1151 foreach ($lines as $line)
1152 echo "$prefix $line\n";
1155 function _context($lines) {
1156 $this->_lines($lines);
1159 function _added($lines) {
1160 $this->_lines($lines, '>');
1162 function _deleted($lines) {
1163 $this->_lines($lines, '<');
1166 function _changed($orig, $closing) {
1167 $this->_deleted($orig);
1168 echo "---\n";
1169 $this->_added($closing);
1175 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1179 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1182 * @todo document
1183 * @package MediaWiki
1185 class _HWLDF_WordAccumulator {
1186 function _HWLDF_WordAccumulator () {
1187 $this->_lines = array();
1188 $this->_line = '';
1189 $this->_group = '';
1190 $this->_tag = '';
1193 function _flushGroup ($new_tag) {
1194 if ($this->_group !== '') {
1195 if ($this->_tag == 'mark')
1196 $this->_line .= '<span class="diffchange">' .
1197 htmlspecialchars ( $this->_group ) . '</span>';
1198 else
1199 $this->_line .= htmlspecialchars ( $this->_group );
1201 $this->_group = '';
1202 $this->_tag = $new_tag;
1205 function _flushLine ($new_tag) {
1206 $this->_flushGroup($new_tag);
1207 if ($this->_line != '')
1208 array_push ( $this->_lines, $this->_line );
1209 else
1210 # make empty lines visible by inserting an NBSP
1211 array_push ( $this->_lines, NBSP );
1212 $this->_line = '';
1215 function addWords ($words, $tag = '') {
1216 if ($tag != $this->_tag)
1217 $this->_flushGroup($tag);
1219 foreach ($words as $word) {
1220 // new-line should only come as first char of word.
1221 if ($word == '')
1222 continue;
1223 if ($word[0] == "\n") {
1224 $this->_flushLine($tag);
1225 $word = substr($word, 1);
1227 assert(!strstr($word, "\n"));
1228 $this->_group .= $word;
1232 function getLines() {
1233 $this->_flushLine('~done');
1234 return $this->_lines;
1239 * @todo document
1240 * @package MediaWiki
1242 class WordLevelDiff extends MappedDiff
1244 function WordLevelDiff ($orig_lines, $closing_lines) {
1245 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1246 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1249 $this->MappedDiff($orig_words, $closing_words,
1250 $orig_stripped, $closing_stripped);
1253 function _split($lines) {
1254 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1255 implode("\n", $lines),
1256 $m)) {
1257 return array(array(''), array(''));
1259 return array($m[0], $m[1]);
1262 function orig () {
1263 $orig = new _HWLDF_WordAccumulator;
1265 foreach ($this->edits as $edit) {
1266 if ($edit->type == 'copy')
1267 $orig->addWords($edit->orig);
1268 elseif ($edit->orig)
1269 $orig->addWords($edit->orig, 'mark');
1271 return $orig->getLines();
1274 function closing () {
1275 $closing = new _HWLDF_WordAccumulator;
1277 foreach ($this->edits as $edit) {
1278 if ($edit->type == 'copy')
1279 $closing->addWords($edit->closing);
1280 elseif ($edit->closing)
1281 $closing->addWords($edit->closing, 'mark');
1283 return $closing->getLines();
1288 * Wikipedia Table style diff formatter.
1289 * @todo document
1290 * @package MediaWiki
1292 class TableDiffFormatter extends DiffFormatter
1294 function TableDiffFormatter() {
1295 $this->leading_context_lines = 2;
1296 $this->trailing_context_lines = 2;
1299 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1300 $l1 = wfMsg( 'lineno', $xbeg );
1301 $l2 = wfMsg( 'lineno', $ybeg );
1303 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1304 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1305 return $r;
1308 function _start_block( $header ) {
1309 global $wgOut;
1310 $wgOut->addHTML( $header );
1313 function _end_block() {
1316 function _lines( $lines, $prefix=' ', $color='white' ) {
1319 # HTML-escape parameter before calling this
1320 function addedLine( $line ) {
1321 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1324 # HTML-escape parameter before calling this
1325 function deletedLine( $line ) {
1326 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1329 # HTML-escape parameter before calling this
1330 function contextLine( $line ) {
1331 return "<td> </td><td class='diff-context'>{$line}</td>";
1334 function emptyLine() {
1335 return '<td colspan="2">&nbsp;</td>';
1338 function _added( $lines ) {
1339 global $wgOut;
1340 foreach ($lines as $line) {
1341 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1342 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1346 function _deleted($lines) {
1347 global $wgOut;
1348 foreach ($lines as $line) {
1349 $wgOut->addHTML( '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1350 $this->emptyLine() . "</tr>\n" );
1354 function _context( $lines ) {
1355 global $wgOut;
1356 foreach ($lines as $line) {
1357 $wgOut->addHTML( '<tr>' .
1358 $this->contextLine( htmlspecialchars ( $line ) ) .
1359 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n" );
1363 function _changed( $orig, $closing ) {
1364 global $wgOut;
1365 $diff = new WordLevelDiff( $orig, $closing );
1366 $del = $diff->orig();
1367 $add = $diff->closing();
1369 # Notice that WordLevelDiff returns HTML-escaped output.
1370 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1372 while ( $line = array_shift( $del ) ) {
1373 $aline = array_shift( $add );
1374 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1375 $this->addedLine( $aline ) . "</tr>\n" );
1377 foreach ($add as $line) { # If any leftovers
1378 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1379 $this->addedLine( $line ) . "</tr>\n" );