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