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