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