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