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