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