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