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