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