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