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