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