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