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