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