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