Use Doxygen @addtogroup instead of phpdoc @package && @subpackage
[lhc/web/wiklou.git] / includes / DifferenceEngine.php
1 <?php
2 /**
3 * See diff.doc
4 * @addtogroup DifferenceEngine
5 */
6
7 /**
8 * @todo document
9 * @public
10 * @addtogroup DifferenceEngine
11 */
12 class DifferenceEngine {
13 /**#@+
14 * @private
15 */
16 var $mOldid, $mNewid, $mTitle;
17 var $mOldtitle, $mNewtitle, $mPagetitle;
18 var $mOldtext, $mNewtext;
19 var $mOldPage, $mNewPage;
20 var $mRcidMarkPatrolled;
21 var $mOldRev, $mNewRev;
22 var $mRevisionsLoaded = false; // Have the revisions been loaded
23 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
24 /**#@-*/
25
26 /**
27 * Constructor
28 * @param $titleObj Title object that the diff is associated with
29 * @param $old Integer: old ID we want to show and diff with.
30 * @param $new String: either 'prev' or 'next'.
31 * @param $rcid Integer: ??? FIXME (default 0)
32 */
33 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
34 $this->mTitle = $titleObj;
35 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
36
37 if ( 'prev' === $new ) {
38 # Show diff between revision $old and the previous one.
39 # Get previous one from DB.
40 #
41 $this->mNewid = intval($old);
42
43 $this->mOldid = $this->mTitle->getPreviousRevisionID( $this->mNewid );
44
45 } elseif ( 'next' === $new ) {
46 # Show diff between revision $old and the previous one.
47 # Get previous one from DB.
48 #
49 $this->mOldid = intval($old);
50 $this->mNewid = $this->mTitle->getNextRevisionID( $this->mOldid );
51 if ( false === $this->mNewid ) {
52 # if no result, NewId points to the newest old revision. The only newer
53 # revision is cur, which is "0".
54 $this->mNewid = 0;
55 }
56
57 } else {
58 $this->mOldid = intval($old);
59 $this->mNewid = intval($new);
60 }
61 $this->mRcidMarkPatrolled = intval($rcid); # force it to be an integer
62 }
63
64 function showDiffPage( $diffOnly = false ) {
65 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
66 $fname = 'DifferenceEngine::showDiffPage';
67 wfProfileIn( $fname );
68
69 # If external diffs are enabled both globally and for the user,
70 # we'll use the application/x-external-editor interface to call
71 # an external diff tool like kompare, kdiff3, etc.
72 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
73 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
74 $wgOut->disable();
75 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
76 $url1=$this->mTitle->getFullURL("action=raw&oldid=".$this->mOldid);
77 $url2=$this->mTitle->getFullURL("action=raw&oldid=".$this->mNewid);
78 $special=$wgLang->getNsText(NS_SPECIAL);
79 $control=<<<CONTROL
80 [Process]
81 Type=Diff text
82 Engine=MediaWiki
83 Script={$wgServer}{$wgScript}
84 Special namespace={$special}
85
86 [File]
87 Extension=wiki
88 URL=$url1
89
90 [File 2]
91 Extension=wiki
92 URL=$url2
93 CONTROL;
94 echo($control);
95 return;
96 }
97
98 $wgOut->setArticleFlag( false );
99 if ( ! $this->loadRevisionData() ) {
100 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
101 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
102 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
103 $wgOut->addWikitext( $mtext );
104 wfProfileOut( $fname );
105 return;
106 }
107
108 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
109
110 if ( $this->mNewRev->isCurrent() ) {
111 $wgOut->setArticleFlag( true );
112 }
113
114 # mOldid is false if the difference engine is called with a "vague" query for
115 # a diff between a version V and its previous version V' AND the version V
116 # is the first version of that article. In that case, V' does not exist.
117 if ( $this->mOldid === false ) {
118 $this->showFirstRevision();
119 $this->renderNewRevision(); // should we respect $diffOnly here or not?
120 wfProfileOut( $fname );
121 return;
122 }
123
124 $wgOut->suppressQuickbar();
125
126 $oldTitle = $this->mOldPage->getPrefixedText();
127 $newTitle = $this->mNewPage->getPrefixedText();
128 if( $oldTitle == $newTitle ) {
129 $wgOut->setPageTitle( $newTitle );
130 } else {
131 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
132 }
133 $wgOut->setSubtitle( wfMsg( 'difference' ) );
134 $wgOut->setRobotpolicy( 'noindex,nofollow' );
135
136 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
137 $wgOut->loginToUse();
138 $wgOut->output();
139 wfProfileOut( $fname );
140 exit;
141 }
142
143 $sk = $wgUser->getSkin();
144
145 if ( $this->mNewRev->isCurrent() && $wgUser->isAllowed('rollback') ) {
146 $rollback = '&nbsp;&nbsp;&nbsp;' . $sk->generateRollback( $this->mNewRev );
147 } else {
148 $rollback = '';
149 }
150 if( $wgUseRCPatrol && $this->mRcidMarkPatrolled != 0 && $wgUser->isAllowed( 'patrol' ) ) {
151 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
152 } else {
153 $patrol = '';
154 }
155
156 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousdiff' ),
157 'diff=prev&oldid='.$this->mOldid, '', '', 'id="differences-prevlink"' );
158 if ( $this->mNewRev->isCurrent() ) {
159 $nextlink = '&nbsp;';
160 } else {
161 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ),
162 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
163 }
164
165 $oldminor = '';
166 $newminor = '';
167
168 if ($this->mOldRev->mMinorEdit == 1) {
169 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
170 wfMsg( 'minoreditletter') ) . ' ';
171 }
172
173 if ($this->mNewRev->mMinorEdit == 1) {
174 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
175 wfMsg( 'minoreditletter') ) . ' ';
176 }
177
178 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />" .
179 $sk->revUserTools( $this->mOldRev ) . "<br />" .
180 $oldminor . $sk->revComment( $this->mOldRev, !$diffOnly ) . "<br />" .
181 $prevlink;
182 $newHeader = "<strong>{$this->mNewtitle}</strong><br />" .
183 $sk->revUserTools( $this->mNewRev ) . " $rollback<br />" .
184 $newminor . $sk->revComment( $this->mNewRev, !$diffOnly ) . "<br />" .
185 $nextlink . $patrol;
186
187 $this->showDiff( $oldHeader, $newHeader );
188
189 if ( !$diffOnly )
190 $this->renderNewRevision();
191
192 wfProfileOut( $fname );
193 }
194
195 /**
196 * Show the new revision of the page.
197 */
198 function renderNewRevision() {
199 global $wgOut;
200 $fname = 'DifferenceEngine::renderNewRevision';
201 wfProfileIn( $fname );
202
203 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
204
205 if( !$this->mNewRev->isCurrent() ) {
206 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
207 }
208
209 $this->loadNewText();
210 if( is_object( $this->mNewRev ) ) {
211 $wgOut->setRevisionId( $this->mNewRev->getId() );
212 }
213
214 $wgOut->addWikiTextTidy( $this->mNewtext );
215
216 if( !$this->mNewRev->isCurrent() ) {
217 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
218 }
219
220 wfProfileOut( $fname );
221 }
222
223 /**
224 * Show the first revision of an article. Uses normal diff headers in
225 * contrast to normal "old revision" display style.
226 */
227 function showFirstRevision() {
228 global $wgOut, $wgUser;
229
230 $fname = 'DifferenceEngine::showFirstRevision';
231 wfProfileIn( $fname );
232
233 # Get article text from the DB
234 #
235 if ( ! $this->loadNewText() ) {
236 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
237 "{$this->mNewid})";
238 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
239 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
240 $wgOut->addWikitext( $mtext );
241 wfProfileOut( $fname );
242 return;
243 }
244 if ( $this->mNewRev->isCurrent() ) {
245 $wgOut->setArticleFlag( true );
246 }
247
248 # Check if user is allowed to look at this page. If not, bail out.
249 #
250 if ( !( $this->mTitle->userCanRead() ) ) {
251 $wgOut->loginToUse();
252 $wgOut->output();
253 wfProfileOut( $fname );
254 exit;
255 }
256
257 # Prepare the header box
258 #
259 $sk = $wgUser->getSkin();
260
261 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
262 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
263 $sk->revUserTools( $this->mNewRev ) . "<br />" .
264 $sk->revComment( $this->mNewRev ) . "<br />" .
265 $nextlink . "</div>\n";
266
267 $wgOut->addHTML( $header );
268
269 $wgOut->setSubtitle( wfMsg( 'difference' ) );
270 $wgOut->setRobotpolicy( 'noindex,nofollow' );
271
272 wfProfileOut( $fname );
273 }
274
275 /**
276 * Get the diff text, send it to $wgOut
277 * Returns false if the diff could not be generated, otherwise returns true
278 */
279 function showDiff( $otitle, $ntitle ) {
280 global $wgOut;
281 $diff = $this->getDiff( $otitle, $ntitle );
282 if ( $diff === false ) {
283 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
284 return false;
285 } else {
286 $wgOut->addHTML( $diff );
287 return true;
288 }
289 }
290
291 /**
292 * Get diff table, including header
293 * Note that the interface has changed, it's no longer static.
294 * Returns false on error
295 */
296 function getDiff( $otitle, $ntitle ) {
297 $body = $this->getDiffBody();
298 if ( $body === false ) {
299 return false;
300 } else {
301 $multi = $this->getMultiNotice();
302 return $this->addHeader( $body, $otitle, $ntitle, $multi );
303 }
304 }
305
306 /**
307 * Get the diff table body, without header
308 * Results are cached
309 * Returns false on error
310 */
311 function getDiffBody() {
312 global $wgMemc;
313 $fname = 'DifferenceEngine::getDiffBody';
314 wfProfileIn( $fname );
315
316 // Cacheable?
317 $key = false;
318 if ( $this->mOldid && $this->mNewid ) {
319 // Try cache
320 $key = wfMemcKey( 'diff', 'oldid', $this->mOldid, 'newid', $this->mNewid );
321 $difftext = $wgMemc->get( $key );
322 if ( $difftext ) {
323 wfIncrStats( 'diff_cache_hit' );
324 $difftext = $this->localiseLineNumbers( $difftext );
325 $difftext .= "\n<!-- diff cache key $key -->\n";
326 wfProfileOut( $fname );
327 return $difftext;
328 }
329 }
330
331 if ( !$this->loadText() ) {
332 wfProfileOut( $fname );
333 return false;
334 }
335
336 $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext );
337
338 // Save to cache for 7 days
339 if ( $key !== false && $difftext !== false ) {
340 wfIncrStats( 'diff_cache_miss' );
341 $wgMemc->set( $key, $difftext, 7*86400 );
342 } else {
343 wfIncrStats( 'diff_uncacheable' );
344 }
345 // Replace line numbers with the text in the user's language
346 if ( $difftext !== false ) {
347 $difftext = $this->localiseLineNumbers( $difftext );
348 }
349 wfProfileOut( $fname );
350 return $difftext;
351 }
352
353 /**
354 * Generate a diff, no caching
355 * $otext and $ntext must be already segmented
356 */
357 function generateDiffBody( $otext, $ntext ) {
358 global $wgExternalDiffEngine, $wgContLang;
359 $fname = 'DifferenceEngine::generateDiffBody';
360
361 $otext = str_replace( "\r\n", "\n", $otext );
362 $ntext = str_replace( "\r\n", "\n", $ntext );
363
364 if ( $wgExternalDiffEngine == 'wikidiff' ) {
365 # For historical reasons, external diff engine expects
366 # input text to be HTML-escaped already
367 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
368 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
369 if( !function_exists( 'wikidiff_do_diff' ) ) {
370 dl('php_wikidiff.so');
371 }
372 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
373 }
374
375 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
376 # Better external diff engine, the 2 may some day be dropped
377 # This one does the escaping and segmenting itself
378 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
379 wfProfileIn( "$fname-dl" );
380 @dl('php_wikidiff2.so');
381 wfProfileOut( "$fname-dl" );
382 }
383 if ( function_exists( 'wikidiff2_do_diff' ) ) {
384 wfProfileIn( 'wikidiff2_do_diff' );
385 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
386 wfProfileOut( 'wikidiff2_do_diff' );
387 return $text;
388 }
389 }
390 if ( $wgExternalDiffEngine !== false ) {
391 # Diff via the shell
392 global $wgTmpDirectory;
393 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
394 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
395
396 $tempFile1 = fopen( $tempName1, "w" );
397 if ( !$tempFile1 ) {
398 wfProfileOut( $fname );
399 return false;
400 }
401 $tempFile2 = fopen( $tempName2, "w" );
402 if ( !$tempFile2 ) {
403 wfProfileOut( $fname );
404 return false;
405 }
406 fwrite( $tempFile1, $otext );
407 fwrite( $tempFile2, $ntext );
408 fclose( $tempFile1 );
409 fclose( $tempFile2 );
410 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
411 wfProfileIn( "$fname-shellexec" );
412 $difftext = wfShellExec( $cmd );
413 wfProfileOut( "$fname-shellexec" );
414 unlink( $tempName1 );
415 unlink( $tempName2 );
416 return $difftext;
417 }
418
419 # Native PHP diff
420 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
421 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
422 $diffs = new Diff( $ota, $nta );
423 $formatter = new TableDiffFormatter();
424 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
425 }
426
427
428 /**
429 * Replace line numbers with the text in the user's language
430 */
431 function localiseLineNumbers( $text ) {
432 return preg_replace_callback( '/<!--LINE (\d+)-->/',
433 array( &$this, 'localiseLineNumbersCb' ), $text );
434 }
435
436 function localiseLineNumbersCb( $matches ) {
437 global $wgLang;
438 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
439 }
440
441
442 /**
443 * If there are revisions between the ones being compared, return a note saying so.
444 */
445 function getMultiNotice() {
446 if ( !is_object($this->mOldRev) || !is_object($this->mNewRev) )
447 return '';
448
449 if( !$this->mOldPage->equals( $this->mNewPage ) ) {
450 // Comparing two different pages? Count would be meaningless.
451 return '';
452 }
453
454 $oldid = $this->mOldRev->getId();
455 $newid = $this->mNewRev->getId();
456 if ( $oldid > $newid ) {
457 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
458 }
459
460 $n = $this->mTitle->countRevisionsBetween( $oldid, $newid );
461 if ( !$n )
462 return '';
463
464 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
465 }
466
467
468 /**
469 * Add the header to a diff body
470 */
471 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
472 $header = "
473 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
474 <tr>
475 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
476 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
477 </tr>
478 ";
479
480 if ( $multi != '' )
481 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
482
483 return $header . $diff . "</table>";
484 }
485
486 /**
487 * Use specified text instead of loading from the database
488 */
489 function setText( $oldText, $newText ) {
490 $this->mOldtext = $oldText;
491 $this->mNewtext = $newText;
492 $this->mTextLoaded = 2;
493 }
494
495 /**
496 * Load revision metadata for the specified articles. If newid is 0, then compare
497 * the old article in oldid to the current article; if oldid is 0, then
498 * compare the current article to the immediately previous one (ignoring the
499 * value of newid).
500 *
501 * If oldid is false, leave the corresponding revision object set
502 * to false. This is impossible via ordinary user input, and is provided for
503 * API convenience.
504 */
505 function loadRevisionData() {
506 global $wgLang;
507 if ( $this->mRevisionsLoaded ) {
508 return true;
509 } else {
510 // Whether it succeeds or fails, we don't want to try again
511 $this->mRevisionsLoaded = true;
512 }
513
514 // Load the new revision object
515 if( $this->mNewid ) {
516 $this->mNewRev = Revision::newFromId( $this->mNewid );
517 } else {
518 $this->mNewRev = Revision::newFromTitle( $this->mTitle );
519 }
520
521 if( is_null( $this->mNewRev ) ) {
522 return false;
523 }
524
525 // Set assorted variables
526 $timestamp = $wgLang->timeanddate( $this->mNewRev->getTimestamp(), true );
527 $this->mNewPage = $this->mNewRev->getTitle();
528 if( $this->mNewRev->isCurrent() ) {
529 $newLink = $this->mNewPage->escapeLocalUrl();
530 $this->mPagetitle = htmlspecialchars( wfMsg( 'currentrev' ) );
531 $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit' );
532 $newUndo = $this->mNewPage->escapeLocalUrl( 'action=edit&undo=' . $this->mNewid );
533
534 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
535 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)"
536 . " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
537
538 } else {
539 $newLink = $this->mNewPage->escapeLocalUrl( 'oldid=' . $this->mNewid );
540 $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid );
541 $newUndo = $this->mNewPage->escapeLocalUrl( 'action=edit&undo=' . $this->mNewid );
542 $this->mPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
543
544 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>"
545 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)"
546 . " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
547 }
548
549 // Load the old revision object
550 $this->mOldRev = false;
551 if( $this->mOldid ) {
552 $this->mOldRev = Revision::newFromId( $this->mOldid );
553 } elseif ( $this->mOldid === 0 ) {
554 $rev = $this->mNewRev->getPrevious();
555 if( $rev ) {
556 $this->mOldid = $rev->getId();
557 $this->mOldRev = $rev;
558 } else {
559 // No previous revision; mark to show as first-version only.
560 $this->mOldid = false;
561 $this->mOldRev = false;
562 }
563 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
564
565 if( is_null( $this->mOldRev ) ) {
566 return false;
567 }
568
569 if ( $this->mOldRev ) {
570 $this->mOldPage = $this->mOldRev->getTitle();
571
572 $t = $wgLang->timeanddate( $this->mOldRev->getTimestamp(), true );
573 $oldLink = $this->mOldPage->escapeLocalUrl( 'oldid=' . $this->mOldid );
574 $oldEdit = $this->mOldPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid );
575 $this->mOldtitle = "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
576 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
577 }
578
579 return true;
580 }
581
582 /**
583 * Load the text of the revisions, as well as revision data.
584 */
585 function loadText() {
586 if ( $this->mTextLoaded == 2 ) {
587 return true;
588 } else {
589 // Whether it succeeds or fails, we don't want to try again
590 $this->mTextLoaded = 2;
591 }
592
593 if ( !$this->loadRevisionData() ) {
594 return false;
595 }
596 if ( $this->mOldRev ) {
597 // FIXME: permission tests
598 $this->mOldtext = $this->mOldRev->getText();
599 if ( $this->mOldtext === false ) {
600 return false;
601 }
602 }
603 if ( $this->mNewRev ) {
604 $this->mNewtext = $this->mNewRev->getText();
605 if ( $this->mNewtext === false ) {
606 return false;
607 }
608 }
609 return true;
610 }
611
612 /**
613 * Load the text of the new revision, not the old one
614 */
615 function loadNewText() {
616 if ( $this->mTextLoaded >= 1 ) {
617 return true;
618 } else {
619 $this->mTextLoaded = 1;
620 }
621 if ( !$this->loadRevisionData() ) {
622 return false;
623 }
624 $this->mNewtext = $this->mNewRev->getText();
625 return true;
626 }
627
628
629 }
630
631 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
632 //
633 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
634 // You may copy this code freely under the conditions of the GPL.
635 //
636
637 define('USE_ASSERTS', function_exists('assert'));
638
639 /**
640 * @todo document
641 * @private
642 * @addtogroup DifferenceEngine
643 */
644 class _DiffOp {
645 var $type;
646 var $orig;
647 var $closing;
648
649 function reverse() {
650 trigger_error('pure virtual', E_USER_ERROR);
651 }
652
653 function norig() {
654 return $this->orig ? sizeof($this->orig) : 0;
655 }
656
657 function nclosing() {
658 return $this->closing ? sizeof($this->closing) : 0;
659 }
660 }
661
662 /**
663 * @todo document
664 * @private
665 * @addtogroup DifferenceEngine
666 */
667 class _DiffOp_Copy extends _DiffOp {
668 var $type = 'copy';
669
670 function _DiffOp_Copy ($orig, $closing = false) {
671 if (!is_array($closing))
672 $closing = $orig;
673 $this->orig = $orig;
674 $this->closing = $closing;
675 }
676
677 function reverse() {
678 return new _DiffOp_Copy($this->closing, $this->orig);
679 }
680 }
681
682 /**
683 * @todo document
684 * @private
685 * @addtogroup DifferenceEngine
686 */
687 class _DiffOp_Delete extends _DiffOp {
688 var $type = 'delete';
689
690 function _DiffOp_Delete ($lines) {
691 $this->orig = $lines;
692 $this->closing = false;
693 }
694
695 function reverse() {
696 return new _DiffOp_Add($this->orig);
697 }
698 }
699
700 /**
701 * @todo document
702 * @private
703 * @addtogroup DifferenceEngine
704 */
705 class _DiffOp_Add extends _DiffOp {
706 var $type = 'add';
707
708 function _DiffOp_Add ($lines) {
709 $this->closing = $lines;
710 $this->orig = false;
711 }
712
713 function reverse() {
714 return new _DiffOp_Delete($this->closing);
715 }
716 }
717
718 /**
719 * @todo document
720 * @private
721 * @addtogroup DifferenceEngine
722 */
723 class _DiffOp_Change extends _DiffOp {
724 var $type = 'change';
725
726 function _DiffOp_Change ($orig, $closing) {
727 $this->orig = $orig;
728 $this->closing = $closing;
729 }
730
731 function reverse() {
732 return new _DiffOp_Change($this->closing, $this->orig);
733 }
734 }
735
736
737 /**
738 * Class used internally by Diff to actually compute the diffs.
739 *
740 * The algorithm used here is mostly lifted from the perl module
741 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
742 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
743 *
744 * More ideas are taken from:
745 * http://www.ics.uci.edu/~eppstein/161/960229.html
746 *
747 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
748 * diffutils-2.7, which can be found at:
749 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
750 *
751 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
752 * are my own.
753 *
754 * Line length limits for robustness added by Tim Starling, 2005-08-31
755 *
756 * @author Geoffrey T. Dairiki, Tim Starling
757 * @private
758 * @addtogroup 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 * @addtogroup DifferenceEngine
1180 */
1181 class Diff
1182 {
1183 var $edits;
1184
1185 /**
1186 * Constructor.
1187 * Computes diff between sequences of strings.
1188 *
1189 * @param $from_lines array An array of strings.
1190 * (Typically these are lines from a file.)
1191 * @param $to_lines array An array of strings.
1192 */
1193 function Diff($from_lines, $to_lines) {
1194 $eng = new _DiffEngine;
1195 $this->edits = $eng->diff($from_lines, $to_lines);
1196 //$this->_check($from_lines, $to_lines);
1197 }
1198
1199 /**
1200 * Compute reversed Diff.
1201 *
1202 * SYNOPSIS:
1203 *
1204 * $diff = new Diff($lines1, $lines2);
1205 * $rev = $diff->reverse();
1206 * @return object A Diff object representing the inverse of the
1207 * original diff.
1208 */
1209 function reverse () {
1210 $rev = $this;
1211 $rev->edits = array();
1212 foreach ($this->edits as $edit) {
1213 $rev->edits[] = $edit->reverse();
1214 }
1215 return $rev;
1216 }
1217
1218 /**
1219 * Check for empty diff.
1220 *
1221 * @return bool True iff two sequences were identical.
1222 */
1223 function isEmpty () {
1224 foreach ($this->edits as $edit) {
1225 if ($edit->type != 'copy')
1226 return false;
1227 }
1228 return true;
1229 }
1230
1231 /**
1232 * Compute the length of the Longest Common Subsequence (LCS).
1233 *
1234 * This is mostly for diagnostic purposed.
1235 *
1236 * @return int The length of the LCS.
1237 */
1238 function lcs () {
1239 $lcs = 0;
1240 foreach ($this->edits as $edit) {
1241 if ($edit->type == 'copy')
1242 $lcs += sizeof($edit->orig);
1243 }
1244 return $lcs;
1245 }
1246
1247 /**
1248 * Get the original set of lines.
1249 *
1250 * This reconstructs the $from_lines parameter passed to the
1251 * constructor.
1252 *
1253 * @return array The original sequence of strings.
1254 */
1255 function orig() {
1256 $lines = array();
1257
1258 foreach ($this->edits as $edit) {
1259 if ($edit->orig)
1260 array_splice($lines, sizeof($lines), 0, $edit->orig);
1261 }
1262 return $lines;
1263 }
1264
1265 /**
1266 * Get the closing set of lines.
1267 *
1268 * This reconstructs the $to_lines parameter passed to the
1269 * constructor.
1270 *
1271 * @return array The sequence of strings.
1272 */
1273 function closing() {
1274 $lines = array();
1275
1276 foreach ($this->edits as $edit) {
1277 if ($edit->closing)
1278 array_splice($lines, sizeof($lines), 0, $edit->closing);
1279 }
1280 return $lines;
1281 }
1282
1283 /**
1284 * Check a Diff for validity.
1285 *
1286 * This is here only for debugging purposes.
1287 */
1288 function _check ($from_lines, $to_lines) {
1289 $fname = 'Diff::_check';
1290 wfProfileIn( $fname );
1291 if (serialize($from_lines) != serialize($this->orig()))
1292 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
1293 if (serialize($to_lines) != serialize($this->closing()))
1294 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
1295
1296 $rev = $this->reverse();
1297 if (serialize($to_lines) != serialize($rev->orig()))
1298 trigger_error("Reversed original doesn't match", E_USER_ERROR);
1299 if (serialize($from_lines) != serialize($rev->closing()))
1300 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
1301
1302
1303 $prevtype = 'none';
1304 foreach ($this->edits as $edit) {
1305 if ( $prevtype == $edit->type )
1306 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
1307 $prevtype = $edit->type;
1308 }
1309
1310 $lcs = $this->lcs();
1311 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
1312 wfProfileOut( $fname );
1313 }
1314 }
1315
1316 /**
1317 * FIXME: bad name.
1318 * @todo document
1319 * @private
1320 * @addtogroup 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 * @addtogroup DifferenceEngine
1384 */
1385 class DiffFormatter
1386 {
1387 /**
1388 * Number of leading context "lines" to preserve.
1389 *
1390 * This should be left at zero for this class, but subclasses
1391 * may want to set this to other values.
1392 */
1393 var $leading_context_lines = 0;
1394
1395 /**
1396 * Number of trailing context "lines" to preserve.
1397 *
1398 * This should be left at zero for this class, but subclasses
1399 * may want to set this to other values.
1400 */
1401 var $trailing_context_lines = 0;
1402
1403 /**
1404 * Format a diff.
1405 *
1406 * @param $diff object A Diff object.
1407 * @return string The formatted output.
1408 */
1409 function format($diff) {
1410 $fname = 'DiffFormatter::format';
1411 wfProfileIn( $fname );
1412
1413 $xi = $yi = 1;
1414 $block = false;
1415 $context = array();
1416
1417 $nlead = $this->leading_context_lines;
1418 $ntrail = $this->trailing_context_lines;
1419
1420 $this->_start_diff();
1421
1422 foreach ($diff->edits as $edit) {
1423 if ($edit->type == 'copy') {
1424 if (is_array($block)) {
1425 if (sizeof($edit->orig) <= $nlead + $ntrail) {
1426 $block[] = $edit;
1427 }
1428 else{
1429 if ($ntrail) {
1430 $context = array_slice($edit->orig, 0, $ntrail);
1431 $block[] = new _DiffOp_Copy($context);
1432 }
1433 $this->_block($x0, $ntrail + $xi - $x0,
1434 $y0, $ntrail + $yi - $y0,
1435 $block);
1436 $block = false;
1437 }
1438 }
1439 $context = $edit->orig;
1440 }
1441 else {
1442 if (! is_array($block)) {
1443 $context = array_slice($context, sizeof($context) - $nlead);
1444 $x0 = $xi - sizeof($context);
1445 $y0 = $yi - sizeof($context);
1446 $block = array();
1447 if ($context)
1448 $block[] = new _DiffOp_Copy($context);
1449 }
1450 $block[] = $edit;
1451 }
1452
1453 if ($edit->orig)
1454 $xi += sizeof($edit->orig);
1455 if ($edit->closing)
1456 $yi += sizeof($edit->closing);
1457 }
1458
1459 if (is_array($block))
1460 $this->_block($x0, $xi - $x0,
1461 $y0, $yi - $y0,
1462 $block);
1463
1464 $end = $this->_end_diff();
1465 wfProfileOut( $fname );
1466 return $end;
1467 }
1468
1469 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1470 $fname = 'DiffFormatter::_block';
1471 wfProfileIn( $fname );
1472 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1473 foreach ($edits as $edit) {
1474 if ($edit->type == 'copy')
1475 $this->_context($edit->orig);
1476 elseif ($edit->type == 'add')
1477 $this->_added($edit->closing);
1478 elseif ($edit->type == 'delete')
1479 $this->_deleted($edit->orig);
1480 elseif ($edit->type == 'change')
1481 $this->_changed($edit->orig, $edit->closing);
1482 else
1483 trigger_error('Unknown edit type', E_USER_ERROR);
1484 }
1485 $this->_end_block();
1486 wfProfileOut( $fname );
1487 }
1488
1489 function _start_diff() {
1490 ob_start();
1491 }
1492
1493 function _end_diff() {
1494 $val = ob_get_contents();
1495 ob_end_clean();
1496 return $val;
1497 }
1498
1499 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1500 if ($xlen > 1)
1501 $xbeg .= "," . ($xbeg + $xlen - 1);
1502 if ($ylen > 1)
1503 $ybeg .= "," . ($ybeg + $ylen - 1);
1504
1505 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
1506 }
1507
1508 function _start_block($header) {
1509 echo $header;
1510 }
1511
1512 function _end_block() {
1513 }
1514
1515 function _lines($lines, $prefix = ' ') {
1516 foreach ($lines as $line)
1517 echo "$prefix $line\n";
1518 }
1519
1520 function _context($lines) {
1521 $this->_lines($lines);
1522 }
1523
1524 function _added($lines) {
1525 $this->_lines($lines, '>');
1526 }
1527 function _deleted($lines) {
1528 $this->_lines($lines, '<');
1529 }
1530
1531 function _changed($orig, $closing) {
1532 $this->_deleted($orig);
1533 echo "---\n";
1534 $this->_added($closing);
1535 }
1536 }
1537
1538
1539 /**
1540 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1541 *
1542 */
1543
1544 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1545
1546 /**
1547 * @todo document
1548 * @private
1549 * @addtogroup DifferenceEngine
1550 */
1551 class _HWLDF_WordAccumulator {
1552 function _HWLDF_WordAccumulator () {
1553 $this->_lines = array();
1554 $this->_line = '';
1555 $this->_group = '';
1556 $this->_tag = '';
1557 }
1558
1559 function _flushGroup ($new_tag) {
1560 if ($this->_group !== '') {
1561 if ($this->_tag == 'mark')
1562 $this->_line .= '<span class="diffchange">' .
1563 htmlspecialchars ( $this->_group ) . '</span>';
1564 else
1565 $this->_line .= htmlspecialchars ( $this->_group );
1566 }
1567 $this->_group = '';
1568 $this->_tag = $new_tag;
1569 }
1570
1571 function _flushLine ($new_tag) {
1572 $this->_flushGroup($new_tag);
1573 if ($this->_line != '')
1574 array_push ( $this->_lines, $this->_line );
1575 else
1576 # make empty lines visible by inserting an NBSP
1577 array_push ( $this->_lines, NBSP );
1578 $this->_line = '';
1579 }
1580
1581 function addWords ($words, $tag = '') {
1582 if ($tag != $this->_tag)
1583 $this->_flushGroup($tag);
1584
1585 foreach ($words as $word) {
1586 // new-line should only come as first char of word.
1587 if ($word == '')
1588 continue;
1589 if ($word[0] == "\n") {
1590 $this->_flushLine($tag);
1591 $word = substr($word, 1);
1592 }
1593 assert(!strstr($word, "\n"));
1594 $this->_group .= $word;
1595 }
1596 }
1597
1598 function getLines() {
1599 $this->_flushLine('~done');
1600 return $this->_lines;
1601 }
1602 }
1603
1604 /**
1605 * @todo document
1606 * @private
1607 * @addtogroup DifferenceEngine
1608 */
1609 class WordLevelDiff extends MappedDiff
1610 {
1611 const MAX_LINE_LENGTH = 10000;
1612
1613 function WordLevelDiff ($orig_lines, $closing_lines) {
1614 $fname = 'WordLevelDiff::WordLevelDiff';
1615 wfProfileIn( $fname );
1616
1617 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1618 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1619
1620 $this->MappedDiff($orig_words, $closing_words,
1621 $orig_stripped, $closing_stripped);
1622 wfProfileOut( $fname );
1623 }
1624
1625 function _split($lines) {
1626 $fname = 'WordLevelDiff::_split';
1627 wfProfileIn( $fname );
1628
1629 $words = array();
1630 $stripped = array();
1631 $first = true;
1632 foreach ( $lines as $line ) {
1633 # If the line is too long, just pretend the entire line is one big word
1634 # This prevents resource exhaustion problems
1635 if ( $first ) {
1636 $first = false;
1637 } else {
1638 $words[] = "\n";
1639 $stripped[] = "\n";
1640 }
1641 if ( strlen( $line ) > self::MAX_LINE_LENGTH ) {
1642 $words[] = $line;
1643 $stripped[] = $line;
1644 } else {
1645 $m = array();
1646 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1647 $line, $m))
1648 {
1649 $words = array_merge( $words, $m[0] );
1650 $stripped = array_merge( $stripped, $m[1] );
1651 }
1652 }
1653 }
1654 wfProfileOut( $fname );
1655 return array($words, $stripped);
1656 }
1657
1658 function orig () {
1659 $fname = 'WordLevelDiff::orig';
1660 wfProfileIn( $fname );
1661 $orig = new _HWLDF_WordAccumulator;
1662
1663 foreach ($this->edits as $edit) {
1664 if ($edit->type == 'copy')
1665 $orig->addWords($edit->orig);
1666 elseif ($edit->orig)
1667 $orig->addWords($edit->orig, 'mark');
1668 }
1669 $lines = $orig->getLines();
1670 wfProfileOut( $fname );
1671 return $lines;
1672 }
1673
1674 function closing () {
1675 $fname = 'WordLevelDiff::closing';
1676 wfProfileIn( $fname );
1677 $closing = new _HWLDF_WordAccumulator;
1678
1679 foreach ($this->edits as $edit) {
1680 if ($edit->type == 'copy')
1681 $closing->addWords($edit->closing);
1682 elseif ($edit->closing)
1683 $closing->addWords($edit->closing, 'mark');
1684 }
1685 $lines = $closing->getLines();
1686 wfProfileOut( $fname );
1687 return $lines;
1688 }
1689 }
1690
1691 /**
1692 * Wikipedia Table style diff formatter.
1693 * @todo document
1694 * @private
1695 * @addtogroup DifferenceEngine
1696 */
1697 class TableDiffFormatter extends DiffFormatter
1698 {
1699 function TableDiffFormatter() {
1700 $this->leading_context_lines = 2;
1701 $this->trailing_context_lines = 2;
1702 }
1703
1704 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1705 $r = '<tr><td colspan="2" align="left"><strong><!--LINE '.$xbeg."--></strong></td>\n" .
1706 '<td colspan="2" align="left"><strong><!--LINE '.$ybeg."--></strong></td></tr>\n";
1707 return $r;
1708 }
1709
1710 function _start_block( $header ) {
1711 echo $header;
1712 }
1713
1714 function _end_block() {
1715 }
1716
1717 function _lines( $lines, $prefix=' ', $color='white' ) {
1718 }
1719
1720 # HTML-escape parameter before calling this
1721 function addedLine( $line ) {
1722 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1723 }
1724
1725 # HTML-escape parameter before calling this
1726 function deletedLine( $line ) {
1727 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1728 }
1729
1730 # HTML-escape parameter before calling this
1731 function contextLine( $line ) {
1732 return "<td> </td><td class='diff-context'>{$line}</td>";
1733 }
1734
1735 function emptyLine() {
1736 return '<td colspan="2">&nbsp;</td>';
1737 }
1738
1739 function _added( $lines ) {
1740 foreach ($lines as $line) {
1741 echo '<tr>' . $this->emptyLine() .
1742 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1743 }
1744 }
1745
1746 function _deleted($lines) {
1747 foreach ($lines as $line) {
1748 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1749 $this->emptyLine() . "</tr>\n";
1750 }
1751 }
1752
1753 function _context( $lines ) {
1754 foreach ($lines as $line) {
1755 echo '<tr>' .
1756 $this->contextLine( htmlspecialchars ( $line ) ) .
1757 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1758 }
1759 }
1760
1761 function _changed( $orig, $closing ) {
1762 $fname = 'TableDiffFormatter::_changed';
1763 wfProfileIn( $fname );
1764
1765 $diff = new WordLevelDiff( $orig, $closing );
1766 $del = $diff->orig();
1767 $add = $diff->closing();
1768
1769 # Notice that WordLevelDiff returns HTML-escaped output.
1770 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1771
1772 while ( $line = array_shift( $del ) ) {
1773 $aline = array_shift( $add );
1774 echo '<tr>' . $this->deletedLine( $line ) .
1775 $this->addedLine( $aline ) . "</tr>\n";
1776 }
1777 foreach ($add as $line) { # If any leftovers
1778 echo '<tr>' . $this->emptyLine() .
1779 $this->addedLine( $line ) . "</tr>\n";
1780 }
1781 wfProfileOut( $fname );
1782 }
1783 }
1784
1785 ?>