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