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