Integrated C++ wikidiff engine. Enable by setting wgUseExternalDiffEngine to true.
[lhc/web/wiklou.git] / includes / DifferenceEngine.php
1 <?php
2 # See diff.doc
3
4 class DifferenceEngine {
5 /* private */ var $mOldid, $mNewid;
6 /* private */ var $mOldtitle, $mNewtitle;
7 /* private */ var $mOldtext, $mNewtext;
8 /* private */ var $mOldUser, $mNewUser;
9 /* private */ var $mOldComment, $mNewComment;
10 /* private */ var $mOldPage, $mNewPage;
11
12 function DifferenceEngine( $old, $new )
13 {
14 $this->mOldid = $old;
15 $this->mNewid = $new;
16 }
17
18 function showDiffPage()
19 {
20 global $wgUser, $wgTitle, $wgOut, $wgLang;
21 $fname = "DifferenceEngine::showDiffPage";
22 wfProfileIn( $fname );
23
24 $t = $wgTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
25 "{$this->mNewid})";
26 $mtext = wfMsg( "missingarticle", $t );
27
28 $wgOut->setArticleFlag( false );
29 if ( ! $this->loadText() ) {
30 $wgOut->setPagetitle( wfMsg( "errorpagetitle" ) );
31 $wgOut->addHTML( $mtext );
32 wfProfileOut( $fname );
33 return;
34 }
35 $wgOut->suppressQuickbar();
36
37 $oldTitle = $this->mOldPage->getPrefixedText();
38 $newTitle = $this->mNewPage->getPrefixedText();
39 if( $oldTitle == $newTitle ) {
40 $wgOut->setPageTitle( $newTitle );
41 } else {
42 $wgOut->setPageTitle( $oldTitle . ", " . $newTitle );
43 }
44 $wgOut->setSubtitle( wfMsg( "difference" ) );
45 $wgOut->setRobotpolicy( "noindex,follow" );
46
47 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
48 $wgOut->loginToUse();
49 $wgOut->output();
50 wfProfileOut( $fname );
51 exit;
52 }
53
54 $sk = $wgUser->getSkin();
55 $talk = $wgLang->getNsText( NS_TALK );
56 $contribs = wfMsg( "contribslink" );
57
58
59 $this->mOldComment = $sk->formatComment($this->mOldComment);
60 $this->mNewComment = $sk->formatComment($this->mNewComment);
61
62
63 $oldUserLink = $sk->makeLinkObj( Title::makeTitle( NS_USER, $this->mOldUser ), $this->mOldUser );
64 $newUserLink = $sk->makeLinkObj( Title::makeTitle( NS_USER, $this->mNewUser ), $this->mNewUser );
65 $oldUTLink = $sk->makeLinkObj( Title::makeTitle( NS_USER_TALK, $this->mOldUser ), $talk );
66 $newUTLink = $sk->makeLinkObj( Title::makeTitle( NS_USER_TALK, $this->mNewUser ), $talk );
67 $oldContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, "Contributions" ), $contribs,
68 "target=" . urlencode($this->mOldUser) );
69 $newContribs = $sk->makeKnownLinkObj( Title::makeTitle( NS_SPECIAL, "Contributions" ), $contribs,
70 "target=" . urlencode($this->mNewUser) );
71 if ( !$this->mNewid && $wgUser->isSysop() ) {
72 $rollback = "&nbsp;&nbsp;&nbsp;<strong>[" . $sk->makeKnownLinkObj( $wgTitle, wfMsg( "rollbacklink" ),
73 "action=rollback&from=" . urlencode($this->mNewUser) ) . "]</strong>";
74 } else {
75 $rollback = "";
76 }
77
78 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />$oldUserLink ($oldUTLink | $oldContribs)<br />".
79 $this->mOldComment;
80 $newHeader = "<strong>{$this->mNewtitle}</strong><br />$newUserLink ($newUTLink | $newContribs) $rollback<br />".
81 $this->mNewComment;
82
83 DifferenceEngine::showDiff( $this->mOldtext, $this->mNewtext,
84 $oldHeader, $newHeader );
85 $wgOut->addHTML( "<hr /><h2>{$this->mNewtitle}</h2>\n" );
86 $wgOut->addWikiText( $this->mNewtext );
87
88 wfProfileOut( $fname );
89 }
90
91 function showDiff( $otext, $ntext, $otitle, $ntitle )
92 {
93 global $wgOut, $wgUseExternalDiffEngine;
94
95 $otext = str_replace( "\r\n", "\n", htmlspecialchars( $otext ) );
96 $ntext = str_replace( "\r\n", "\n", htmlspecialchars( $ntext ) );
97
98
99 $wgOut->addHTML( "<table border='0' width='98%'
100 cellpadding='0' cellspacing='4px' class='diff'><tr>
101 <td colspan='2' width='50%' align='center' class='diff-otitle'>
102 {$otitle}</td>
103 <td colspan='2' width='50%' align='center' class='diff-ntitle'>
104 {$ntitle}</td>
105 </tr>\n" );
106 if ( $wgUseExternalDiffEngine ) {
107 dl("php_wikidiff.so");
108 $wgOut->addHTML( wikidiff_do_diff( $otext, $ntext, 2) );
109 } else {
110 $ota = explode( "\n", $otext);
111 $nta = explode( "\n", $ntext);
112 $diffs = new Diff( $ota, $nta );
113 $formatter = new TableDiffFormatter();
114 $formatter->format( $diffs );
115 }
116 $wgOut->addHTML( "</table>\n" );
117 }
118
119 # Load the text of the articles to compare. If newid is 0, then compare
120 # the old article in oldid to the current article; if oldid is 0, then
121 # compare the current article to the immediately previous one (ignoring
122 # the value of newid).
123 #
124 function loadText()
125 {
126 global $wgTitle, $wgOut, $wgLang;
127 $fname = "DifferenceEngine::loadText";
128
129 $dbr =& wfGetDB( DB_SLAVE );
130 if ( 0 == $this->mNewid || 0 == $this->mOldid ) {
131 $wgOut->setArticleFlag( true );
132 $this->mNewtitle = wfMsg( "currentrev" );
133 $id = $wgTitle->getArticleID();
134
135 $s = $dbr->getArray( 'cur', array( 'cur_text', 'cur_user_text', 'cur_comment' ),
136 array( 'cur_id' => $id ), $fname );
137 if ( $s === false ) {
138 return false;
139 }
140
141 $this->mNewPage = &$wgTitle;
142 $this->mNewtext = $s->cur_text;
143 $this->mNewUser = $s->cur_user_text;
144 $this->mNewComment = $s->cur_comment;
145 } else {
146 $s = $dbr->getArray( 'old', array( 'old_namespace','old_title','old_timestamp', 'old_text',
147 'old_flags','old_user_text','old_comment' ), array( 'old_id' => $this->mNewid ), $fname );
148
149 if ( $s === false ) {
150 return false;
151 }
152
153 $this->mNewtext = Article::getRevisionText( $s );
154
155 $t = $wgLang->timeanddate( $s->old_timestamp, true );
156 $this->mNewPage = Title::MakeTitle( $s->old_namespace, $s->old_title );
157 $this->mNewtitle = wfMsg( "revisionasof", $t );
158 $this->mNewUser = $s->old_user_text;
159 $this->mNewComment = $s->old_comment;
160 }
161 if ( 0 == $this->mOldid ) {
162 $s = $dbr->getArray( 'old',
163 array( 'old_namespace','old_title','old_timestamp','old_text', 'old_flags','old_user_text','old_comment' ),
164 array( /* WHERE */
165 'old_namespace' => $this->mNewPage->getNamespace(),
166 'old_title' => $this->mNewPage->getDBkey()
167 ), $fname, array( 'ORDER BY' => 'inverse_timestamp', 'USE INDEX' => 'name_title_timestamp' )
168 );
169 } else {
170 $s = $dbr->getArray( 'old',
171 array( 'old_namespace','old_title','old_timestamp','old_text','old_flags','old_user_text','old_comment'),
172 array( 'old_id' => $this->mOldid ),
173 $fname
174 );
175 }
176 if ( $s === false ) {
177 return false;
178 }
179 $this->mOldPage = Title::MakeTitle( $s->old_namespace, $s->old_title );
180 $this->mOldtext = Article::getRevisionText( $s );
181
182 $t = $wgLang->timeanddate( $s->old_timestamp, true );
183 $this->mOldtitle = wfMsg( "revisionasof", $t );
184 $this->mOldUser = $s->old_user_text;
185 $this->mOldComment = $s->old_comment;
186
187 return true;
188 }
189 }
190
191 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
192 //
193 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
194 // You may copy this code freely under the conditions of the GPL.
195 //
196
197 define('USE_ASSERTS', function_exists('assert'));
198
199 class _DiffOp {
200 var $type;
201 var $orig;
202 var $closing;
203
204 function reverse() {
205 trigger_error("pure virtual", E_USER_ERROR);
206 }
207
208 function norig() {
209 return $this->orig ? sizeof($this->orig) : 0;
210 }
211
212 function nclosing() {
213 return $this->closing ? sizeof($this->closing) : 0;
214 }
215 }
216
217 class _DiffOp_Copy extends _DiffOp {
218 var $type = 'copy';
219
220 function _DiffOp_Copy ($orig, $closing = false) {
221 if (!is_array($closing))
222 $closing = $orig;
223 $this->orig = $orig;
224 $this->closing = $closing;
225 }
226
227 function reverse() {
228 return new _DiffOp_Copy($this->closing, $this->orig);
229 }
230 }
231
232 class _DiffOp_Delete extends _DiffOp {
233 var $type = 'delete';
234
235 function _DiffOp_Delete ($lines) {
236 $this->orig = $lines;
237 $this->closing = false;
238 }
239
240 function reverse() {
241 return new _DiffOp_Add($this->orig);
242 }
243 }
244
245 class _DiffOp_Add extends _DiffOp {
246 var $type = 'add';
247
248 function _DiffOp_Add ($lines) {
249 $this->closing = $lines;
250 $this->orig = false;
251 }
252
253 function reverse() {
254 return new _DiffOp_Delete($this->closing);
255 }
256 }
257
258 class _DiffOp_Change extends _DiffOp {
259 var $type = 'change';
260
261 function _DiffOp_Change ($orig, $closing) {
262 $this->orig = $orig;
263 $this->closing = $closing;
264 }
265
266 function reverse() {
267 return new _DiffOp_Change($this->closing, $this->orig);
268 }
269 }
270
271
272 /**
273 * Class used internally by Diff to actually compute the diffs.
274 *
275 * The algorithm used here is mostly lifted from the perl module
276 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
277 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
278 *
279 * More ideas are taken from:
280 * http://www.ics.uci.edu/~eppstein/161/960229.html
281 *
282 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
283 * diffutils-2.7, which can be found at:
284 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
285 *
286 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
287 * are my own.
288 *
289 * @author Geoffrey T. Dairiki
290 * @access private
291 */
292 class _DiffEngine
293 {
294 function diff ($from_lines, $to_lines) {
295 $n_from = sizeof($from_lines);
296 $n_to = sizeof($to_lines);
297
298 $this->xchanged = $this->ychanged = array();
299 $this->xv = $this->yv = array();
300 $this->xind = $this->yind = array();
301 unset($this->seq);
302 unset($this->in_seq);
303 unset($this->lcs);
304
305 // Skip leading common lines.
306 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
307 if ($from_lines[$skip] != $to_lines[$skip])
308 break;
309 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
310 }
311 // Skip trailing common lines.
312 $xi = $n_from; $yi = $n_to;
313 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
314 if ($from_lines[$xi] != $to_lines[$yi])
315 break;
316 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
317 }
318
319 // Ignore lines which do not exist in both files.
320 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
321 $xhash[$from_lines[$xi]] = 1;
322 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
323 $line = $to_lines[$yi];
324 if ( ($this->ychanged[$yi] = empty($xhash[$line])) )
325 continue;
326 $yhash[$line] = 1;
327 $this->yv[] = $line;
328 $this->yind[] = $yi;
329 }
330 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
331 $line = $from_lines[$xi];
332 if ( ($this->xchanged[$xi] = empty($yhash[$line])) )
333 continue;
334 $this->xv[] = $line;
335 $this->xind[] = $xi;
336 }
337
338 // Find the LCS.
339 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
340
341 // Merge edits when possible
342 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
343 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
344
345 // Compute the edit operations.
346 $edits = array();
347 $xi = $yi = 0;
348 while ($xi < $n_from || $yi < $n_to) {
349 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
350 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
351
352 // Skip matching "snake".
353 $copy = array();
354 while ( $xi < $n_from && $yi < $n_to
355 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
356 $copy[] = $from_lines[$xi++];
357 ++$yi;
358 }
359 if ($copy)
360 $edits[] = new _DiffOp_Copy($copy);
361
362 // Find deletes & adds.
363 $delete = array();
364 while ($xi < $n_from && $this->xchanged[$xi])
365 $delete[] = $from_lines[$xi++];
366
367 $add = array();
368 while ($yi < $n_to && $this->ychanged[$yi])
369 $add[] = $to_lines[$yi++];
370
371 if ($delete && $add)
372 $edits[] = new _DiffOp_Change($delete, $add);
373 elseif ($delete)
374 $edits[] = new _DiffOp_Delete($delete);
375 elseif ($add)
376 $edits[] = new _DiffOp_Add($add);
377 }
378 return $edits;
379 }
380
381
382 /* Divide the Largest Common Subsequence (LCS) of the sequences
383 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
384 * sized segments.
385 *
386 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
387 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
388 * sub sequences. The first sub-sequence is contained in [X0, X1),
389 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
390 * that (X0, Y0) == (XOFF, YOFF) and
391 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
392 *
393 * This function assumes that the first lines of the specified portions
394 * of the two files do not match, and likewise that the last lines do not
395 * match. The caller must trim matching lines from the beginning and end
396 * of the portions it is going to specify.
397 */
398 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
399 $flip = false;
400
401 if ($xlim - $xoff > $ylim - $yoff) {
402 // Things seems faster (I'm not sure I understand why)
403 // when the shortest sequence in X.
404 $flip = true;
405 list ($xoff, $xlim, $yoff, $ylim)
406 = array( $yoff, $ylim, $xoff, $xlim);
407 }
408
409 if ($flip)
410 for ($i = $ylim - 1; $i >= $yoff; $i--)
411 $ymatches[$this->xv[$i]][] = $i;
412 else
413 for ($i = $ylim - 1; $i >= $yoff; $i--)
414 $ymatches[$this->yv[$i]][] = $i;
415
416 $this->lcs = 0;
417 $this->seq[0]= $yoff - 1;
418 $this->in_seq = array();
419 $ymids[0] = array();
420
421 $numer = $xlim - $xoff + $nchunks - 1;
422 $x = $xoff;
423 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
424 if ($chunk > 0)
425 for ($i = 0; $i <= $this->lcs; $i++)
426 $ymids[$i][$chunk-1] = $this->seq[$i];
427
428 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
429 for ( ; $x < $x1; $x++) {
430 $line = $flip ? $this->yv[$x] : $this->xv[$x];
431 if (empty($ymatches[$line]))
432 continue;
433 $matches = $ymatches[$line];
434 reset($matches);
435 while (list ($junk, $y) = each($matches))
436 if (empty($this->in_seq[$y])) {
437 $k = $this->_lcs_pos($y);
438 USE_ASSERTS && assert($k > 0);
439 $ymids[$k] = $ymids[$k-1];
440 break;
441 }
442 while (list ($junk, $y) = each($matches)) {
443 if ($y > $this->seq[$k-1]) {
444 USE_ASSERTS && assert($y < $this->seq[$k]);
445 // Optimization: this is a common case:
446 // next match is just replacing previous match.
447 $this->in_seq[$this->seq[$k]] = false;
448 $this->seq[$k] = $y;
449 $this->in_seq[$y] = 1;
450 }
451 else if (empty($this->in_seq[$y])) {
452 $k = $this->_lcs_pos($y);
453 USE_ASSERTS && assert($k > 0);
454 $ymids[$k] = $ymids[$k-1];
455 }
456 }
457 }
458 }
459
460 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
461 $ymid = $ymids[$this->lcs];
462 for ($n = 0; $n < $nchunks - 1; $n++) {
463 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
464 $y1 = $ymid[$n] + 1;
465 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
466 }
467 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
468
469 return array($this->lcs, $seps);
470 }
471
472 function _lcs_pos ($ypos) {
473 $end = $this->lcs;
474 if ($end == 0 || $ypos > $this->seq[$end]) {
475 $this->seq[++$this->lcs] = $ypos;
476 $this->in_seq[$ypos] = 1;
477 return $this->lcs;
478 }
479
480 $beg = 1;
481 while ($beg < $end) {
482 $mid = (int)(($beg + $end) / 2);
483 if ( $ypos > $this->seq[$mid] )
484 $beg = $mid + 1;
485 else
486 $end = $mid;
487 }
488
489 USE_ASSERTS && assert($ypos != $this->seq[$end]);
490
491 $this->in_seq[$this->seq[$end]] = false;
492 $this->seq[$end] = $ypos;
493 $this->in_seq[$ypos] = 1;
494 return $end;
495 }
496
497 /* Find LCS of two sequences.
498 *
499 * The results are recorded in the vectors $this->{x,y}changed[], by
500 * storing a 1 in the element for each line that is an insertion
501 * or deletion (ie. is not in the LCS).
502 *
503 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
504 *
505 * Note that XLIM, YLIM are exclusive bounds.
506 * All line numbers are origin-0 and discarded lines are not counted.
507 */
508 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
509 // Slide down the bottom initial diagonal.
510 while ($xoff < $xlim && $yoff < $ylim
511 && $this->xv[$xoff] == $this->yv[$yoff]) {
512 ++$xoff;
513 ++$yoff;
514 }
515
516 // Slide up the top initial diagonal.
517 while ($xlim > $xoff && $ylim > $yoff
518 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
519 --$xlim;
520 --$ylim;
521 }
522
523 if ($xoff == $xlim || $yoff == $ylim)
524 $lcs = 0;
525 else {
526 // This is ad hoc but seems to work well.
527 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
528 //$nchunks = max(2,min(8,(int)$nchunks));
529 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
530 list ($lcs, $seps)
531 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
532 }
533
534 if ($lcs == 0) {
535 // X and Y sequences have no common subsequence:
536 // mark all changed.
537 while ($yoff < $ylim)
538 $this->ychanged[$this->yind[$yoff++]] = 1;
539 while ($xoff < $xlim)
540 $this->xchanged[$this->xind[$xoff++]] = 1;
541 }
542 else {
543 // Use the partitions to split this problem into subproblems.
544 reset($seps);
545 $pt1 = $seps[0];
546 while ($pt2 = next($seps)) {
547 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
548 $pt1 = $pt2;
549 }
550 }
551 }
552
553 /* Adjust inserts/deletes of identical lines to join changes
554 * as much as possible.
555 *
556 * We do something when a run of changed lines include a
557 * line at one end and has an excluded, identical line at the other.
558 * We are free to choose which identical line is included.
559 * `compareseq' usually chooses the one at the beginning,
560 * but usually it is cleaner to consider the following identical line
561 * to be the "change".
562 *
563 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
564 */
565 function _shift_boundaries ($lines, &$changed, $other_changed) {
566 $i = 0;
567 $j = 0;
568
569 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
570 $len = sizeof($lines);
571 $other_len = sizeof($other_changed);
572
573 while (1) {
574 /*
575 * Scan forwards to find beginning of another run of changes.
576 * Also keep track of the corresponding point in the other file.
577 *
578 * Throughout this code, $i and $j are adjusted together so that
579 * the first $i elements of $changed and the first $j elements
580 * of $other_changed both contain the same number of zeros
581 * (unchanged lines).
582 * Furthermore, $j is always kept so that $j == $other_len or
583 * $other_changed[$j] == false.
584 */
585 while ($j < $other_len && $other_changed[$j])
586 $j++;
587
588 while ($i < $len && ! $changed[$i]) {
589 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
590 $i++; $j++;
591 while ($j < $other_len && $other_changed[$j])
592 $j++;
593 }
594
595 if ($i == $len)
596 break;
597
598 $start = $i;
599
600 // Find the end of this run of changes.
601 while (++$i < $len && $changed[$i])
602 continue;
603
604 do {
605 /*
606 * Record the length of this run of changes, so that
607 * we can later determine whether the run has grown.
608 */
609 $runlength = $i - $start;
610
611 /*
612 * Move the changed region back, so long as the
613 * previous unchanged line matches the last changed one.
614 * This merges with previous changed regions.
615 */
616 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
617 $changed[--$start] = 1;
618 $changed[--$i] = false;
619 while ($start > 0 && $changed[$start - 1])
620 $start--;
621 USE_ASSERTS && assert('$j > 0');
622 while ($other_changed[--$j])
623 continue;
624 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
625 }
626
627 /*
628 * Set CORRESPONDING to the end of the changed run, at the last
629 * point where it corresponds to a changed run in the other file.
630 * CORRESPONDING == LEN means no such point has been found.
631 */
632 $corresponding = $j < $other_len ? $i : $len;
633
634 /*
635 * Move the changed region forward, so long as the
636 * first changed line matches the following unchanged one.
637 * This merges with following changed regions.
638 * Do this second, so that if there are no merges,
639 * the changed region is moved forward as far as possible.
640 */
641 while ($i < $len && $lines[$start] == $lines[$i]) {
642 $changed[$start++] = false;
643 $changed[$i++] = 1;
644 while ($i < $len && $changed[$i])
645 $i++;
646
647 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
648 $j++;
649 if ($j < $other_len && $other_changed[$j]) {
650 $corresponding = $i;
651 while ($j < $other_len && $other_changed[$j])
652 $j++;
653 }
654 }
655 } while ($runlength != $i - $start);
656
657 /*
658 * If possible, move the fully-merged run of changes
659 * back to a corresponding run in the other file.
660 */
661 while ($corresponding < $i) {
662 $changed[--$start] = 1;
663 $changed[--$i] = 0;
664 USE_ASSERTS && assert('$j > 0');
665 while ($other_changed[--$j])
666 continue;
667 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
668 }
669 }
670 }
671 }
672
673 /**
674 * Class representing a 'diff' between two sequences of strings.
675 */
676 class Diff
677 {
678 var $edits;
679
680 /**
681 * Constructor.
682 * Computes diff between sequences of strings.
683 *
684 * @param $from_lines array An array of strings.
685 * (Typically these are lines from a file.)
686 * @param $to_lines array An array of strings.
687 */
688 function Diff($from_lines, $to_lines) {
689 $eng = new _DiffEngine;
690 $this->edits = $eng->diff($from_lines, $to_lines);
691 //$this->_check($from_lines, $to_lines);
692 }
693
694 /**
695 * Compute reversed Diff.
696 *
697 * SYNOPSIS:
698 *
699 * $diff = new Diff($lines1, $lines2);
700 * $rev = $diff->reverse();
701 * @return object A Diff object representing the inverse of the
702 * original diff.
703 */
704 function reverse () {
705 $rev = $this;
706 $rev->edits = array();
707 foreach ($this->edits as $edit) {
708 $rev->edits[] = $edit->reverse();
709 }
710 return $rev;
711 }
712
713 /**
714 * Check for empty diff.
715 *
716 * @return bool True iff two sequences were identical.
717 */
718 function isEmpty () {
719 foreach ($this->edits as $edit) {
720 if ($edit->type != 'copy')
721 return false;
722 }
723 return true;
724 }
725
726 /**
727 * Compute the length of the Longest Common Subsequence (LCS).
728 *
729 * This is mostly for diagnostic purposed.
730 *
731 * @return int The length of the LCS.
732 */
733 function lcs () {
734 $lcs = 0;
735 foreach ($this->edits as $edit) {
736 if ($edit->type == 'copy')
737 $lcs += sizeof($edit->orig);
738 }
739 return $lcs;
740 }
741
742 /**
743 * Get the original set of lines.
744 *
745 * This reconstructs the $from_lines parameter passed to the
746 * constructor.
747 *
748 * @return array The original sequence of strings.
749 */
750 function orig() {
751 $lines = array();
752
753 foreach ($this->edits as $edit) {
754 if ($edit->orig)
755 array_splice($lines, sizeof($lines), 0, $edit->orig);
756 }
757 return $lines;
758 }
759
760 /**
761 * Get the closing set of lines.
762 *
763 * This reconstructs the $to_lines parameter passed to the
764 * constructor.
765 *
766 * @return array The sequence of strings.
767 */
768 function closing() {
769 $lines = array();
770
771 foreach ($this->edits as $edit) {
772 if ($edit->closing)
773 array_splice($lines, sizeof($lines), 0, $edit->closing);
774 }
775 return $lines;
776 }
777
778 /**
779 * Check a Diff for validity.
780 *
781 * This is here only for debugging purposes.
782 */
783 function _check ($from_lines, $to_lines) {
784 if (serialize($from_lines) != serialize($this->orig()))
785 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
786 if (serialize($to_lines) != serialize($this->closing()))
787 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
788
789 $rev = $this->reverse();
790 if (serialize($to_lines) != serialize($rev->orig()))
791 trigger_error("Reversed original doesn't match", E_USER_ERROR);
792 if (serialize($from_lines) != serialize($rev->closing()))
793 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
794
795
796 $prevtype = 'none';
797 foreach ($this->edits as $edit) {
798 if ( $prevtype == $edit->type )
799 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
800 $prevtype = $edit->type;
801 }
802
803 $lcs = $this->lcs();
804 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
805 }
806 }
807
808 /**
809 * FIXME: bad name.
810 */
811 class MappedDiff
812 extends Diff
813 {
814 /**
815 * Constructor.
816 *
817 * Computes diff between sequences of strings.
818 *
819 * This can be used to compute things like
820 * case-insensitve diffs, or diffs which ignore
821 * changes in white-space.
822 *
823 * @param $from_lines array An array of strings.
824 * (Typically these are lines from a file.)
825 *
826 * @param $to_lines array An array of strings.
827 *
828 * @param $mapped_from_lines array This array should
829 * have the same size number of elements as $from_lines.
830 * The elements in $mapped_from_lines and
831 * $mapped_to_lines are what is actually compared
832 * when computing the diff.
833 *
834 * @param $mapped_to_lines array This array should
835 * have the same number of elements as $to_lines.
836 */
837 function MappedDiff($from_lines, $to_lines,
838 $mapped_from_lines, $mapped_to_lines) {
839
840 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
841 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
842
843 $this->Diff($mapped_from_lines, $mapped_to_lines);
844
845 $xi = $yi = 0;
846 for ($i = 0; $i < sizeof($this->edits); $i++) {
847 $orig = &$this->edits[$i]->orig;
848 if (is_array($orig)) {
849 $orig = array_slice($from_lines, $xi, sizeof($orig));
850 $xi += sizeof($orig);
851 }
852
853 $closing = &$this->edits[$i]->closing;
854 if (is_array($closing)) {
855 $closing = array_slice($to_lines, $yi, sizeof($closing));
856 $yi += sizeof($closing);
857 }
858 }
859 }
860 }
861
862 /**
863 * A class to format Diffs
864 *
865 * This class formats the diff in classic diff format.
866 * It is intended that this class be customized via inheritance,
867 * to obtain fancier outputs.
868 */
869 class DiffFormatter
870 {
871 /**
872 * Number of leading context "lines" to preserve.
873 *
874 * This should be left at zero for this class, but subclasses
875 * may want to set this to other values.
876 */
877 var $leading_context_lines = 0;
878
879 /**
880 * Number of trailing context "lines" to preserve.
881 *
882 * This should be left at zero for this class, but subclasses
883 * may want to set this to other values.
884 */
885 var $trailing_context_lines = 0;
886
887 /**
888 * Format a diff.
889 *
890 * @param $diff object A Diff object.
891 * @return string The formatted output.
892 */
893 function format($diff) {
894
895 $xi = $yi = 1;
896 $block = false;
897 $context = array();
898
899 $nlead = $this->leading_context_lines;
900 $ntrail = $this->trailing_context_lines;
901
902 $this->_start_diff();
903
904 foreach ($diff->edits as $edit) {
905 if ($edit->type == 'copy') {
906 if (is_array($block)) {
907 if (sizeof($edit->orig) <= $nlead + $ntrail) {
908 $block[] = $edit;
909 }
910 else{
911 if ($ntrail) {
912 $context = array_slice($edit->orig, 0, $ntrail);
913 $block[] = new _DiffOp_Copy($context);
914 }
915 $this->_block($x0, $ntrail + $xi - $x0,
916 $y0, $ntrail + $yi - $y0,
917 $block);
918 $block = false;
919 }
920 }
921 $context = $edit->orig;
922 }
923 else {
924 if (! is_array($block)) {
925 $context = array_slice($context, sizeof($context) - $nlead);
926 $x0 = $xi - sizeof($context);
927 $y0 = $yi - sizeof($context);
928 $block = array();
929 if ($context)
930 $block[] = new _DiffOp_Copy($context);
931 }
932 $block[] = $edit;
933 }
934
935 if ($edit->orig)
936 $xi += sizeof($edit->orig);
937 if ($edit->closing)
938 $yi += sizeof($edit->closing);
939 }
940
941 if (is_array($block))
942 $this->_block($x0, $xi - $x0,
943 $y0, $yi - $y0,
944 $block);
945
946 return $this->_end_diff();
947 }
948
949 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
950 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
951 foreach ($edits as $edit) {
952 if ($edit->type == 'copy')
953 $this->_context($edit->orig);
954 elseif ($edit->type == 'add')
955 $this->_added($edit->closing);
956 elseif ($edit->type == 'delete')
957 $this->_deleted($edit->orig);
958 elseif ($edit->type == 'change')
959 $this->_changed($edit->orig, $edit->closing);
960 else
961 trigger_error("Unknown edit type", E_USER_ERROR);
962 }
963 $this->_end_block();
964 }
965
966 function _start_diff() {
967 ob_start();
968 }
969
970 function _end_diff() {
971 $val = ob_get_contents();
972 ob_end_clean();
973 return $val;
974 }
975
976 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
977 if ($xlen > 1)
978 $xbeg .= "," . ($xbeg + $xlen - 1);
979 if ($ylen > 1)
980 $ybeg .= "," . ($ybeg + $ylen - 1);
981
982 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
983 }
984
985 function _start_block($header) {
986 echo $header;
987 }
988
989 function _end_block() {
990 }
991
992 function _lines($lines, $prefix = ' ') {
993 foreach ($lines as $line)
994 echo "$prefix $line\n";
995 }
996
997 function _context($lines) {
998 $this->_lines($lines);
999 }
1000
1001 function _added($lines) {
1002 $this->_lines($lines, ">");
1003 }
1004 function _deleted($lines) {
1005 $this->_lines($lines, "<");
1006 }
1007
1008 function _changed($orig, $closing) {
1009 $this->_deleted($orig);
1010 echo "---\n";
1011 $this->_added($closing);
1012 }
1013 }
1014
1015
1016 /**
1017 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1018 *
1019 */
1020
1021 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1022
1023 class _HWLDF_WordAccumulator {
1024 function _HWLDF_WordAccumulator () {
1025 $this->_lines = array();
1026 $this->_line = '';
1027 $this->_group = '';
1028 $this->_tag = '';
1029 }
1030
1031 function _flushGroup ($new_tag) {
1032 if ($this->_group !== '') {
1033 if ($this->_tag == 'mark')
1034 $this->_line .= '<span class="diffchange">'.$this->_group.'</span>';
1035 else
1036 $this->_line .= $this->_group;
1037 }
1038 $this->_group = '';
1039 $this->_tag = $new_tag;
1040 }
1041
1042 function _flushLine ($new_tag) {
1043 $this->_flushGroup($new_tag);
1044 if ($this->_line != '')
1045 $this->_lines[] = $this->_line;
1046 $this->_line = '';
1047 }
1048
1049 function addWords ($words, $tag = '') {
1050 if ($tag != $this->_tag)
1051 $this->_flushGroup($tag);
1052
1053 foreach ($words as $word) {
1054 // new-line should only come as first char of word.
1055 if ($word == '')
1056 continue;
1057 if ($word[0] == "\n") {
1058 $this->_group .= NBSP;
1059 $this->_flushLine($tag);
1060 $word = substr($word, 1);
1061 }
1062 assert(!strstr($word, "\n"));
1063 $this->_group .= $word;
1064 }
1065 }
1066
1067 function getLines() {
1068 $this->_flushLine('~done');
1069 return $this->_lines;
1070 }
1071 }
1072
1073 class WordLevelDiff extends MappedDiff
1074 {
1075 function WordLevelDiff ($orig_lines, $closing_lines) {
1076 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1077 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1078
1079
1080 $this->MappedDiff($orig_words, $closing_words,
1081 $orig_stripped, $closing_stripped);
1082 }
1083
1084 function _split($lines) {
1085 // FIXME: fix POSIX char class.
1086 # if (!preg_match_all('/ ( [^\S\n]+ | [[:alnum:]]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1087 if (!preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1088 implode("\n", $lines),
1089 $m)) {
1090 return array(array(''), array(''));
1091 }
1092 return array($m[0], $m[1]);
1093 }
1094
1095 function orig () {
1096 $orig = new _HWLDF_WordAccumulator;
1097
1098 foreach ($this->edits as $edit) {
1099 if ($edit->type == 'copy')
1100 $orig->addWords($edit->orig);
1101 elseif ($edit->orig)
1102 $orig->addWords($edit->orig, 'mark');
1103 }
1104 return $orig->getLines();
1105 }
1106
1107 function closing () {
1108 $closing = new _HWLDF_WordAccumulator;
1109
1110 foreach ($this->edits as $edit) {
1111 if ($edit->type == 'copy')
1112 $closing->addWords($edit->closing);
1113 elseif ($edit->closing)
1114 $closing->addWords($edit->closing, 'mark');
1115 }
1116 return $closing->getLines();
1117 }
1118 }
1119
1120 /**
1121 * Wikipedia Table style diff formatter.
1122 *
1123 */
1124 class TableDiffFormatter extends DiffFormatter
1125 {
1126 function TableDiffFormatter() {
1127 $this->leading_context_lines = 2;
1128 $this->trailing_context_lines = 2;
1129 }
1130
1131 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1132 $l1 = wfMsg( "lineno", $xbeg );
1133 $l2 = wfMsg( "lineno", $ybeg );
1134
1135 $r = '<tr><td colspan="2" align="left"><strong>'.$l1."</strong></td>\n" .
1136 '<td colspan="2" align="left"><strong>'.$l2."</strong></td></tr>\n";
1137 return $r;
1138 }
1139
1140 function _start_block( $header ) {
1141 global $wgOut;
1142 $wgOut->addHTML( $header );
1143 }
1144
1145 function _end_block() {
1146 }
1147
1148 function _lines( $lines, $prefix=' ', $color="white" ) {
1149 }
1150
1151 function addedLine( $line ) {
1152 return '<td>+</td><td class="diff-addedline">' .
1153 $line.'</td>';
1154 }
1155
1156 function deletedLine( $line ) {
1157 return '<td>-</td><td class="diff-deletedline">' .
1158 $line.'</td>';
1159 }
1160
1161 function emptyLine() {
1162 return '<td colspan="2">&nbsp;</td>';
1163 }
1164
1165 function contextLine( $line ) {
1166 return '<td> </td><td class="diff-context">'.$line.'</td>';
1167 }
1168
1169 function _added($lines) {
1170 global $wgOut;
1171 foreach ($lines as $line) {
1172 $wgOut->addHTML( '<tr>' . $this->emptyLine() .
1173 $this->addedLine( $line ) . "</tr>\n" );
1174 }
1175 }
1176
1177 function _deleted($lines) {
1178 global $wgOut;
1179 foreach ($lines as $line) {
1180 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1181 $this->emptyLine() . "</tr>\n" );
1182 }
1183 }
1184
1185 function _context( $lines ) {
1186 global $wgOut;
1187 foreach ($lines as $line) {
1188 $wgOut->addHTML( '<tr>' . $this->contextLine( $line ) .
1189 $this->contextLine( $line ) . "</tr>\n" );
1190 }
1191 }
1192
1193 function _changed( $orig, $closing ) {
1194 global $wgOut;
1195 $diff = new WordLevelDiff( $orig, $closing );
1196 $del = $diff->orig();
1197 $add = $diff->closing();
1198
1199 while ( $line = array_shift( $del ) ) {
1200 $aline = array_shift( $add );
1201 $wgOut->addHTML( '<tr>' . $this->deletedLine( $line ) .
1202 $this->addedLine( $aline ) . "</tr>\n" );
1203 }
1204 $this->_added( $add ); # If any leftovers
1205 }
1206 }
1207
1208 ?>