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