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