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