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