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