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