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