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