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