* Removed a redundant <strong> tag from diff pages that was causing display issues...
[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 if( !$this->mOldPage->equals( $this->mNewPage ) ) {
444 // Comparing two different pages? Count would be meaningless.
445 return '';
446 }
447
448 $oldid = $this->mOldRev->getId();
449 $newid = $this->mNewRev->getId();
450 if ( $oldid > $newid ) {
451 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
452 }
453
454 $n = $this->mTitle->countRevisionsBetween( $oldid, $newid );
455 if ( !$n )
456 return '';
457
458 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
459 }
460
461
462 /**
463 * Add the header to a diff body
464 */
465 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
466 $header = "
467 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
468 <tr>
469 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
470 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
471 </tr>
472 ";
473
474 if ( $multi != '' )
475 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
476
477 return $header . $diff . "</table>";
478 }
479
480 /**
481 * Use specified text instead of loading from the database
482 */
483 function setText( $oldText, $newText ) {
484 $this->mOldtext = $oldText;
485 $this->mNewtext = $newText;
486 $this->mTextLoaded = 2;
487 }
488
489 /**
490 * Load revision metadata for the specified articles. If newid is 0, then compare
491 * the old article in oldid to the current article; if oldid is 0, then
492 * compare the current article to the immediately previous one (ignoring the
493 * value of newid).
494 *
495 * If oldid is false, leave the corresponding revision object set
496 * to false. This is impossible via ordinary user input, and is provided for
497 * API convenience.
498 */
499 function loadRevisionData() {
500 global $wgLang;
501 if ( $this->mRevisionsLoaded ) {
502 return true;
503 } else {
504 // Whether it succeeds or fails, we don't want to try again
505 $this->mRevisionsLoaded = true;
506 }
507
508 // Load the new revision object
509 if( $this->mNewid ) {
510 $this->mNewRev = Revision::newFromId( $this->mNewid );
511 } else {
512 $this->mNewRev = Revision::newFromTitle( $this->mTitle );
513 }
514
515 if( is_null( $this->mNewRev ) ) {
516 return false;
517 }
518
519 // Set assorted variables
520 $timestamp = $wgLang->timeanddate( $this->mNewRev->getTimestamp(), true );
521 $this->mNewPage = $this->mNewRev->getTitle();
522 if( $this->mNewRev->isCurrent() ) {
523 $newLink = $this->mNewPage->escapeLocalUrl();
524 $this->mPagetitle = htmlspecialchars( wfMsg( 'currentrev' ) );
525 $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit' );
526
527 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
528 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
529
530 } else {
531 $newLink = $this->mNewPage->escapeLocalUrl( 'oldid=' . $this->mNewid );
532 $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid );
533 $newUndo = $this->mNewPage->escapeLocalUrl( 'action=edit&undo=' . $this->mNewid );
534 $this->mPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
535
536 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>"
537 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)"
538 . " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
539 }
540
541 // Load the old revision object
542 $this->mOldRev = false;
543 if( $this->mOldid ) {
544 $this->mOldRev = Revision::newFromId( $this->mOldid );
545 } elseif ( $this->mOldid === 0 ) {
546 $rev = $this->mNewRev->getPrevious();
547 if( $rev ) {
548 $this->mOldid = $rev->getId();
549 $this->mOldRev = $rev;
550 } else {
551 // No previous revision; mark to show as first-version only.
552 $this->mOldid = false;
553 $this->mOldRev = false;
554 }
555 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
556
557 if( is_null( $this->mOldRev ) ) {
558 return false;
559 }
560
561 if ( $this->mOldRev ) {
562 $this->mOldPage = $this->mOldRev->getTitle();
563
564 $t = $wgLang->timeanddate( $this->mOldRev->getTimestamp(), true );
565 $oldLink = $this->mOldPage->escapeLocalUrl( 'oldid=' . $this->mOldid );
566 $oldEdit = $this->mOldPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid );
567 $this->mOldtitle = "<strong><a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
568 . "</a></strong> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
569 }
570
571 return true;
572 }
573
574 /**
575 * Load the text of the revisions, as well as revision data.
576 */
577 function loadText() {
578 if ( $this->mTextLoaded == 2 ) {
579 return true;
580 } else {
581 // Whether it succeeds or fails, we don't want to try again
582 $this->mTextLoaded = 2;
583 }
584
585 if ( !$this->loadRevisionData() ) {
586 return false;
587 }
588 if ( $this->mOldRev ) {
589 // FIXME: permission tests
590 $this->mOldtext = $this->mOldRev->getText();
591 if ( $this->mOldtext === false ) {
592 return false;
593 }
594 }
595 if ( $this->mNewRev ) {
596 $this->mNewtext = $this->mNewRev->getText();
597 if ( $this->mNewtext === false ) {
598 return false;
599 }
600 }
601 return true;
602 }
603
604 /**
605 * Load the text of the new revision, not the old one
606 */
607 function loadNewText() {
608 if ( $this->mTextLoaded >= 1 ) {
609 return true;
610 } else {
611 $this->mTextLoaded = 1;
612 }
613 if ( !$this->loadRevisionData() ) {
614 return false;
615 }
616 $this->mNewtext = $this->mNewRev->getText();
617 return true;
618 }
619
620
621 }
622
623 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
624 //
625 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
626 // You may copy this code freely under the conditions of the GPL.
627 //
628
629 define('USE_ASSERTS', function_exists('assert'));
630
631 /**
632 * @todo document
633 * @private
634 * @package MediaWiki
635 * @subpackage DifferenceEngine
636 */
637 class _DiffOp {
638 var $type;
639 var $orig;
640 var $closing;
641
642 function reverse() {
643 trigger_error('pure virtual', E_USER_ERROR);
644 }
645
646 function norig() {
647 return $this->orig ? sizeof($this->orig) : 0;
648 }
649
650 function nclosing() {
651 return $this->closing ? sizeof($this->closing) : 0;
652 }
653 }
654
655 /**
656 * @todo document
657 * @private
658 * @package MediaWiki
659 * @subpackage DifferenceEngine
660 */
661 class _DiffOp_Copy extends _DiffOp {
662 var $type = 'copy';
663
664 function _DiffOp_Copy ($orig, $closing = false) {
665 if (!is_array($closing))
666 $closing = $orig;
667 $this->orig = $orig;
668 $this->closing = $closing;
669 }
670
671 function reverse() {
672 return new _DiffOp_Copy($this->closing, $this->orig);
673 }
674 }
675
676 /**
677 * @todo document
678 * @private
679 * @package MediaWiki
680 * @subpackage DifferenceEngine
681 */
682 class _DiffOp_Delete extends _DiffOp {
683 var $type = 'delete';
684
685 function _DiffOp_Delete ($lines) {
686 $this->orig = $lines;
687 $this->closing = false;
688 }
689
690 function reverse() {
691 return new _DiffOp_Add($this->orig);
692 }
693 }
694
695 /**
696 * @todo document
697 * @private
698 * @package MediaWiki
699 * @subpackage DifferenceEngine
700 */
701 class _DiffOp_Add extends _DiffOp {
702 var $type = 'add';
703
704 function _DiffOp_Add ($lines) {
705 $this->closing = $lines;
706 $this->orig = false;
707 }
708
709 function reverse() {
710 return new _DiffOp_Delete($this->closing);
711 }
712 }
713
714 /**
715 * @todo document
716 * @private
717 * @package MediaWiki
718 * @subpackage DifferenceEngine
719 */
720 class _DiffOp_Change extends _DiffOp {
721 var $type = 'change';
722
723 function _DiffOp_Change ($orig, $closing) {
724 $this->orig = $orig;
725 $this->closing = $closing;
726 }
727
728 function reverse() {
729 return new _DiffOp_Change($this->closing, $this->orig);
730 }
731 }
732
733
734 /**
735 * Class used internally by Diff to actually compute the diffs.
736 *
737 * The algorithm used here is mostly lifted from the perl module
738 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
739 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
740 *
741 * More ideas are taken from:
742 * http://www.ics.uci.edu/~eppstein/161/960229.html
743 *
744 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
745 * diffutils-2.7, which can be found at:
746 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
747 *
748 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
749 * are my own.
750 *
751 * Line length limits for robustness added by Tim Starling, 2005-08-31
752 *
753 * @author Geoffrey T. Dairiki, Tim Starling
754 * @private
755 * @package MediaWiki
756 * @subpackage DifferenceEngine
757 */
758 class _DiffEngine
759 {
760 const MAX_XREF_LENGTH = 10000;
761
762 function diff ($from_lines, $to_lines) {
763 $fname = '_DiffEngine::diff';
764 wfProfileIn( $fname );
765
766 $n_from = sizeof($from_lines);
767 $n_to = sizeof($to_lines);
768
769 $this->xchanged = $this->ychanged = array();
770 $this->xv = $this->yv = array();
771 $this->xind = $this->yind = array();
772 unset($this->seq);
773 unset($this->in_seq);
774 unset($this->lcs);
775
776 // Skip leading common lines.
777 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
778 if ($from_lines[$skip] !== $to_lines[$skip])
779 break;
780 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
781 }
782 // Skip trailing common lines.
783 $xi = $n_from; $yi = $n_to;
784 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
785 if ($from_lines[$xi] !== $to_lines[$yi])
786 break;
787 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
788 }
789
790 // Ignore lines which do not exist in both files.
791 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
792 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
793 }
794
795 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
796 $line = $to_lines[$yi];
797 if ( ($this->ychanged[$yi] = empty($xhash[$this->_line_hash($line)])) )
798 continue;
799 $yhash[$this->_line_hash($line)] = 1;
800 $this->yv[] = $line;
801 $this->yind[] = $yi;
802 }
803 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
804 $line = $from_lines[$xi];
805 if ( ($this->xchanged[$xi] = empty($yhash[$this->_line_hash($line)])) )
806 continue;
807 $this->xv[] = $line;
808 $this->xind[] = $xi;
809 }
810
811 // Find the LCS.
812 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
813
814 // Merge edits when possible
815 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
816 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
817
818 // Compute the edit operations.
819 $edits = array();
820 $xi = $yi = 0;
821 while ($xi < $n_from || $yi < $n_to) {
822 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
823 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
824
825 // Skip matching "snake".
826 $copy = array();
827 while ( $xi < $n_from && $yi < $n_to
828 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
829 $copy[] = $from_lines[$xi++];
830 ++$yi;
831 }
832 if ($copy)
833 $edits[] = new _DiffOp_Copy($copy);
834
835 // Find deletes & adds.
836 $delete = array();
837 while ($xi < $n_from && $this->xchanged[$xi])
838 $delete[] = $from_lines[$xi++];
839
840 $add = array();
841 while ($yi < $n_to && $this->ychanged[$yi])
842 $add[] = $to_lines[$yi++];
843
844 if ($delete && $add)
845 $edits[] = new _DiffOp_Change($delete, $add);
846 elseif ($delete)
847 $edits[] = new _DiffOp_Delete($delete);
848 elseif ($add)
849 $edits[] = new _DiffOp_Add($add);
850 }
851 wfProfileOut( $fname );
852 return $edits;
853 }
854
855 /**
856 * Returns the whole line if it's small enough, or the MD5 hash otherwise
857 */
858 function _line_hash( $line ) {
859 if ( strlen( $line ) > self::MAX_XREF_LENGTH ) {
860 return md5( $line );
861 } else {
862 return $line;
863 }
864 }
865
866
867 /* Divide the Largest Common Subsequence (LCS) of the sequences
868 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
869 * sized segments.
870 *
871 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
872 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
873 * sub sequences. The first sub-sequence is contained in [X0, X1),
874 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
875 * that (X0, Y0) == (XOFF, YOFF) and
876 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
877 *
878 * This function assumes that the first lines of the specified portions
879 * of the two files do not match, and likewise that the last lines do not
880 * match. The caller must trim matching lines from the beginning and end
881 * of the portions it is going to specify.
882 */
883 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
884 $fname = '_DiffEngine::_diag';
885 wfProfileIn( $fname );
886 $flip = false;
887
888 if ($xlim - $xoff > $ylim - $yoff) {
889 // Things seems faster (I'm not sure I understand why)
890 // when the shortest sequence in X.
891 $flip = true;
892 list ($xoff, $xlim, $yoff, $ylim)
893 = array( $yoff, $ylim, $xoff, $xlim);
894 }
895
896 if ($flip)
897 for ($i = $ylim - 1; $i >= $yoff; $i--)
898 $ymatches[$this->xv[$i]][] = $i;
899 else
900 for ($i = $ylim - 1; $i >= $yoff; $i--)
901 $ymatches[$this->yv[$i]][] = $i;
902
903 $this->lcs = 0;
904 $this->seq[0]= $yoff - 1;
905 $this->in_seq = array();
906 $ymids[0] = array();
907
908 $numer = $xlim - $xoff + $nchunks - 1;
909 $x = $xoff;
910 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
911 wfProfileIn( "$fname-chunk" );
912 if ($chunk > 0)
913 for ($i = 0; $i <= $this->lcs; $i++)
914 $ymids[$i][$chunk-1] = $this->seq[$i];
915
916 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
917 for ( ; $x < $x1; $x++) {
918 $line = $flip ? $this->yv[$x] : $this->xv[$x];
919 if (empty($ymatches[$line]))
920 continue;
921 $matches = $ymatches[$line];
922 reset($matches);
923 while (list ($junk, $y) = each($matches))
924 if (empty($this->in_seq[$y])) {
925 $k = $this->_lcs_pos($y);
926 USE_ASSERTS && assert($k > 0);
927 $ymids[$k] = $ymids[$k-1];
928 break;
929 }
930 while (list ( /* $junk */, $y) = each($matches)) {
931 if ($y > $this->seq[$k-1]) {
932 USE_ASSERTS && assert($y < $this->seq[$k]);
933 // Optimization: this is a common case:
934 // next match is just replacing previous match.
935 $this->in_seq[$this->seq[$k]] = false;
936 $this->seq[$k] = $y;
937 $this->in_seq[$y] = 1;
938 } else if (empty($this->in_seq[$y])) {
939 $k = $this->_lcs_pos($y);
940 USE_ASSERTS && assert($k > 0);
941 $ymids[$k] = $ymids[$k-1];
942 }
943 }
944 }
945 wfProfileOut( "$fname-chunk" );
946 }
947
948 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
949 $ymid = $ymids[$this->lcs];
950 for ($n = 0; $n < $nchunks - 1; $n++) {
951 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
952 $y1 = $ymid[$n] + 1;
953 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
954 }
955 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
956
957 wfProfileOut( $fname );
958 return array($this->lcs, $seps);
959 }
960
961 function _lcs_pos ($ypos) {
962 $fname = '_DiffEngine::_lcs_pos';
963 wfProfileIn( $fname );
964
965 $end = $this->lcs;
966 if ($end == 0 || $ypos > $this->seq[$end]) {
967 $this->seq[++$this->lcs] = $ypos;
968 $this->in_seq[$ypos] = 1;
969 wfProfileOut( $fname );
970 return $this->lcs;
971 }
972
973 $beg = 1;
974 while ($beg < $end) {
975 $mid = (int)(($beg + $end) / 2);
976 if ( $ypos > $this->seq[$mid] )
977 $beg = $mid + 1;
978 else
979 $end = $mid;
980 }
981
982 USE_ASSERTS && assert($ypos != $this->seq[$end]);
983
984 $this->in_seq[$this->seq[$end]] = false;
985 $this->seq[$end] = $ypos;
986 $this->in_seq[$ypos] = 1;
987 wfProfileOut( $fname );
988 return $end;
989 }
990
991 /* Find LCS of two sequences.
992 *
993 * The results are recorded in the vectors $this->{x,y}changed[], by
994 * storing a 1 in the element for each line that is an insertion
995 * or deletion (ie. is not in the LCS).
996 *
997 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
998 *
999 * Note that XLIM, YLIM are exclusive bounds.
1000 * All line numbers are origin-0 and discarded lines are not counted.
1001 */
1002 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1003 $fname = '_DiffEngine::_compareseq';
1004 wfProfileIn( $fname );
1005
1006 // Slide down the bottom initial diagonal.
1007 while ($xoff < $xlim && $yoff < $ylim
1008 && $this->xv[$xoff] == $this->yv[$yoff]) {
1009 ++$xoff;
1010 ++$yoff;
1011 }
1012
1013 // Slide up the top initial diagonal.
1014 while ($xlim > $xoff && $ylim > $yoff
1015 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
1016 --$xlim;
1017 --$ylim;
1018 }
1019
1020 if ($xoff == $xlim || $yoff == $ylim)
1021 $lcs = 0;
1022 else {
1023 // This is ad hoc but seems to work well.
1024 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1025 //$nchunks = max(2,min(8,(int)$nchunks));
1026 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
1027 list ($lcs, $seps)
1028 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1029 }
1030
1031 if ($lcs == 0) {
1032 // X and Y sequences have no common subsequence:
1033 // mark all changed.
1034 while ($yoff < $ylim)
1035 $this->ychanged[$this->yind[$yoff++]] = 1;
1036 while ($xoff < $xlim)
1037 $this->xchanged[$this->xind[$xoff++]] = 1;
1038 } else {
1039 // Use the partitions to split this problem into subproblems.
1040 reset($seps);
1041 $pt1 = $seps[0];
1042 while ($pt2 = next($seps)) {
1043 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1044 $pt1 = $pt2;
1045 }
1046 }
1047 wfProfileOut( $fname );
1048 }
1049
1050 /* Adjust inserts/deletes of identical lines to join changes
1051 * as much as possible.
1052 *
1053 * We do something when a run of changed lines include a
1054 * line at one end and has an excluded, identical line at the other.
1055 * We are free to choose which identical line is included.
1056 * `compareseq' usually chooses the one at the beginning,
1057 * but usually it is cleaner to consider the following identical line
1058 * to be the "change".
1059 *
1060 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1061 */
1062 function _shift_boundaries ($lines, &$changed, $other_changed) {
1063 $fname = '_DiffEngine::_shift_boundaries';
1064 wfProfileIn( $fname );
1065 $i = 0;
1066 $j = 0;
1067
1068 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
1069 $len = sizeof($lines);
1070 $other_len = sizeof($other_changed);
1071
1072 while (1) {
1073 /*
1074 * Scan forwards to find beginning of another run of changes.
1075 * Also keep track of the corresponding point in the other file.
1076 *
1077 * Throughout this code, $i and $j are adjusted together so that
1078 * the first $i elements of $changed and the first $j elements
1079 * of $other_changed both contain the same number of zeros
1080 * (unchanged lines).
1081 * Furthermore, $j is always kept so that $j == $other_len or
1082 * $other_changed[$j] == false.
1083 */
1084 while ($j < $other_len && $other_changed[$j])
1085 $j++;
1086
1087 while ($i < $len && ! $changed[$i]) {
1088 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1089 $i++; $j++;
1090 while ($j < $other_len && $other_changed[$j])
1091 $j++;
1092 }
1093
1094 if ($i == $len)
1095 break;
1096
1097 $start = $i;
1098
1099 // Find the end of this run of changes.
1100 while (++$i < $len && $changed[$i])
1101 continue;
1102
1103 do {
1104 /*
1105 * Record the length of this run of changes, so that
1106 * we can later determine whether the run has grown.
1107 */
1108 $runlength = $i - $start;
1109
1110 /*
1111 * Move the changed region back, so long as the
1112 * previous unchanged line matches the last changed one.
1113 * This merges with previous changed regions.
1114 */
1115 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1116 $changed[--$start] = 1;
1117 $changed[--$i] = false;
1118 while ($start > 0 && $changed[$start - 1])
1119 $start--;
1120 USE_ASSERTS && assert('$j > 0');
1121 while ($other_changed[--$j])
1122 continue;
1123 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1124 }
1125
1126 /*
1127 * Set CORRESPONDING to the end of the changed run, at the last
1128 * point where it corresponds to a changed run in the other file.
1129 * CORRESPONDING == LEN means no such point has been found.
1130 */
1131 $corresponding = $j < $other_len ? $i : $len;
1132
1133 /*
1134 * Move the changed region forward, so long as the
1135 * first changed line matches the following unchanged one.
1136 * This merges with following changed regions.
1137 * Do this second, so that if there are no merges,
1138 * the changed region is moved forward as far as possible.
1139 */
1140 while ($i < $len && $lines[$start] == $lines[$i]) {
1141 $changed[$start++] = false;
1142 $changed[$i++] = 1;
1143 while ($i < $len && $changed[$i])
1144 $i++;
1145
1146 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1147 $j++;
1148 if ($j < $other_len && $other_changed[$j]) {
1149 $corresponding = $i;
1150 while ($j < $other_len && $other_changed[$j])
1151 $j++;
1152 }
1153 }
1154 } while ($runlength != $i - $start);
1155
1156 /*
1157 * If possible, move the fully-merged run of changes
1158 * back to a corresponding run in the other file.
1159 */
1160 while ($corresponding < $i) {
1161 $changed[--$start] = 1;
1162 $changed[--$i] = 0;
1163 USE_ASSERTS && assert('$j > 0');
1164 while ($other_changed[--$j])
1165 continue;
1166 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1167 }
1168 }
1169 wfProfileOut( $fname );
1170 }
1171 }
1172
1173 /**
1174 * Class representing a 'diff' between two sequences of strings.
1175 * @todo document
1176 * @private
1177 * @package MediaWiki
1178 * @subpackage DifferenceEngine
1179 */
1180 class Diff
1181 {
1182 var $edits;
1183
1184 /**
1185 * Constructor.
1186 * Computes diff between sequences of strings.
1187 *
1188 * @param $from_lines array An array of strings.
1189 * (Typically these are lines from a file.)
1190 * @param $to_lines array An array of strings.
1191 */
1192 function Diff($from_lines, $to_lines) {
1193 $eng = new _DiffEngine;
1194 $this->edits = $eng->diff($from_lines, $to_lines);
1195 //$this->_check($from_lines, $to_lines);
1196 }
1197
1198 /**
1199 * Compute reversed Diff.
1200 *
1201 * SYNOPSIS:
1202 *
1203 * $diff = new Diff($lines1, $lines2);
1204 * $rev = $diff->reverse();
1205 * @return object A Diff object representing the inverse of the
1206 * original diff.
1207 */
1208 function reverse () {
1209 $rev = $this;
1210 $rev->edits = array();
1211 foreach ($this->edits as $edit) {
1212 $rev->edits[] = $edit->reverse();
1213 }
1214 return $rev;
1215 }
1216
1217 /**
1218 * Check for empty diff.
1219 *
1220 * @return bool True iff two sequences were identical.
1221 */
1222 function isEmpty () {
1223 foreach ($this->edits as $edit) {
1224 if ($edit->type != 'copy')
1225 return false;
1226 }
1227 return true;
1228 }
1229
1230 /**
1231 * Compute the length of the Longest Common Subsequence (LCS).
1232 *
1233 * This is mostly for diagnostic purposed.
1234 *
1235 * @return int The length of the LCS.
1236 */
1237 function lcs () {
1238 $lcs = 0;
1239 foreach ($this->edits as $edit) {
1240 if ($edit->type == 'copy')
1241 $lcs += sizeof($edit->orig);
1242 }
1243 return $lcs;
1244 }
1245
1246 /**
1247 * Get the original set of lines.
1248 *
1249 * This reconstructs the $from_lines parameter passed to the
1250 * constructor.
1251 *
1252 * @return array The original sequence of strings.
1253 */
1254 function orig() {
1255 $lines = array();
1256
1257 foreach ($this->edits as $edit) {
1258 if ($edit->orig)
1259 array_splice($lines, sizeof($lines), 0, $edit->orig);
1260 }
1261 return $lines;
1262 }
1263
1264 /**
1265 * Get the closing set of lines.
1266 *
1267 * This reconstructs the $to_lines parameter passed to the
1268 * constructor.
1269 *
1270 * @return array The sequence of strings.
1271 */
1272 function closing() {
1273 $lines = array();
1274
1275 foreach ($this->edits as $edit) {
1276 if ($edit->closing)
1277 array_splice($lines, sizeof($lines), 0, $edit->closing);
1278 }
1279 return $lines;
1280 }
1281
1282 /**
1283 * Check a Diff for validity.
1284 *
1285 * This is here only for debugging purposes.
1286 */
1287 function _check ($from_lines, $to_lines) {
1288 $fname = 'Diff::_check';
1289 wfProfileIn( $fname );
1290 if (serialize($from_lines) != serialize($this->orig()))
1291 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
1292 if (serialize($to_lines) != serialize($this->closing()))
1293 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
1294
1295 $rev = $this->reverse();
1296 if (serialize($to_lines) != serialize($rev->orig()))
1297 trigger_error("Reversed original doesn't match", E_USER_ERROR);
1298 if (serialize($from_lines) != serialize($rev->closing()))
1299 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
1300
1301
1302 $prevtype = 'none';
1303 foreach ($this->edits as $edit) {
1304 if ( $prevtype == $edit->type )
1305 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
1306 $prevtype = $edit->type;
1307 }
1308
1309 $lcs = $this->lcs();
1310 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
1311 wfProfileOut( $fname );
1312 }
1313 }
1314
1315 /**
1316 * FIXME: bad name.
1317 * @todo document
1318 * @private
1319 * @package MediaWiki
1320 * @subpackage DifferenceEngine
1321 */
1322 class MappedDiff extends Diff
1323 {
1324 /**
1325 * Constructor.
1326 *
1327 * Computes diff between sequences of strings.
1328 *
1329 * This can be used to compute things like
1330 * case-insensitve diffs, or diffs which ignore
1331 * changes in white-space.
1332 *
1333 * @param $from_lines array An array of strings.
1334 * (Typically these are lines from a file.)
1335 *
1336 * @param $to_lines array An array of strings.
1337 *
1338 * @param $mapped_from_lines array This array should
1339 * have the same size number of elements as $from_lines.
1340 * The elements in $mapped_from_lines and
1341 * $mapped_to_lines are what is actually compared
1342 * when computing the diff.
1343 *
1344 * @param $mapped_to_lines array This array should
1345 * have the same number of elements as $to_lines.
1346 */
1347 function MappedDiff($from_lines, $to_lines,
1348 $mapped_from_lines, $mapped_to_lines) {
1349 $fname = 'MappedDiff::MappedDiff';
1350 wfProfileIn( $fname );
1351
1352 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1353 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1354
1355 $this->Diff($mapped_from_lines, $mapped_to_lines);
1356
1357 $xi = $yi = 0;
1358 for ($i = 0; $i < sizeof($this->edits); $i++) {
1359 $orig = &$this->edits[$i]->orig;
1360 if (is_array($orig)) {
1361 $orig = array_slice($from_lines, $xi, sizeof($orig));
1362 $xi += sizeof($orig);
1363 }
1364
1365 $closing = &$this->edits[$i]->closing;
1366 if (is_array($closing)) {
1367 $closing = array_slice($to_lines, $yi, sizeof($closing));
1368 $yi += sizeof($closing);
1369 }
1370 }
1371 wfProfileOut( $fname );
1372 }
1373 }
1374
1375 /**
1376 * A class to format Diffs
1377 *
1378 * This class formats the diff in classic diff format.
1379 * It is intended that this class be customized via inheritance,
1380 * to obtain fancier outputs.
1381 * @todo document
1382 * @private
1383 * @package MediaWiki
1384 * @subpackage DifferenceEngine
1385 */
1386 class DiffFormatter
1387 {
1388 /**
1389 * Number of leading context "lines" to preserve.
1390 *
1391 * This should be left at zero for this class, but subclasses
1392 * may want to set this to other values.
1393 */
1394 var $leading_context_lines = 0;
1395
1396 /**
1397 * Number of trailing context "lines" to preserve.
1398 *
1399 * This should be left at zero for this class, but subclasses
1400 * may want to set this to other values.
1401 */
1402 var $trailing_context_lines = 0;
1403
1404 /**
1405 * Format a diff.
1406 *
1407 * @param $diff object A Diff object.
1408 * @return string The formatted output.
1409 */
1410 function format($diff) {
1411 $fname = 'DiffFormatter::format';
1412 wfProfileIn( $fname );
1413
1414 $xi = $yi = 1;
1415 $block = false;
1416 $context = array();
1417
1418 $nlead = $this->leading_context_lines;
1419 $ntrail = $this->trailing_context_lines;
1420
1421 $this->_start_diff();
1422
1423 foreach ($diff->edits as $edit) {
1424 if ($edit->type == 'copy') {
1425 if (is_array($block)) {
1426 if (sizeof($edit->orig) <= $nlead + $ntrail) {
1427 $block[] = $edit;
1428 }
1429 else{
1430 if ($ntrail) {
1431 $context = array_slice($edit->orig, 0, $ntrail);
1432 $block[] = new _DiffOp_Copy($context);
1433 }
1434 $this->_block($x0, $ntrail + $xi - $x0,
1435 $y0, $ntrail + $yi - $y0,
1436 $block);
1437 $block = false;
1438 }
1439 }
1440 $context = $edit->orig;
1441 }
1442 else {
1443 if (! is_array($block)) {
1444 $context = array_slice($context, sizeof($context) - $nlead);
1445 $x0 = $xi - sizeof($context);
1446 $y0 = $yi - sizeof($context);
1447 $block = array();
1448 if ($context)
1449 $block[] = new _DiffOp_Copy($context);
1450 }
1451 $block[] = $edit;
1452 }
1453
1454 if ($edit->orig)
1455 $xi += sizeof($edit->orig);
1456 if ($edit->closing)
1457 $yi += sizeof($edit->closing);
1458 }
1459
1460 if (is_array($block))
1461 $this->_block($x0, $xi - $x0,
1462 $y0, $yi - $y0,
1463 $block);
1464
1465 $end = $this->_end_diff();
1466 wfProfileOut( $fname );
1467 return $end;
1468 }
1469
1470 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1471 $fname = 'DiffFormatter::_block';
1472 wfProfileIn( $fname );
1473 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1474 foreach ($edits as $edit) {
1475 if ($edit->type == 'copy')
1476 $this->_context($edit->orig);
1477 elseif ($edit->type == 'add')
1478 $this->_added($edit->closing);
1479 elseif ($edit->type == 'delete')
1480 $this->_deleted($edit->orig);
1481 elseif ($edit->type == 'change')
1482 $this->_changed($edit->orig, $edit->closing);
1483 else
1484 trigger_error('Unknown edit type', E_USER_ERROR);
1485 }
1486 $this->_end_block();
1487 wfProfileOut( $fname );
1488 }
1489
1490 function _start_diff() {
1491 ob_start();
1492 }
1493
1494 function _end_diff() {
1495 $val = ob_get_contents();
1496 ob_end_clean();
1497 return $val;
1498 }
1499
1500 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1501 if ($xlen > 1)
1502 $xbeg .= "," . ($xbeg + $xlen - 1);
1503 if ($ylen > 1)
1504 $ybeg .= "," . ($ybeg + $ylen - 1);
1505
1506 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
1507 }
1508
1509 function _start_block($header) {
1510 echo $header;
1511 }
1512
1513 function _end_block() {
1514 }
1515
1516 function _lines($lines, $prefix = ' ') {
1517 foreach ($lines as $line)
1518 echo "$prefix $line\n";
1519 }
1520
1521 function _context($lines) {
1522 $this->_lines($lines);
1523 }
1524
1525 function _added($lines) {
1526 $this->_lines($lines, '>');
1527 }
1528 function _deleted($lines) {
1529 $this->_lines($lines, '<');
1530 }
1531
1532 function _changed($orig, $closing) {
1533 $this->_deleted($orig);
1534 echo "---\n";
1535 $this->_added($closing);
1536 }
1537 }
1538
1539
1540 /**
1541 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1542 *
1543 */
1544
1545 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1546
1547 /**
1548 * @todo document
1549 * @private
1550 * @package MediaWiki
1551 * @subpackage DifferenceEngine
1552 */
1553 class _HWLDF_WordAccumulator {
1554 function _HWLDF_WordAccumulator () {
1555 $this->_lines = array();
1556 $this->_line = '';
1557 $this->_group = '';
1558 $this->_tag = '';
1559 }
1560
1561 function _flushGroup ($new_tag) {
1562 if ($this->_group !== '') {
1563 if ($this->_tag == 'mark')
1564 $this->_line .= '<span class="diffchange">' .
1565 htmlspecialchars ( $this->_group ) . '</span>';
1566 else
1567 $this->_line .= htmlspecialchars ( $this->_group );
1568 }
1569 $this->_group = '';
1570 $this->_tag = $new_tag;
1571 }
1572
1573 function _flushLine ($new_tag) {
1574 $this->_flushGroup($new_tag);
1575 if ($this->_line != '')
1576 array_push ( $this->_lines, $this->_line );
1577 else
1578 # make empty lines visible by inserting an NBSP
1579 array_push ( $this->_lines, NBSP );
1580 $this->_line = '';
1581 }
1582
1583 function addWords ($words, $tag = '') {
1584 if ($tag != $this->_tag)
1585 $this->_flushGroup($tag);
1586
1587 foreach ($words as $word) {
1588 // new-line should only come as first char of word.
1589 if ($word == '')
1590 continue;
1591 if ($word[0] == "\n") {
1592 $this->_flushLine($tag);
1593 $word = substr($word, 1);
1594 }
1595 assert(!strstr($word, "\n"));
1596 $this->_group .= $word;
1597 }
1598 }
1599
1600 function getLines() {
1601 $this->_flushLine('~done');
1602 return $this->_lines;
1603 }
1604 }
1605
1606 /**
1607 * @todo document
1608 * @private
1609 * @package MediaWiki
1610 * @subpackage DifferenceEngine
1611 */
1612 class WordLevelDiff extends MappedDiff
1613 {
1614 const MAX_LINE_LENGTH = 10000;
1615
1616 function WordLevelDiff ($orig_lines, $closing_lines) {
1617 $fname = 'WordLevelDiff::WordLevelDiff';
1618 wfProfileIn( $fname );
1619
1620 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1621 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1622
1623 $this->MappedDiff($orig_words, $closing_words,
1624 $orig_stripped, $closing_stripped);
1625 wfProfileOut( $fname );
1626 }
1627
1628 function _split($lines) {
1629 $fname = 'WordLevelDiff::_split';
1630 wfProfileIn( $fname );
1631
1632 $words = array();
1633 $stripped = array();
1634 $first = true;
1635 foreach ( $lines as $line ) {
1636 # If the line is too long, just pretend the entire line is one big word
1637 # This prevents resource exhaustion problems
1638 if ( $first ) {
1639 $first = false;
1640 } else {
1641 $words[] = "\n";
1642 $stripped[] = "\n";
1643 }
1644 if ( strlen( $line ) > self::MAX_LINE_LENGTH ) {
1645 $words[] = $line;
1646 $stripped[] = $line;
1647 } else {
1648 $m = array();
1649 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1650 $line, $m))
1651 {
1652 $words = array_merge( $words, $m[0] );
1653 $stripped = array_merge( $stripped, $m[1] );
1654 }
1655 }
1656 }
1657 wfProfileOut( $fname );
1658 return array($words, $stripped);
1659 }
1660
1661 function orig () {
1662 $fname = 'WordLevelDiff::orig';
1663 wfProfileIn( $fname );
1664 $orig = new _HWLDF_WordAccumulator;
1665
1666 foreach ($this->edits as $edit) {
1667 if ($edit->type == 'copy')
1668 $orig->addWords($edit->orig);
1669 elseif ($edit->orig)
1670 $orig->addWords($edit->orig, 'mark');
1671 }
1672 $lines = $orig->getLines();
1673 wfProfileOut( $fname );
1674 return $lines;
1675 }
1676
1677 function closing () {
1678 $fname = 'WordLevelDiff::closing';
1679 wfProfileIn( $fname );
1680 $closing = new _HWLDF_WordAccumulator;
1681
1682 foreach ($this->edits as $edit) {
1683 if ($edit->type == 'copy')
1684 $closing->addWords($edit->closing);
1685 elseif ($edit->closing)
1686 $closing->addWords($edit->closing, 'mark');
1687 }
1688 $lines = $closing->getLines();
1689 wfProfileOut( $fname );
1690 return $lines;
1691 }
1692 }
1693
1694 /**
1695 * Wikipedia Table style diff formatter.
1696 * @todo document
1697 * @private
1698 * @package MediaWiki
1699 * @subpackage DifferenceEngine
1700 */
1701 class TableDiffFormatter extends DiffFormatter
1702 {
1703 function TableDiffFormatter() {
1704 $this->leading_context_lines = 2;
1705 $this->trailing_context_lines = 2;
1706 }
1707
1708 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1709 $r = '<tr><td colspan="2" align="left"><strong><!--LINE '.$xbeg."--></strong></td>\n" .
1710 '<td colspan="2" align="left"><strong><!--LINE '.$ybeg."--></strong></td></tr>\n";
1711 return $r;
1712 }
1713
1714 function _start_block( $header ) {
1715 echo $header;
1716 }
1717
1718 function _end_block() {
1719 }
1720
1721 function _lines( $lines, $prefix=' ', $color='white' ) {
1722 }
1723
1724 # HTML-escape parameter before calling this
1725 function addedLine( $line ) {
1726 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1727 }
1728
1729 # HTML-escape parameter before calling this
1730 function deletedLine( $line ) {
1731 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1732 }
1733
1734 # HTML-escape parameter before calling this
1735 function contextLine( $line ) {
1736 return "<td> </td><td class='diff-context'>{$line}</td>";
1737 }
1738
1739 function emptyLine() {
1740 return '<td colspan="2">&nbsp;</td>';
1741 }
1742
1743 function _added( $lines ) {
1744 foreach ($lines as $line) {
1745 echo '<tr>' . $this->emptyLine() .
1746 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1747 }
1748 }
1749
1750 function _deleted($lines) {
1751 foreach ($lines as $line) {
1752 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1753 $this->emptyLine() . "</tr>\n";
1754 }
1755 }
1756
1757 function _context( $lines ) {
1758 foreach ($lines as $line) {
1759 echo '<tr>' .
1760 $this->contextLine( htmlspecialchars ( $line ) ) .
1761 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1762 }
1763 }
1764
1765 function _changed( $orig, $closing ) {
1766 $fname = 'TableDiffFormatter::_changed';
1767 wfProfileIn( $fname );
1768
1769 $diff = new WordLevelDiff( $orig, $closing );
1770 $del = $diff->orig();
1771 $add = $diff->closing();
1772
1773 # Notice that WordLevelDiff returns HTML-escaped output.
1774 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1775
1776 while ( $line = array_shift( $del ) ) {
1777 $aline = array_shift( $add );
1778 echo '<tr>' . $this->deletedLine( $line ) .
1779 $this->addedLine( $aline ) . "</tr>\n";
1780 }
1781 foreach ($add as $line) { # If any leftovers
1782 echo '<tr>' . $this->emptyLine() .
1783 $this->addedLine( $line ) . "</tr>\n";
1784 }
1785 wfProfileOut( $fname );
1786 }
1787 }
1788
1789 ?>