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