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