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