Fixing E_NOTICE
[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 {
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 $fname = 'DifferenceEngine::showDiffPage';
78 wfProfileIn( $fname );
79
80 # If external diffs are enabled both globally and for the user,
81 # we'll use the application/x-external-editor interface to call
82 # an external diff tool like kompare, kdiff3, etc.
83 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
84 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
85 $wgOut->disable();
86 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
87 $url1=$this->mTitle->getFullURL("action=raw&oldid=".$this->mOldid);
88 $url2=$this->mTitle->getFullURL("action=raw&oldid=".$this->mNewid);
89 $special=$wgLang->getNsText(NS_SPECIAL);
90 $control=<<<CONTROL
91 [Process]
92 Type=Diff text
93 Engine=MediaWiki
94 Script={$wgServer}{$wgScript}
95 Special namespace={$special}
96
97 [File]
98 Extension=wiki
99 URL=$url1
100
101 [File 2]
102 Extension=wiki
103 URL=$url2
104 CONTROL;
105 echo($control);
106 return;
107 }
108
109 $wgOut->setArticleFlag( false );
110 if ( ! $this->loadRevisionData() ) {
111 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})";
112 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
113 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
114 wfProfileOut( $fname );
115 return;
116 }
117
118 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
119
120 if ( $this->mNewRev->isCurrent() ) {
121 $wgOut->setArticleFlag( true );
122 }
123
124 # mOldid is false if the difference engine is called with a "vague" query for
125 # a diff between a version V and its previous version V' AND the version V
126 # is the first version of that article. In that case, V' does not exist.
127 if ( $this->mOldid === false ) {
128 $this->showFirstRevision();
129 $this->renderNewRevision(); // should we respect $diffOnly here or not?
130 wfProfileOut( $fname );
131 return;
132 }
133
134 $wgOut->suppressQuickbar();
135
136 $oldTitle = $this->mOldPage->getPrefixedText();
137 $newTitle = $this->mNewPage->getPrefixedText();
138 if( $oldTitle == $newTitle ) {
139 $wgOut->setPageTitle( $newTitle );
140 } else {
141 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
142 }
143 $wgOut->setSubtitle( wfMsg( 'difference' ) );
144 $wgOut->setRobotpolicy( 'noindex,nofollow' );
145
146 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
147 $wgOut->loginToUse();
148 $wgOut->output();
149 wfProfileOut( $fname );
150 exit;
151 }
152
153 $sk = $wgUser->getSkin();
154
155 if ( $this->mNewRev->isCurrent() && $wgUser->isAllowed('rollback') ) {
156 $rollback = '&nbsp;&nbsp;&nbsp;' . $sk->generateRollback( $this->mNewRev );
157 } else {
158 $rollback = '';
159 }
160
161 // Prepare a change patrol link, if applicable
162 if( $wgUseRCPatrol && $wgUser->isAllowed( 'patrol' ) ) {
163 // If we've been given an explicit change identifier, use it; saves time
164 if( $this->mRcidMarkPatrolled ) {
165 $rcid = $this->mRcidMarkPatrolled;
166 } else {
167 // Look for an unpatrolled change corresponding to this diff
168 $db = wfGetDB( DB_SLAVE );
169 $change = RecentChange::newFromConds(
170 array(
171 // Add redundant user,timestamp condition so we can use the existing index
172 'rc_user_text' => $this->mNewRev->getRawUserText(),
173 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
174 'rc_this_oldid' => $this->mNewid,
175 'rc_last_oldid' => $this->mOldid,
176 'rc_patrolled' => 0
177 ),
178 __METHOD__
179 );
180 if( $change instanceof RecentChange ) {
181 $rcid = $change->mAttribs['rc_id'];
182 } else {
183 // None found
184 $rcid = 0;
185 }
186 }
187 // Build the link
188 if( $rcid ) {
189 $patrol = ' <span class="patrollink">[' . $sk->makeKnownLinkObj(
190 $this->mTitle,
191 wfMsgHtml( 'markaspatrolleddiff' ),
192 "action=markpatrolled&rcid={$rcid}"
193 ) . ']</span>';
194 } else {
195 $patrol = '';
196 }
197 } else {
198 $patrol = '';
199 }
200
201 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousdiff' ),
202 'diff=prev&oldid='.$this->mOldid, '', '', 'id="differences-prevlink"' );
203 if ( $this->mNewRev->isCurrent() ) {
204 $nextlink = '&nbsp;';
205 } else {
206 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ),
207 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
208 }
209
210 $oldminor = '';
211 $newminor = '';
212
213 if ($this->mOldRev->mMinorEdit == 1) {
214 $oldminor = wfElement( 'span', array( 'class' => 'minor' ),
215 wfMsg( 'minoreditletter') ) . ' ';
216 }
217
218 if ($this->mNewRev->mMinorEdit == 1) {
219 $newminor = wfElement( 'span', array( 'class' => 'minor' ),
220 wfMsg( 'minoreditletter') ) . ' ';
221 }
222
223 $rdel = ''; $ldel = '';
224 if( $wgUser->isAllowed( 'deleterevision' ) ) {
225 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
226 if( !$this->mOldRev->userCan( Revision::DELETED_RESTRICTED ) ) {
227 // If revision was hidden from sysops
228 $ldel = wfMsgHtml('rev-delundel');
229 } else {
230 $ldel = $sk->makeKnownLinkObj( $revdel,
231 wfMsgHtml('rev-delundel'),
232 'target=' . urlencode( $this->mOldRev->mTitle->getPrefixedDbkey() ) .
233 '&oldid=' . urlencode( $this->mOldRev->getId() ) );
234 // Bolden oversighted content
235 if( $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) )
236 $ldel = "<strong>$ldel</strong>";
237 }
238 $ldel = "&nbsp;&nbsp;&nbsp;<tt>(<small>$ldel</small>)</tt> ";
239 // We don't currently handle well changing the top revision's settings
240 if( $this->mNewRev->isCurrent() ) {
241 // If revision was hidden from sysops
242 $rdel = wfMsgHtml('rev-delundel');
243 } else if( !$this->mNewRev->userCan( Revision::DELETED_RESTRICTED ) ) {
244 // If revision was hidden from sysops
245 $rdel = wfMsgHtml('rev-delundel');
246 } else {
247 $rdel = $sk->makeKnownLinkObj( $revdel,
248 wfMsgHtml('rev-delundel'),
249 'target=' . urlencode( $this->mNewRev->mTitle->getPrefixedDbkey() ) .
250 '&oldid=' . urlencode( $this->mNewRev->getId() ) );
251 // Bolden oversighted content
252 if( $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) )
253 $rdel = "<strong>$rdel</strong>";
254 }
255 $rdel = "&nbsp;&nbsp;&nbsp;<tt>(<small>$rdel</small>)</tt> ";
256 }
257
258 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle.'</strong></div>' .
259 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev, true ) . "</div>" .
260 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev, !$diffOnly, true ) . $ldel . "</div>" .
261 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
262 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle.'</strong></div>' .
263 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev, true ) . " $rollback</div>" .
264 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev, !$diffOnly, true ) . $rdel . "</div>" .
265 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
266
267 $this->showDiff( $oldHeader, $newHeader );
268
269 if ( !$diffOnly )
270 $this->renderNewRevision();
271
272 wfProfileOut( $fname );
273 }
274
275 /**
276 * Show the new revision of the page.
277 */
278 function renderNewRevision() {
279 global $wgOut;
280 $fname = 'DifferenceEngine::renderNewRevision';
281 wfProfileIn( $fname );
282
283 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
284 #add deleted rev tag if needed
285 if( !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) {
286 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
287 } else if( $this->mNewRev->isDeleted(Revision::DELETED_TEXT) ) {
288 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
289 }
290
291 if( !$this->mNewRev->isCurrent() ) {
292 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
293 }
294
295 $this->loadNewText();
296 if( is_object( $this->mNewRev ) ) {
297 $wgOut->setRevisionId( $this->mNewRev->getId() );
298 }
299
300 if ($this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage()) {
301 // Stolen from Article::view --AG 2007-10-11
302
303 // Give hooks a chance to customise the output
304 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext, $this->mTitle, $wgOut ) ) ) {
305 // Wrap the whole lot in a <pre> and don't parse
306 $m = array();
307 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
308 $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
309 $wgOut->addHtml( htmlspecialchars( $this->mNewtext ) );
310 $wgOut->addHtml( "\n</pre>\n" );
311 }
312 } else
313 $wgOut->addWikiTextTidy( $this->mNewtext );
314
315 if( !$this->mNewRev->isCurrent() ) {
316 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
317 }
318
319 wfProfileOut( $fname );
320 }
321
322 /**
323 * Show the first revision of an article. Uses normal diff headers in
324 * contrast to normal "old revision" display style.
325 */
326 function showFirstRevision() {
327 global $wgOut, $wgUser;
328
329 $fname = 'DifferenceEngine::showFirstRevision';
330 wfProfileIn( $fname );
331
332 # Get article text from the DB
333 #
334 if ( ! $this->loadNewText() ) {
335 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
336 "{$this->mNewid})";
337 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
338 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
339 wfProfileOut( $fname );
340 return;
341 }
342 if ( $this->mNewRev->isCurrent() ) {
343 $wgOut->setArticleFlag( true );
344 }
345
346 # Check if user is allowed to look at this page. If not, bail out.
347 #
348 if ( !( $this->mTitle->userCanRead() ) ) {
349 $wgOut->loginToUse();
350 $wgOut->output();
351 wfProfileOut( $fname );
352 exit;
353 }
354
355 # Prepare the header box
356 #
357 $sk = $wgUser->getSkin();
358
359 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
360 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
361 $sk->revUserTools( $this->mNewRev ) . "<br />" .
362 $sk->revComment( $this->mNewRev ) . "<br />" .
363 $nextlink . "</div>\n";
364
365 $wgOut->addHTML( $header );
366
367 $wgOut->setSubtitle( wfMsg( 'difference' ) );
368 $wgOut->setRobotpolicy( 'noindex,nofollow' );
369
370 wfProfileOut( $fname );
371 }
372
373 /**
374 * Get the diff text, send it to $wgOut
375 * Returns false if the diff could not be generated, otherwise returns true
376 */
377 function showDiff( $otitle, $ntitle ) {
378 global $wgOut;
379 $diff = $this->getDiff( $otitle, $ntitle );
380 if ( $diff === false ) {
381 $wgOut->addWikiMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" );
382 return false;
383 } else {
384 $this->showDiffStyle();
385 $wgOut->addHTML( $diff );
386 return true;
387 }
388 }
389
390 /**
391 * Add style sheets and supporting JS for diff display.
392 */
393 function showDiffStyle() {
394 global $wgStylePath, $wgStyleVersion, $wgOut;
395 $wgOut->addStyle( 'common/diff.css' );
396
397 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
398 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
399 }
400
401 /**
402 * Get complete diff table, including header
403 *
404 * @param Title $otitle Old title
405 * @param Title $ntitle New title
406 * @return mixed
407 */
408 function getDiff( $otitle, $ntitle ) {
409 $body = $this->getDiffBody();
410 if ( $body === false ) {
411 return false;
412 } else {
413 $multi = $this->getMultiNotice();
414 return $this->addHeader( $body, $otitle, $ntitle, $multi );
415 }
416 }
417
418 /**
419 * Get the diff table body, without header
420 *
421 * @return mixed
422 */
423 function getDiffBody() {
424 global $wgMemc;
425 $fname = 'DifferenceEngine::getDiffBody';
426 wfProfileIn( $fname );
427 // Check if the diff should be hidden from this user
428 if ( $this->mOldRev && !$this->mOldRev->userCan(Revision::DELETED_TEXT) ) {
429 return false;
430 } else if ( $this->mNewRev && !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) {
431 return false;
432 }
433 // Cacheable?
434 $key = false;
435 if ( $this->mOldid && $this->mNewid ) {
436 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION, 'oldid', $this->mOldid, 'newid', $this->mNewid );
437 // Try cache
438 if ( !$this->mRefreshCache ) {
439 $difftext = $wgMemc->get( $key );
440 if ( $difftext ) {
441 wfIncrStats( 'diff_cache_hit' );
442 $difftext = $this->localiseLineNumbers( $difftext );
443 $difftext .= "\n<!-- diff cache key $key -->\n";
444 wfProfileOut( $fname );
445 return $difftext;
446 }
447 } // don't try to load but save the result
448 }
449
450 // Loadtext is permission safe, this just clears out the diff
451 if ( !$this->loadText() ) {
452 wfProfileOut( $fname );
453 return false;
454 }
455
456 $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext );
457
458 // Save to cache for 7 days
459 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 = wfMsgHTML( '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 . "\n";
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 * A formatter that outputs unified diffs
1676 * @addtogroup DifferenceEngine
1677 */
1678
1679 class UnifiedDiffFormatter extends DiffFormatter
1680 {
1681 var $leading_context_lines = 2;
1682 var $trailing_context_lines = 2;
1683
1684 function _added($lines) {
1685 $this->_lines($lines, '+');
1686 }
1687 function _deleted($lines) {
1688 $this->_lines($lines, '-');
1689 }
1690 function _changed($orig, $closing) {
1691 $this->_deleted($orig);
1692 $this->_added($closing);
1693 }
1694 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1695 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1696 }
1697 }
1698
1699 /**
1700 * A pseudo-formatter that just passes along the Diff::$edits array
1701 * @addtogroup DifferenceEngine
1702 */
1703 class ArrayDiffFormatter extends DiffFormatter
1704 {
1705 function format($diff)
1706 {
1707 $oldline = 1;
1708 $newline = 1;
1709 $retval = array();
1710 foreach($diff->edits as $edit)
1711 switch($edit->type)
1712 {
1713 case 'add':
1714 foreach($edit->closing as $l)
1715 {
1716 $retval[] = array(
1717 'action' => 'add',
1718 'new'=> $l,
1719 'newline' => $newline++
1720 );
1721 }
1722 break;
1723 case 'delete':
1724 foreach($edit->orig as $l)
1725 {
1726 $retval[] = array(
1727 'action' => 'delete',
1728 'old' => $l,
1729 'oldline' => $oldline++,
1730 );
1731 }
1732 break;
1733 case 'change':
1734 foreach($edit->orig as $i => $l)
1735 {
1736 $retval[] = array(
1737 'action' => 'change',
1738 'old' => $l,
1739 'new' => @$edit->closing[$i],
1740 'oldline' => $oldline++,
1741 'newline' => $newline++,
1742 );
1743 }
1744 break;
1745 case 'copy':
1746 $oldline += count($edit->orig);
1747 $newline += count($edit->orig);
1748 }
1749 return $retval;
1750 }
1751 }
1752
1753 /**
1754 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1755 *
1756 */
1757
1758 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1759
1760 /**
1761 * @todo document
1762 * @private
1763 * @addtogroup DifferenceEngine
1764 */
1765 class _HWLDF_WordAccumulator {
1766 function _HWLDF_WordAccumulator () {
1767 $this->_lines = array();
1768 $this->_line = '';
1769 $this->_group = '';
1770 $this->_tag = '';
1771 }
1772
1773 function _flushGroup ($new_tag) {
1774 if ($this->_group !== '') {
1775 if ($this->_tag == 'ins')
1776 $this->_line .= '<ins class="diffchange diffchange-inline">' .
1777 htmlspecialchars ( $this->_group ) . '</ins>';
1778 elseif ($this->_tag == 'del')
1779 $this->_line .= '<del class="diffchange diffchange-inline">' .
1780 htmlspecialchars ( $this->_group ) . '</del>';
1781 else
1782 $this->_line .= htmlspecialchars ( $this->_group );
1783 }
1784 $this->_group = '';
1785 $this->_tag = $new_tag;
1786 }
1787
1788 function _flushLine ($new_tag) {
1789 $this->_flushGroup($new_tag);
1790 if ($this->_line != '')
1791 array_push ( $this->_lines, $this->_line );
1792 else
1793 # make empty lines visible by inserting an NBSP
1794 array_push ( $this->_lines, NBSP );
1795 $this->_line = '';
1796 }
1797
1798 function addWords ($words, $tag = '') {
1799 if ($tag != $this->_tag)
1800 $this->_flushGroup($tag);
1801
1802 foreach ($words as $word) {
1803 // new-line should only come as first char of word.
1804 if ($word == '')
1805 continue;
1806 if ($word[0] == "\n") {
1807 $this->_flushLine($tag);
1808 $word = substr($word, 1);
1809 }
1810 assert(!strstr($word, "\n"));
1811 $this->_group .= $word;
1812 }
1813 }
1814
1815 function getLines() {
1816 $this->_flushLine('~done');
1817 return $this->_lines;
1818 }
1819 }
1820
1821 /**
1822 * @todo document
1823 * @private
1824 * @addtogroup DifferenceEngine
1825 */
1826 class WordLevelDiff extends MappedDiff
1827 {
1828 const MAX_LINE_LENGTH = 10000;
1829
1830 function WordLevelDiff ($orig_lines, $closing_lines) {
1831 $fname = 'WordLevelDiff::WordLevelDiff';
1832 wfProfileIn( $fname );
1833
1834 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1835 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1836
1837 $this->MappedDiff($orig_words, $closing_words,
1838 $orig_stripped, $closing_stripped);
1839 wfProfileOut( $fname );
1840 }
1841
1842 function _split($lines) {
1843 $fname = 'WordLevelDiff::_split';
1844 wfProfileIn( $fname );
1845
1846 $words = array();
1847 $stripped = array();
1848 $first = true;
1849 foreach ( $lines as $line ) {
1850 # If the line is too long, just pretend the entire line is one big word
1851 # This prevents resource exhaustion problems
1852 if ( $first ) {
1853 $first = false;
1854 } else {
1855 $words[] = "\n";
1856 $stripped[] = "\n";
1857 }
1858 if ( strlen( $line ) > self::MAX_LINE_LENGTH ) {
1859 $words[] = $line;
1860 $stripped[] = $line;
1861 } else {
1862 $m = array();
1863 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1864 $line, $m))
1865 {
1866 $words = array_merge( $words, $m[0] );
1867 $stripped = array_merge( $stripped, $m[1] );
1868 }
1869 }
1870 }
1871 wfProfileOut( $fname );
1872 return array($words, $stripped);
1873 }
1874
1875 function orig () {
1876 $fname = 'WordLevelDiff::orig';
1877 wfProfileIn( $fname );
1878 $orig = new _HWLDF_WordAccumulator;
1879
1880 foreach ($this->edits as $edit) {
1881 if ($edit->type == 'copy')
1882 $orig->addWords($edit->orig);
1883 elseif ($edit->orig)
1884 $orig->addWords($edit->orig, 'del');
1885 }
1886 $lines = $orig->getLines();
1887 wfProfileOut( $fname );
1888 return $lines;
1889 }
1890
1891 function closing () {
1892 $fname = 'WordLevelDiff::closing';
1893 wfProfileIn( $fname );
1894 $closing = new _HWLDF_WordAccumulator;
1895
1896 foreach ($this->edits as $edit) {
1897 if ($edit->type == 'copy')
1898 $closing->addWords($edit->closing);
1899 elseif ($edit->closing)
1900 $closing->addWords($edit->closing, 'ins');
1901 }
1902 $lines = $closing->getLines();
1903 wfProfileOut( $fname );
1904 return $lines;
1905 }
1906 }
1907
1908 /**
1909 * Wikipedia Table style diff formatter.
1910 * @todo document
1911 * @private
1912 * @addtogroup DifferenceEngine
1913 */
1914 class TableDiffFormatter extends DiffFormatter
1915 {
1916 function TableDiffFormatter() {
1917 $this->leading_context_lines = 2;
1918 $this->trailing_context_lines = 2;
1919 }
1920
1921 public static function escapeWhiteSpace( $msg ) {
1922 $msg = preg_replace( '/^ /m', '&nbsp; ', $msg );
1923 $msg = preg_replace( '/ $/m', ' &nbsp;', $msg );
1924 $msg = preg_replace( '/ /', '&nbsp; ', $msg );
1925 return $msg;
1926 }
1927
1928 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1929 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1930 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1931 return $r;
1932 }
1933
1934 function _start_block( $header ) {
1935 echo $header;
1936 }
1937
1938 function _end_block() {
1939 }
1940
1941 function _lines( $lines, $prefix=' ', $color='white' ) {
1942 }
1943
1944 # HTML-escape parameter before calling this
1945 function addedLine( $line ) {
1946 return $this->wrapLine( '+', 'diff-addedline', $line );
1947 }
1948
1949 # HTML-escape parameter before calling this
1950 function deletedLine( $line ) {
1951 return $this->wrapLine( '-', 'diff-deletedline', $line );
1952 }
1953
1954 # HTML-escape parameter before calling this
1955 function contextLine( $line ) {
1956 return $this->wrapLine( ' ', 'diff-context', $line );
1957 }
1958
1959 private function wrapLine( $marker, $class, $line ) {
1960 if( $line !== '' ) {
1961 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1962 $line = Xml::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1963 }
1964 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1965 }
1966
1967 function emptyLine() {
1968 return '<td colspan="2">&nbsp;</td>';
1969 }
1970
1971 function _added( $lines ) {
1972 foreach ($lines as $line) {
1973 echo '<tr>' . $this->emptyLine() .
1974 $this->addedLine( '<ins class="diffchange">' .
1975 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1976 }
1977 }
1978
1979 function _deleted($lines) {
1980 foreach ($lines as $line) {
1981 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1982 htmlspecialchars ( $line ) . '</del>' ) .
1983 $this->emptyLine() . "</tr>\n";
1984 }
1985 }
1986
1987 function _context( $lines ) {
1988 foreach ($lines as $line) {
1989 echo '<tr>' .
1990 $this->contextLine( htmlspecialchars ( $line ) ) .
1991 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1992 }
1993 }
1994
1995 function _changed( $orig, $closing ) {
1996 $fname = 'TableDiffFormatter::_changed';
1997 wfProfileIn( $fname );
1998
1999 $diff = new WordLevelDiff( $orig, $closing );
2000 $del = $diff->orig();
2001 $add = $diff->closing();
2002
2003 # Notice that WordLevelDiff returns HTML-escaped output.
2004 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2005
2006 while ( $line = array_shift( $del ) ) {
2007 $aline = array_shift( $add );
2008 echo '<tr>' . $this->deletedLine( $line ) .
2009 $this->addedLine( $aline ) . "</tr>\n";
2010 }
2011 foreach ($add as $line) { # If any leftovers
2012 echo '<tr>' . $this->emptyLine() .
2013 $this->addedLine( $line ) . "</tr>\n";
2014 }
2015 wfProfileOut( $fname );
2016 }
2017 }
2018
2019
2020