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