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