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