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