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