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