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