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