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