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