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