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