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