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