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