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