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