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