PHPDocumentor [http://en.wikipedia.org/wiki/PhpDocumentor] documentation tweaking...
[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->setArticleFlag( false );
100 if ( ! $this->loadRevisionData() ) {
101 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
102 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
103 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
104 $wgOut->addWikitext( $mtext );
105 wfProfileOut( $fname );
106 return;
107 }
108
109 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
110
111 if ( $this->mNewRev->isCurrent() ) {
112 $wgOut->setArticleFlag( true );
113 }
114
115 # mOldid is false if the difference engine is called with a "vague" query for
116 # a diff between a version V and its previous version V' AND the version V
117 # is the first version of that article. In that case, V' does not exist.
118 if ( $this->mOldid === false ) {
119 $this->showFirstRevision();
120 $this->renderNewRevision(); // should we respect $diffOnly here or not?
121 wfProfileOut( $fname );
122 return;
123 }
124
125 $wgOut->suppressQuickbar();
126
127 $oldTitle = $this->mOldPage->getPrefixedText();
128 $newTitle = $this->mNewPage->getPrefixedText();
129 if( $oldTitle == $newTitle ) {
130 $wgOut->setPageTitle( $newTitle );
131 } else {
132 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
133 }
134 $wgOut->setSubtitle( wfMsg( 'difference' ) );
135 $wgOut->setRobotpolicy( 'noindex,nofollow' );
136
137 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
138 $wgOut->loginToUse();
139 $wgOut->output();
140 wfProfileOut( $fname );
141 exit;
142 }
143
144 $sk = $wgUser->getSkin();
145
146 if ( $this->mNewRev->isCurrent() && $wgUser->isAllowed('rollback') ) {
147 $rollback = '&nbsp;&nbsp;&nbsp;' . $sk->generateRollback( $this->mNewRev );
148 } else {
149 $rollback = '';
150 }
151 if( $wgUseRCPatrol && $this->mRcidMarkPatrolled != 0 && $wgUser->isAllowed( 'patrol' ) ) {
152 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
153 } else {
154 $patrol = '';
155 }
156
157 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousdiff' ),
158 'diff=prev&oldid='.$this->mOldid, '', '', 'id="differences-prevlink"' );
159 if ( $this->mNewRev->isCurrent() ) {
160 $nextlink = '&nbsp;';
161 } else {
162 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ),
163 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
164 }
165
166 $oldminor = '';
167 $newminor = '';
168
169 if ($this->mOldRev->mMinorEdit == 1) {
170 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
171 wfMsg( 'minoreditletter') ) . ' ';
172 }
173
174 if ($this->mNewRev->mMinorEdit == 1) {
175 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
176 wfMsg( 'minoreditletter') ) . ' ';
177 }
178
179 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />" .
180 $sk->revUserTools( $this->mOldRev ) . "<br />" .
181 $oldminor . $sk->revComment( $this->mOldRev, !$diffOnly ) . "<br />" .
182 $prevlink;
183 $newHeader = "<strong>{$this->mNewtitle}</strong><br />" .
184 $sk->revUserTools( $this->mNewRev ) . " $rollback<br />" .
185 $newminor . $sk->revComment( $this->mNewRev, !$diffOnly ) . "<br />" .
186 $nextlink . $patrol;
187
188 $this->showDiff( $oldHeader, $newHeader );
189
190 if ( !$diffOnly )
191 $this->renderNewRevision();
192
193 wfProfileOut( $fname );
194 }
195
196 /**
197 * Show the new revision of the page.
198 */
199 function renderNewRevision() {
200 global $wgOut;
201 $fname = 'DifferenceEngine::renderNewRevision';
202 wfProfileIn( $fname );
203
204 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
205 #add deleted rev tag if needed
206 if ( !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) {
207 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
208 }
209
210 if( !$this->mNewRev->isCurrent() ) {
211 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
212 }
213
214 $this->loadNewText();
215 if( is_object( $this->mNewRev ) ) {
216 $wgOut->setRevisionId( $this->mNewRev->getId() );
217 }
218
219 $wgOut->addWikiTextTidy( $this->mNewtext );
220
221 if( !$this->mNewRev->isCurrent() ) {
222 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
223 }
224
225 wfProfileOut( $fname );
226 }
227
228 /**
229 * Show the first revision of an article. Uses normal diff headers in
230 * contrast to normal "old revision" display style.
231 */
232 function showFirstRevision() {
233 global $wgOut, $wgUser;
234
235 $fname = 'DifferenceEngine::showFirstRevision';
236 wfProfileIn( $fname );
237
238 # Get article text from the DB
239 #
240 if ( ! $this->loadNewText() ) {
241 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
242 "{$this->mNewid})";
243 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
244 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
245 $wgOut->addWikitext( $mtext );
246 wfProfileOut( $fname );
247 return;
248 }
249 if ( $this->mNewRev->isCurrent() ) {
250 $wgOut->setArticleFlag( true );
251 }
252
253 # Check if user is allowed to look at this page. If not, bail out.
254 #
255 if ( !( $this->mTitle->userCanRead() ) ) {
256 $wgOut->loginToUse();
257 $wgOut->output();
258 wfProfileOut( $fname );
259 exit;
260 }
261
262 # Prepare the header box
263 #
264 $sk = $wgUser->getSkin();
265
266 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
267 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
268 $sk->revUserTools( $this->mNewRev ) . "<br />" .
269 $sk->revComment( $this->mNewRev ) . "<br />" .
270 $nextlink . "</div>\n";
271
272 $wgOut->addHTML( $header );
273
274 $wgOut->setSubtitle( wfMsg( 'difference' ) );
275 $wgOut->setRobotpolicy( 'noindex,nofollow' );
276
277 wfProfileOut( $fname );
278 }
279
280 /**
281 * Get the diff text, send it to $wgOut
282 * Returns false if the diff could not be generated, otherwise returns true
283 */
284 function showDiff( $otitle, $ntitle ) {
285 global $wgOut;
286 $diff = $this->getDiff( $otitle, $ntitle );
287 if ( $diff === false ) {
288 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
289 return false;
290 } else {
291 $wgOut->addHTML( $diff );
292 return true;
293 }
294 }
295
296 /**
297 * Get diff table, including header
298 * Note that the interface has changed, it's no longer static.
299 * Returns false on error
300 */
301 function getDiff( $otitle, $ntitle ) {
302 $body = $this->getDiffBody();
303 if ( $body === false ) {
304 return false;
305 } else {
306 $multi = $this->getMultiNotice();
307 return $this->addHeader( $body, $otitle, $ntitle, $multi );
308 }
309 }
310
311 /**
312 * Get the diff table body, without header
313 * Results are cached
314 * Returns false on error
315 */
316 function getDiffBody() {
317 global $wgMemc;
318 $fname = 'DifferenceEngine::getDiffBody';
319 wfProfileIn( $fname );
320
321 // Cacheable?
322 $key = false;
323 if ( $this->mOldid && $this->mNewid ) {
324 // Try cache
325 $key = wfMemcKey( 'diff', 'oldid', $this->mOldid, 'newid', $this->mNewid );
326 $difftext = $wgMemc->get( $key );
327 if ( $difftext ) {
328 wfIncrStats( 'diff_cache_hit' );
329 $difftext = $this->localiseLineNumbers( $difftext );
330 $difftext .= "\n<!-- diff cache key $key -->\n";
331 wfProfileOut( $fname );
332 return $difftext;
333 }
334 }
335
336 #loadtext is permission safe, this just clears out the diff
337 if ( !$this->loadText() ) {
338 wfProfileOut( $fname );
339 return false;
340 } else if ( $this->mOldRev && !$this->mOldRev->userCan(Revision::DELETED_TEXT) ) {
341 return '';
342 } else if ( $this->mNewRev && !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) {
343 return '';
344 }
345
346 $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext );
347
348 // Save to cache for 7 days
349 if ( $key !== false && $difftext !== false ) {
350 wfIncrStats( 'diff_cache_miss' );
351 $wgMemc->set( $key, $difftext, 7*86400 );
352 } else {
353 wfIncrStats( 'diff_uncacheable' );
354 }
355 // Replace line numbers with the text in the user's language
356 if ( $difftext !== false ) {
357 $difftext = $this->localiseLineNumbers( $difftext );
358 }
359 wfProfileOut( $fname );
360 return $difftext;
361 }
362
363 /**
364 * Generate a diff, no caching
365 * $otext and $ntext must be already segmented
366 */
367 function generateDiffBody( $otext, $ntext ) {
368 global $wgExternalDiffEngine, $wgContLang;
369 $fname = 'DifferenceEngine::generateDiffBody';
370
371 $otext = str_replace( "\r\n", "\n", $otext );
372 $ntext = str_replace( "\r\n", "\n", $ntext );
373
374 if ( $wgExternalDiffEngine == 'wikidiff' ) {
375 # For historical reasons, external diff engine expects
376 # input text to be HTML-escaped already
377 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
378 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
379 if( !function_exists( 'wikidiff_do_diff' ) ) {
380 dl('php_wikidiff.so');
381 }
382 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
383 }
384
385 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
386 # Better external diff engine, the 2 may some day be dropped
387 # This one does the escaping and segmenting itself
388 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
389 wfProfileIn( "$fname-dl" );
390 @dl('php_wikidiff2.so');
391 wfProfileOut( "$fname-dl" );
392 }
393 if ( function_exists( 'wikidiff2_do_diff' ) ) {
394 wfProfileIn( 'wikidiff2_do_diff' );
395 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
396 wfProfileOut( 'wikidiff2_do_diff' );
397 return $text;
398 }
399 }
400 if ( $wgExternalDiffEngine !== false ) {
401 # Diff via the shell
402 global $wgTmpDirectory;
403 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
404 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
405
406 $tempFile1 = fopen( $tempName1, "w" );
407 if ( !$tempFile1 ) {
408 wfProfileOut( $fname );
409 return false;
410 }
411 $tempFile2 = fopen( $tempName2, "w" );
412 if ( !$tempFile2 ) {
413 wfProfileOut( $fname );
414 return false;
415 }
416 fwrite( $tempFile1, $otext );
417 fwrite( $tempFile2, $ntext );
418 fclose( $tempFile1 );
419 fclose( $tempFile2 );
420 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
421 wfProfileIn( "$fname-shellexec" );
422 $difftext = wfShellExec( $cmd );
423 wfProfileOut( "$fname-shellexec" );
424 unlink( $tempName1 );
425 unlink( $tempName2 );
426 return $difftext;
427 }
428
429 # Native PHP diff
430 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
431 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
432 $diffs = new Diff( $ota, $nta );
433 $formatter = new TableDiffFormatter();
434 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
435 }
436
437
438 /**
439 * Replace line numbers with the text in the user's language
440 */
441 function localiseLineNumbers( $text ) {
442 return preg_replace_callback( '/<!--LINE (\d+)-->/',
443 array( &$this, 'localiseLineNumbersCb' ), $text );
444 }
445
446 function localiseLineNumbersCb( $matches ) {
447 global $wgLang;
448 return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) );
449 }
450
451
452 /**
453 * If there are revisions between the ones being compared, return a note saying so.
454 */
455 function getMultiNotice() {
456 if ( !is_object($this->mOldRev) || !is_object($this->mNewRev) )
457 return '';
458
459 if( !$this->mOldPage->equals( $this->mNewPage ) ) {
460 // Comparing two different pages? Count would be meaningless.
461 return '';
462 }
463
464 $oldid = $this->mOldRev->getId();
465 $newid = $this->mNewRev->getId();
466 if ( $oldid > $newid ) {
467 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
468 }
469
470 $n = $this->mTitle->countRevisionsBetween( $oldid, $newid );
471 if ( !$n )
472 return '';
473
474 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
475 }
476
477
478 /**
479 * Add the header to a diff body
480 */
481 function addHeader( $diff, $otitle, $ntitle, $multi = '' ) {
482 global $wgOut;
483
484 if ( $this->mOldRev && $this->mOldRev->isDeleted(Revision::DELETED_TEXT) ) {
485 $otitle = '<span class="history-deleted">'.$otitle.'</span>';
486 }
487 if ( $this->mNewRev && $this->mNewRev->isDeleted(Revision::DELETED_TEXT) ) {
488 $ntitle = '<span class="history-deleted">'.$ntitle.'</span>';
489 }
490 $header = "
491 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
492 <tr>
493 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
494 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
495 </tr>
496 ";
497
498 if ( $multi != '' )
499 $header .= "<tr><td colspan='4' align='center' class='diff-multi'>{$multi}</td></tr>";
500
501 return $header . $diff . "</table>";
502 }
503
504 /**
505 * Use specified text instead of loading from the database
506 */
507 function setText( $oldText, $newText ) {
508 $this->mOldtext = $oldText;
509 $this->mNewtext = $newText;
510 $this->mTextLoaded = 2;
511 }
512
513 /**
514 * Load revision metadata for the specified articles. If newid is 0, then compare
515 * the old article in oldid to the current article; if oldid is 0, then
516 * compare the current article to the immediately previous one (ignoring the
517 * value of newid).
518 *
519 * If oldid is false, leave the corresponding revision object set
520 * to false. This is impossible via ordinary user input, and is provided for
521 * API convenience.
522 */
523 function loadRevisionData() {
524 global $wgLang;
525 if ( $this->mRevisionsLoaded ) {
526 return true;
527 } else {
528 // Whether it succeeds or fails, we don't want to try again
529 $this->mRevisionsLoaded = true;
530 }
531
532 // Load the new revision object
533 if( $this->mNewid ) {
534 $this->mNewRev = Revision::newFromId( $this->mNewid );
535 } else {
536 $this->mNewRev = Revision::newFromTitle( $this->mTitle );
537 }
538
539 if( is_null( $this->mNewRev ) ) {
540 return false;
541 }
542
543 // Set assorted variables
544 $timestamp = $wgLang->timeanddate( $this->mNewRev->getTimestamp(), true );
545 $this->mNewPage = $this->mNewRev->getTitle();
546 if( $this->mNewRev->isCurrent() ) {
547 $newLink = $this->mNewPage->escapeLocalUrl();
548 $this->mPagetitle = htmlspecialchars( wfMsg( 'currentrev' ) );
549 $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit' );
550 $newUndo = $this->mNewPage->escapeLocalUrl( 'action=edit&undo=' . $this->mNewid );
551
552 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
553 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)"
554 . " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
555
556 } else {
557 $newLink = $this->mNewPage->escapeLocalUrl( 'oldid=' . $this->mNewid );
558 $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid );
559 $newUndo = $this->mNewPage->escapeLocalUrl( 'action=edit&undo=' . $this->mNewid );
560 $this->mPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) );
561
562 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>"
563 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)"
564 . " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
565 }
566
567 // Load the old revision object
568 $this->mOldRev = false;
569 if( $this->mOldid ) {
570 $this->mOldRev = Revision::newFromId( $this->mOldid );
571 } elseif ( $this->mOldid === 0 ) {
572 $rev = $this->mNewRev->getPrevious();
573 if( $rev ) {
574 $this->mOldid = $rev->getId();
575 $this->mOldRev = $rev;
576 } else {
577 // No previous revision; mark to show as first-version only.
578 $this->mOldid = false;
579 $this->mOldRev = false;
580 }
581 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
582
583 if( is_null( $this->mOldRev ) ) {
584 return false;
585 }
586
587 if ( $this->mOldRev ) {
588 $this->mOldPage = $this->mOldRev->getTitle();
589
590 $t = $wgLang->timeanddate( $this->mOldRev->getTimestamp(), true );
591 $oldLink = $this->mOldPage->escapeLocalUrl( 'oldid=' . $this->mOldid );
592 $oldEdit = $this->mOldPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid );
593 $this->mOldtitle = "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) )
594 . "</a> (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
595 }
596
597 return true;
598 }
599
600 /**
601 * Load the text of the revisions, as well as revision data.
602 */
603 function loadText() {
604 if ( $this->mTextLoaded == 2 ) {
605 return true;
606 } else {
607 // Whether it succeeds or fails, we don't want to try again
608 $this->mTextLoaded = 2;
609 }
610
611 if ( !$this->loadRevisionData() ) {
612 return false;
613 }
614 if ( $this->mOldRev ) {
615 // FIXME: permission tests
616 $this->mOldtext = $this->mOldRev->revText();
617 if ( $this->mOldtext === false ) {
618 return false;
619 }
620 }
621 if ( $this->mNewRev ) {
622 $this->mNewtext = $this->mNewRev->revText();
623 if ( $this->mNewtext === false ) {
624 return false;
625 }
626 }
627 return true;
628 }
629
630 /**
631 * Load the text of the new revision, not the old one
632 */
633 function loadNewText() {
634 if ( $this->mTextLoaded >= 1 ) {
635 return true;
636 } else {
637 $this->mTextLoaded = 1;
638 }
639 if ( !$this->loadRevisionData() ) {
640 return false;
641 }
642 $this->mNewtext = $this->mNewRev->getText();
643 return true;
644 }
645
646
647 }
648
649 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
650 //
651 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
652 // You may copy this code freely under the conditions of the GPL.
653 //
654
655 define('USE_ASSERTS', function_exists('assert'));
656
657 /**
658 * @todo document
659 * @private
660 * @addtogroup DifferenceEngine
661 */
662 class _DiffOp {
663 var $type;
664 var $orig;
665 var $closing;
666
667 function reverse() {
668 trigger_error('pure virtual', E_USER_ERROR);
669 }
670
671 function norig() {
672 return $this->orig ? sizeof($this->orig) : 0;
673 }
674
675 function nclosing() {
676 return $this->closing ? sizeof($this->closing) : 0;
677 }
678 }
679
680 /**
681 * @todo document
682 * @private
683 * @addtogroup DifferenceEngine
684 */
685 class _DiffOp_Copy extends _DiffOp {
686 var $type = 'copy';
687
688 function _DiffOp_Copy ($orig, $closing = false) {
689 if (!is_array($closing))
690 $closing = $orig;
691 $this->orig = $orig;
692 $this->closing = $closing;
693 }
694
695 function reverse() {
696 return new _DiffOp_Copy($this->closing, $this->orig);
697 }
698 }
699
700 /**
701 * @todo document
702 * @private
703 * @addtogroup DifferenceEngine
704 */
705 class _DiffOp_Delete extends _DiffOp {
706 var $type = 'delete';
707
708 function _DiffOp_Delete ($lines) {
709 $this->orig = $lines;
710 $this->closing = false;
711 }
712
713 function reverse() {
714 return new _DiffOp_Add($this->orig);
715 }
716 }
717
718 /**
719 * @todo document
720 * @private
721 * @addtogroup DifferenceEngine
722 */
723 class _DiffOp_Add extends _DiffOp {
724 var $type = 'add';
725
726 function _DiffOp_Add ($lines) {
727 $this->closing = $lines;
728 $this->orig = false;
729 }
730
731 function reverse() {
732 return new _DiffOp_Delete($this->closing);
733 }
734 }
735
736 /**
737 * @todo document
738 * @private
739 * @addtogroup DifferenceEngine
740 */
741 class _DiffOp_Change extends _DiffOp {
742 var $type = 'change';
743
744 function _DiffOp_Change ($orig, $closing) {
745 $this->orig = $orig;
746 $this->closing = $closing;
747 }
748
749 function reverse() {
750 return new _DiffOp_Change($this->closing, $this->orig);
751 }
752 }
753
754
755 /**
756 * Class used internally by Diff to actually compute the diffs.
757 *
758 * The algorithm used here is mostly lifted from the perl module
759 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
760 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
761 *
762 * More ideas are taken from:
763 * http://www.ics.uci.edu/~eppstein/161/960229.html
764 *
765 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
766 * diffutils-2.7, which can be found at:
767 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
768 *
769 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
770 * are my own.
771 *
772 * Line length limits for robustness added by Tim Starling, 2005-08-31
773 *
774 * @author Geoffrey T. Dairiki, Tim Starling
775 * @private
776 * @addtogroup DifferenceEngine
777 */
778 class _DiffEngine
779 {
780 const MAX_XREF_LENGTH = 10000;
781
782 function diff ($from_lines, $to_lines) {
783 $fname = '_DiffEngine::diff';
784 wfProfileIn( $fname );
785
786 $n_from = sizeof($from_lines);
787 $n_to = sizeof($to_lines);
788
789 $this->xchanged = $this->ychanged = array();
790 $this->xv = $this->yv = array();
791 $this->xind = $this->yind = array();
792 unset($this->seq);
793 unset($this->in_seq);
794 unset($this->lcs);
795
796 // Skip leading common lines.
797 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
798 if ($from_lines[$skip] !== $to_lines[$skip])
799 break;
800 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
801 }
802 // Skip trailing common lines.
803 $xi = $n_from; $yi = $n_to;
804 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
805 if ($from_lines[$xi] !== $to_lines[$yi])
806 break;
807 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
808 }
809
810 // Ignore lines which do not exist in both files.
811 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
812 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
813 }
814
815 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
816 $line = $to_lines[$yi];
817 if ( ($this->ychanged[$yi] = empty($xhash[$this->_line_hash($line)])) )
818 continue;
819 $yhash[$this->_line_hash($line)] = 1;
820 $this->yv[] = $line;
821 $this->yind[] = $yi;
822 }
823 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
824 $line = $from_lines[$xi];
825 if ( ($this->xchanged[$xi] = empty($yhash[$this->_line_hash($line)])) )
826 continue;
827 $this->xv[] = $line;
828 $this->xind[] = $xi;
829 }
830
831 // Find the LCS.
832 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
833
834 // Merge edits when possible
835 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
836 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
837
838 // Compute the edit operations.
839 $edits = array();
840 $xi = $yi = 0;
841 while ($xi < $n_from || $yi < $n_to) {
842 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
843 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
844
845 // Skip matching "snake".
846 $copy = array();
847 while ( $xi < $n_from && $yi < $n_to
848 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
849 $copy[] = $from_lines[$xi++];
850 ++$yi;
851 }
852 if ($copy)
853 $edits[] = new _DiffOp_Copy($copy);
854
855 // Find deletes & adds.
856 $delete = array();
857 while ($xi < $n_from && $this->xchanged[$xi])
858 $delete[] = $from_lines[$xi++];
859
860 $add = array();
861 while ($yi < $n_to && $this->ychanged[$yi])
862 $add[] = $to_lines[$yi++];
863
864 if ($delete && $add)
865 $edits[] = new _DiffOp_Change($delete, $add);
866 elseif ($delete)
867 $edits[] = new _DiffOp_Delete($delete);
868 elseif ($add)
869 $edits[] = new _DiffOp_Add($add);
870 }
871 wfProfileOut( $fname );
872 return $edits;
873 }
874
875 /**
876 * Returns the whole line if it's small enough, or the MD5 hash otherwise
877 */
878 function _line_hash( $line ) {
879 if ( strlen( $line ) > self::MAX_XREF_LENGTH ) {
880 return md5( $line );
881 } else {
882 return $line;
883 }
884 }
885
886
887 /* Divide the Largest Common Subsequence (LCS) of the sequences
888 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
889 * sized segments.
890 *
891 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
892 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
893 * sub sequences. The first sub-sequence is contained in [X0, X1),
894 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
895 * that (X0, Y0) == (XOFF, YOFF) and
896 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
897 *
898 * This function assumes that the first lines of the specified portions
899 * of the two files do not match, and likewise that the last lines do not
900 * match. The caller must trim matching lines from the beginning and end
901 * of the portions it is going to specify.
902 */
903 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
904 $fname = '_DiffEngine::_diag';
905 wfProfileIn( $fname );
906 $flip = false;
907
908 if ($xlim - $xoff > $ylim - $yoff) {
909 // Things seems faster (I'm not sure I understand why)
910 // when the shortest sequence in X.
911 $flip = true;
912 list ($xoff, $xlim, $yoff, $ylim)
913 = array( $yoff, $ylim, $xoff, $xlim);
914 }
915
916 if ($flip)
917 for ($i = $ylim - 1; $i >= $yoff; $i--)
918 $ymatches[$this->xv[$i]][] = $i;
919 else
920 for ($i = $ylim - 1; $i >= $yoff; $i--)
921 $ymatches[$this->yv[$i]][] = $i;
922
923 $this->lcs = 0;
924 $this->seq[0]= $yoff - 1;
925 $this->in_seq = array();
926 $ymids[0] = array();
927
928 $numer = $xlim - $xoff + $nchunks - 1;
929 $x = $xoff;
930 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
931 wfProfileIn( "$fname-chunk" );
932 if ($chunk > 0)
933 for ($i = 0; $i <= $this->lcs; $i++)
934 $ymids[$i][$chunk-1] = $this->seq[$i];
935
936 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
937 for ( ; $x < $x1; $x++) {
938 $line = $flip ? $this->yv[$x] : $this->xv[$x];
939 if (empty($ymatches[$line]))
940 continue;
941 $matches = $ymatches[$line];
942 reset($matches);
943 while (list ($junk, $y) = each($matches))
944 if (empty($this->in_seq[$y])) {
945 $k = $this->_lcs_pos($y);
946 USE_ASSERTS && assert($k > 0);
947 $ymids[$k] = $ymids[$k-1];
948 break;
949 }
950 while (list ( /* $junk */, $y) = each($matches)) {
951 if ($y > $this->seq[$k-1]) {
952 USE_ASSERTS && assert($y < $this->seq[$k]);
953 // Optimization: this is a common case:
954 // next match is just replacing previous match.
955 $this->in_seq[$this->seq[$k]] = false;
956 $this->seq[$k] = $y;
957 $this->in_seq[$y] = 1;
958 } else if (empty($this->in_seq[$y])) {
959 $k = $this->_lcs_pos($y);
960 USE_ASSERTS && assert($k > 0);
961 $ymids[$k] = $ymids[$k-1];
962 }
963 }
964 }
965 wfProfileOut( "$fname-chunk" );
966 }
967
968 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
969 $ymid = $ymids[$this->lcs];
970 for ($n = 0; $n < $nchunks - 1; $n++) {
971 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
972 $y1 = $ymid[$n] + 1;
973 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
974 }
975 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
976
977 wfProfileOut( $fname );
978 return array($this->lcs, $seps);
979 }
980
981 function _lcs_pos ($ypos) {
982 $fname = '_DiffEngine::_lcs_pos';
983 wfProfileIn( $fname );
984
985 $end = $this->lcs;
986 if ($end == 0 || $ypos > $this->seq[$end]) {
987 $this->seq[++$this->lcs] = $ypos;
988 $this->in_seq[$ypos] = 1;
989 wfProfileOut( $fname );
990 return $this->lcs;
991 }
992
993 $beg = 1;
994 while ($beg < $end) {
995 $mid = (int)(($beg + $end) / 2);
996 if ( $ypos > $this->seq[$mid] )
997 $beg = $mid + 1;
998 else
999 $end = $mid;
1000 }
1001
1002 USE_ASSERTS && assert($ypos != $this->seq[$end]);
1003
1004 $this->in_seq[$this->seq[$end]] = false;
1005 $this->seq[$end] = $ypos;
1006 $this->in_seq[$ypos] = 1;
1007 wfProfileOut( $fname );
1008 return $end;
1009 }
1010
1011 /* Find LCS of two sequences.
1012 *
1013 * The results are recorded in the vectors $this->{x,y}changed[], by
1014 * storing a 1 in the element for each line that is an insertion
1015 * or deletion (ie. is not in the LCS).
1016 *
1017 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1018 *
1019 * Note that XLIM, YLIM are exclusive bounds.
1020 * All line numbers are origin-0 and discarded lines are not counted.
1021 */
1022 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1023 $fname = '_DiffEngine::_compareseq';
1024 wfProfileIn( $fname );
1025
1026 // Slide down the bottom initial diagonal.
1027 while ($xoff < $xlim && $yoff < $ylim
1028 && $this->xv[$xoff] == $this->yv[$yoff]) {
1029 ++$xoff;
1030 ++$yoff;
1031 }
1032
1033 // Slide up the top initial diagonal.
1034 while ($xlim > $xoff && $ylim > $yoff
1035 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
1036 --$xlim;
1037 --$ylim;
1038 }
1039
1040 if ($xoff == $xlim || $yoff == $ylim)
1041 $lcs = 0;
1042 else {
1043 // This is ad hoc but seems to work well.
1044 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1045 //$nchunks = max(2,min(8,(int)$nchunks));
1046 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
1047 list ($lcs, $seps)
1048 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1049 }
1050
1051 if ($lcs == 0) {
1052 // X and Y sequences have no common subsequence:
1053 // mark all changed.
1054 while ($yoff < $ylim)
1055 $this->ychanged[$this->yind[$yoff++]] = 1;
1056 while ($xoff < $xlim)
1057 $this->xchanged[$this->xind[$xoff++]] = 1;
1058 } else {
1059 // Use the partitions to split this problem into subproblems.
1060 reset($seps);
1061 $pt1 = $seps[0];
1062 while ($pt2 = next($seps)) {
1063 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1064 $pt1 = $pt2;
1065 }
1066 }
1067 wfProfileOut( $fname );
1068 }
1069
1070 /* Adjust inserts/deletes of identical lines to join changes
1071 * as much as possible.
1072 *
1073 * We do something when a run of changed lines include a
1074 * line at one end and has an excluded, identical line at the other.
1075 * We are free to choose which identical line is included.
1076 * `compareseq' usually chooses the one at the beginning,
1077 * but usually it is cleaner to consider the following identical line
1078 * to be the "change".
1079 *
1080 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1081 */
1082 function _shift_boundaries ($lines, &$changed, $other_changed) {
1083 $fname = '_DiffEngine::_shift_boundaries';
1084 wfProfileIn( $fname );
1085 $i = 0;
1086 $j = 0;
1087
1088 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
1089 $len = sizeof($lines);
1090 $other_len = sizeof($other_changed);
1091
1092 while (1) {
1093 /*
1094 * Scan forwards to find beginning of another run of changes.
1095 * Also keep track of the corresponding point in the other file.
1096 *
1097 * Throughout this code, $i and $j are adjusted together so that
1098 * the first $i elements of $changed and the first $j elements
1099 * of $other_changed both contain the same number of zeros
1100 * (unchanged lines).
1101 * Furthermore, $j is always kept so that $j == $other_len or
1102 * $other_changed[$j] == false.
1103 */
1104 while ($j < $other_len && $other_changed[$j])
1105 $j++;
1106
1107 while ($i < $len && ! $changed[$i]) {
1108 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1109 $i++; $j++;
1110 while ($j < $other_len && $other_changed[$j])
1111 $j++;
1112 }
1113
1114 if ($i == $len)
1115 break;
1116
1117 $start = $i;
1118
1119 // Find the end of this run of changes.
1120 while (++$i < $len && $changed[$i])
1121 continue;
1122
1123 do {
1124 /*
1125 * Record the length of this run of changes, so that
1126 * we can later determine whether the run has grown.
1127 */
1128 $runlength = $i - $start;
1129
1130 /*
1131 * Move the changed region back, so long as the
1132 * previous unchanged line matches the last changed one.
1133 * This merges with previous changed regions.
1134 */
1135 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1136 $changed[--$start] = 1;
1137 $changed[--$i] = false;
1138 while ($start > 0 && $changed[$start - 1])
1139 $start--;
1140 USE_ASSERTS && assert('$j > 0');
1141 while ($other_changed[--$j])
1142 continue;
1143 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1144 }
1145
1146 /*
1147 * Set CORRESPONDING to the end of the changed run, at the last
1148 * point where it corresponds to a changed run in the other file.
1149 * CORRESPONDING == LEN means no such point has been found.
1150 */
1151 $corresponding = $j < $other_len ? $i : $len;
1152
1153 /*
1154 * Move the changed region forward, so long as the
1155 * first changed line matches the following unchanged one.
1156 * This merges with following changed regions.
1157 * Do this second, so that if there are no merges,
1158 * the changed region is moved forward as far as possible.
1159 */
1160 while ($i < $len && $lines[$start] == $lines[$i]) {
1161 $changed[$start++] = false;
1162 $changed[$i++] = 1;
1163 while ($i < $len && $changed[$i])
1164 $i++;
1165
1166 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1167 $j++;
1168 if ($j < $other_len && $other_changed[$j]) {
1169 $corresponding = $i;
1170 while ($j < $other_len && $other_changed[$j])
1171 $j++;
1172 }
1173 }
1174 } while ($runlength != $i - $start);
1175
1176 /*
1177 * If possible, move the fully-merged run of changes
1178 * back to a corresponding run in the other file.
1179 */
1180 while ($corresponding < $i) {
1181 $changed[--$start] = 1;
1182 $changed[--$i] = 0;
1183 USE_ASSERTS && assert('$j > 0');
1184 while ($other_changed[--$j])
1185 continue;
1186 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1187 }
1188 }
1189 wfProfileOut( $fname );
1190 }
1191 }
1192
1193 /**
1194 * Class representing a 'diff' between two sequences of strings.
1195 * @todo document
1196 * @private
1197 * @addtogroup DifferenceEngine
1198 */
1199 class Diff
1200 {
1201 var $edits;
1202
1203 /**
1204 * Constructor.
1205 * Computes diff between sequences of strings.
1206 *
1207 * @param $from_lines array An array of strings.
1208 * (Typically these are lines from a file.)
1209 * @param $to_lines array An array of strings.
1210 */
1211 function Diff($from_lines, $to_lines) {
1212 $eng = new _DiffEngine;
1213 $this->edits = $eng->diff($from_lines, $to_lines);
1214 //$this->_check($from_lines, $to_lines);
1215 }
1216
1217 /**
1218 * Compute reversed Diff.
1219 *
1220 * SYNOPSIS:
1221 *
1222 * $diff = new Diff($lines1, $lines2);
1223 * $rev = $diff->reverse();
1224 * @return object A Diff object representing the inverse of the
1225 * original diff.
1226 */
1227 function reverse () {
1228 $rev = $this;
1229 $rev->edits = array();
1230 foreach ($this->edits as $edit) {
1231 $rev->edits[] = $edit->reverse();
1232 }
1233 return $rev;
1234 }
1235
1236 /**
1237 * Check for empty diff.
1238 *
1239 * @return bool True iff two sequences were identical.
1240 */
1241 function isEmpty () {
1242 foreach ($this->edits as $edit) {
1243 if ($edit->type != 'copy')
1244 return false;
1245 }
1246 return true;
1247 }
1248
1249 /**
1250 * Compute the length of the Longest Common Subsequence (LCS).
1251 *
1252 * This is mostly for diagnostic purposed.
1253 *
1254 * @return int The length of the LCS.
1255 */
1256 function lcs () {
1257 $lcs = 0;
1258 foreach ($this->edits as $edit) {
1259 if ($edit->type == 'copy')
1260 $lcs += sizeof($edit->orig);
1261 }
1262 return $lcs;
1263 }
1264
1265 /**
1266 * Get the original set of lines.
1267 *
1268 * This reconstructs the $from_lines parameter passed to the
1269 * constructor.
1270 *
1271 * @return array The original sequence of strings.
1272 */
1273 function orig() {
1274 $lines = array();
1275
1276 foreach ($this->edits as $edit) {
1277 if ($edit->orig)
1278 array_splice($lines, sizeof($lines), 0, $edit->orig);
1279 }
1280 return $lines;
1281 }
1282
1283 /**
1284 * Get the closing set of lines.
1285 *
1286 * This reconstructs the $to_lines parameter passed to the
1287 * constructor.
1288 *
1289 * @return array The sequence of strings.
1290 */
1291 function closing() {
1292 $lines = array();
1293
1294 foreach ($this->edits as $edit) {
1295 if ($edit->closing)
1296 array_splice($lines, sizeof($lines), 0, $edit->closing);
1297 }
1298 return $lines;
1299 }
1300
1301 /**
1302 * Check a Diff for validity.
1303 *
1304 * This is here only for debugging purposes.
1305 */
1306 function _check ($from_lines, $to_lines) {
1307 $fname = 'Diff::_check';
1308 wfProfileIn( $fname );
1309 if (serialize($from_lines) != serialize($this->orig()))
1310 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
1311 if (serialize($to_lines) != serialize($this->closing()))
1312 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
1313
1314 $rev = $this->reverse();
1315 if (serialize($to_lines) != serialize($rev->orig()))
1316 trigger_error("Reversed original doesn't match", E_USER_ERROR);
1317 if (serialize($from_lines) != serialize($rev->closing()))
1318 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
1319
1320
1321 $prevtype = 'none';
1322 foreach ($this->edits as $edit) {
1323 if ( $prevtype == $edit->type )
1324 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
1325 $prevtype = $edit->type;
1326 }
1327
1328 $lcs = $this->lcs();
1329 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
1330 wfProfileOut( $fname );
1331 }
1332 }
1333
1334 /**
1335 * @todo document, bad name.
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 ?>