* Small cleanups
[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 // Set assorted variables
643 $timestamp = $wgLang->timeanddate( $this->mNewRev->getTimestamp(), true );
644 $this->mNewPage = $this->mNewRev->getTitle();
645 if( $this->mNewRev->isCurrent() ) {
646 $newLink = $this->mNewPage->escapeLocalUrl();
647 $this->mPagetitle = htmlspecialchars( wfMsg( 'currentrev' ) );
648 $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit' );
649
650 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a> ($timestamp)"
651 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
652
653 } else {
654 $newLink = $this->mNewPage->escapeLocalUrl( 'oldid=' . $this->mNewid );
655 $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid );
656 $this->mPagetitle = wfMsgHTML( 'revisionasof', $timestamp );
657
658 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>"
659 . " (<a href='$newEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
660 }
661 if ( !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) {
662 $this->mNewtitle = "<span class='history-deleted'>{$this->mPagetitle}</span>";
663 } else if ( $this->mNewRev->isDeleted(Revision::DELETED_TEXT) ) {
664 $this->mNewtitle = '<span class="history-deleted">'.$this->mNewtitle.'</span>';
665 }
666
667 // Load the old revision object
668 $this->mOldRev = false;
669 if( $this->mOldid ) {
670 $this->mOldRev = Revision::newFromId( $this->mOldid );
671 } elseif ( $this->mOldid === 0 ) {
672 $rev = $this->mNewRev->getPrevious();
673 if( $rev ) {
674 $this->mOldid = $rev->getId();
675 $this->mOldRev = $rev;
676 } else {
677 // No previous revision; mark to show as first-version only.
678 $this->mOldid = false;
679 $this->mOldRev = false;
680 }
681 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
682
683 if( is_null( $this->mOldRev ) ) {
684 return false;
685 }
686
687 if ( $this->mOldRev ) {
688 $this->mOldPage = $this->mOldRev->getTitle();
689
690 $t = $wgLang->timeanddate( $this->mOldRev->getTimestamp(), true );
691 $oldLink = $this->mOldPage->escapeLocalUrl( 'oldid=' . $this->mOldid );
692 $oldEdit = $this->mOldPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid );
693 $this->mOldPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $t ) );
694
695 $this->mOldtitle = "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
696 . " (<a href='$oldEdit'>" . htmlspecialchars( wfMsg( 'editold' ) ) . "</a>)";
697 // Add an "undo" link
698 $newUndo = $this->mNewPage->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid . '&undo=' . $this->mNewid);
699 if ( $this->mNewRev->userCan(Revision::DELETED_TEXT) )
700 $this->mNewtitle .= " (<a href='$newUndo'>" . htmlspecialchars( wfMsg( 'editundo' ) ) . "</a>)";
701
702 if ( !$this->mOldRev->userCan(Revision::DELETED_TEXT) ) {
703 $this->mOldtitle = "<span class='history-deleted'>{$this->mOldPagetitle}</span>";
704 } else if ( $this->mOldRev->isDeleted(Revision::DELETED_TEXT) ) {
705 $this->mOldtitle = '<span class="history-deleted">'.$this->mOldtitle.'</span>';
706 }
707 }
708
709 return true;
710 }
711
712 /**
713 * Load the text of the revisions, as well as revision data.
714 */
715 function loadText() {
716 if ( $this->mTextLoaded == 2 ) {
717 return true;
718 } else {
719 // Whether it succeeds or fails, we don't want to try again
720 $this->mTextLoaded = 2;
721 }
722
723 if ( !$this->loadRevisionData() ) {
724 return false;
725 }
726 if ( $this->mOldRev ) {
727 $this->mOldtext = $this->mOldRev->revText();
728 if ( $this->mOldtext === false ) {
729 return false;
730 }
731 }
732 if ( $this->mNewRev ) {
733 $this->mNewtext = $this->mNewRev->revText();
734 if ( $this->mNewtext === false ) {
735 return false;
736 }
737 }
738 return true;
739 }
740
741 /**
742 * Load the text of the new revision, not the old one
743 */
744 function loadNewText() {
745 if ( $this->mTextLoaded >= 1 ) {
746 return true;
747 } else {
748 $this->mTextLoaded = 1;
749 }
750 if ( !$this->loadRevisionData() ) {
751 return false;
752 }
753 $this->mNewtext = $this->mNewRev->getText();
754 return true;
755 }
756
757
758 }
759
760 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
761 //
762 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
763 // You may copy this code freely under the conditions of the GPL.
764 //
765
766 define('USE_ASSERTS', function_exists('assert'));
767
768 /**
769 * @todo document
770 * @private
771 * @addtogroup DifferenceEngine
772 */
773 class _DiffOp {
774 var $type;
775 var $orig;
776 var $closing;
777
778 function reverse() {
779 trigger_error('pure virtual', E_USER_ERROR);
780 }
781
782 function norig() {
783 return $this->orig ? sizeof($this->orig) : 0;
784 }
785
786 function nclosing() {
787 return $this->closing ? sizeof($this->closing) : 0;
788 }
789 }
790
791 /**
792 * @todo document
793 * @private
794 * @addtogroup DifferenceEngine
795 */
796 class _DiffOp_Copy extends _DiffOp {
797 var $type = 'copy';
798
799 function _DiffOp_Copy ($orig, $closing = false) {
800 if (!is_array($closing))
801 $closing = $orig;
802 $this->orig = $orig;
803 $this->closing = $closing;
804 }
805
806 function reverse() {
807 return new _DiffOp_Copy($this->closing, $this->orig);
808 }
809 }
810
811 /**
812 * @todo document
813 * @private
814 * @addtogroup DifferenceEngine
815 */
816 class _DiffOp_Delete extends _DiffOp {
817 var $type = 'delete';
818
819 function _DiffOp_Delete ($lines) {
820 $this->orig = $lines;
821 $this->closing = false;
822 }
823
824 function reverse() {
825 return new _DiffOp_Add($this->orig);
826 }
827 }
828
829 /**
830 * @todo document
831 * @private
832 * @addtogroup DifferenceEngine
833 */
834 class _DiffOp_Add extends _DiffOp {
835 var $type = 'add';
836
837 function _DiffOp_Add ($lines) {
838 $this->closing = $lines;
839 $this->orig = false;
840 }
841
842 function reverse() {
843 return new _DiffOp_Delete($this->closing);
844 }
845 }
846
847 /**
848 * @todo document
849 * @private
850 * @addtogroup DifferenceEngine
851 */
852 class _DiffOp_Change extends _DiffOp {
853 var $type = 'change';
854
855 function _DiffOp_Change ($orig, $closing) {
856 $this->orig = $orig;
857 $this->closing = $closing;
858 }
859
860 function reverse() {
861 return new _DiffOp_Change($this->closing, $this->orig);
862 }
863 }
864
865
866 /**
867 * Class used internally by Diff to actually compute the diffs.
868 *
869 * The algorithm used here is mostly lifted from the perl module
870 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
871 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
872 *
873 * More ideas are taken from:
874 * http://www.ics.uci.edu/~eppstein/161/960229.html
875 *
876 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
877 * diffutils-2.7, which can be found at:
878 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
879 *
880 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
881 * are my own.
882 *
883 * Line length limits for robustness added by Tim Starling, 2005-08-31
884 *
885 * @author Geoffrey T. Dairiki, Tim Starling
886 * @private
887 * @addtogroup DifferenceEngine
888 */
889 class _DiffEngine {
890 const MAX_XREF_LENGTH = 10000;
891
892 function diff ($from_lines, $to_lines) {
893 wfProfileIn( __METHOD__ );
894
895 $n_from = sizeof($from_lines);
896 $n_to = sizeof($to_lines);
897
898 $this->xchanged = $this->ychanged = array();
899 $this->xv = $this->yv = array();
900 $this->xind = $this->yind = array();
901 unset($this->seq);
902 unset($this->in_seq);
903 unset($this->lcs);
904
905 // Skip leading common lines.
906 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
907 if ($from_lines[$skip] !== $to_lines[$skip])
908 break;
909 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
910 }
911 // Skip trailing common lines.
912 $xi = $n_from; $yi = $n_to;
913 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
914 if ($from_lines[$xi] !== $to_lines[$yi])
915 break;
916 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
917 }
918
919 // Ignore lines which do not exist in both files.
920 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
921 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
922 }
923
924 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
925 $line = $to_lines[$yi];
926 if ( ($this->ychanged[$yi] = empty($xhash[$this->_line_hash($line)])) )
927 continue;
928 $yhash[$this->_line_hash($line)] = 1;
929 $this->yv[] = $line;
930 $this->yind[] = $yi;
931 }
932 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
933 $line = $from_lines[$xi];
934 if ( ($this->xchanged[$xi] = empty($yhash[$this->_line_hash($line)])) )
935 continue;
936 $this->xv[] = $line;
937 $this->xind[] = $xi;
938 }
939
940 // Find the LCS.
941 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
942
943 // Merge edits when possible
944 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
945 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
946
947 // Compute the edit operations.
948 $edits = array();
949 $xi = $yi = 0;
950 while ($xi < $n_from || $yi < $n_to) {
951 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
952 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
953
954 // Skip matching "snake".
955 $copy = array();
956 while ( $xi < $n_from && $yi < $n_to
957 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
958 $copy[] = $from_lines[$xi++];
959 ++$yi;
960 }
961 if ($copy)
962 $edits[] = new _DiffOp_Copy($copy);
963
964 // Find deletes & adds.
965 $delete = array();
966 while ($xi < $n_from && $this->xchanged[$xi])
967 $delete[] = $from_lines[$xi++];
968
969 $add = array();
970 while ($yi < $n_to && $this->ychanged[$yi])
971 $add[] = $to_lines[$yi++];
972
973 if ($delete && $add)
974 $edits[] = new _DiffOp_Change($delete, $add);
975 elseif ($delete)
976 $edits[] = new _DiffOp_Delete($delete);
977 elseif ($add)
978 $edits[] = new _DiffOp_Add($add);
979 }
980 wfProfileOut( __METHOD__ );
981 return $edits;
982 }
983
984 /**
985 * Returns the whole line if it's small enough, or the MD5 hash otherwise
986 */
987 function _line_hash( $line ) {
988 if ( strlen( $line ) > self::MAX_XREF_LENGTH ) {
989 return md5( $line );
990 } else {
991 return $line;
992 }
993 }
994
995
996 /* Divide the Largest Common Subsequence (LCS) of the sequences
997 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
998 * sized segments.
999 *
1000 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1001 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1002 * sub sequences. The first sub-sequence is contained in [X0, X1),
1003 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1004 * that (X0, Y0) == (XOFF, YOFF) and
1005 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1006 *
1007 * This function assumes that the first lines of the specified portions
1008 * of the two files do not match, and likewise that the last lines do not
1009 * match. The caller must trim matching lines from the beginning and end
1010 * of the portions it is going to specify.
1011 */
1012 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1013 wfProfileIn( __METHOD__ );
1014 $flip = false;
1015
1016 if ($xlim - $xoff > $ylim - $yoff) {
1017 // Things seems faster (I'm not sure I understand why)
1018 // when the shortest sequence in X.
1019 $flip = true;
1020 list ($xoff, $xlim, $yoff, $ylim)
1021 = array( $yoff, $ylim, $xoff, $xlim);
1022 }
1023
1024 if ($flip)
1025 for ($i = $ylim - 1; $i >= $yoff; $i--)
1026 $ymatches[$this->xv[$i]][] = $i;
1027 else
1028 for ($i = $ylim - 1; $i >= $yoff; $i--)
1029 $ymatches[$this->yv[$i]][] = $i;
1030
1031 $this->lcs = 0;
1032 $this->seq[0]= $yoff - 1;
1033 $this->in_seq = array();
1034 $ymids[0] = array();
1035
1036 $numer = $xlim - $xoff + $nchunks - 1;
1037 $x = $xoff;
1038 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
1039 wfProfileIn( __METHOD__ . "-chunk" );
1040 if ($chunk > 0)
1041 for ($i = 0; $i <= $this->lcs; $i++)
1042 $ymids[$i][$chunk-1] = $this->seq[$i];
1043
1044 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
1045 for ( ; $x < $x1; $x++) {
1046 $line = $flip ? $this->yv[$x] : $this->xv[$x];
1047 if (empty($ymatches[$line]))
1048 continue;
1049 $matches = $ymatches[$line];
1050 reset($matches);
1051 while (list ($junk, $y) = each($matches))
1052 if (empty($this->in_seq[$y])) {
1053 $k = $this->_lcs_pos($y);
1054 USE_ASSERTS && assert($k > 0);
1055 $ymids[$k] = $ymids[$k-1];
1056 break;
1057 }
1058 while (list ( /* $junk */, $y) = each($matches)) {
1059 if ($y > $this->seq[$k-1]) {
1060 USE_ASSERTS && assert($y < $this->seq[$k]);
1061 // Optimization: this is a common case:
1062 // next match is just replacing previous match.
1063 $this->in_seq[$this->seq[$k]] = false;
1064 $this->seq[$k] = $y;
1065 $this->in_seq[$y] = 1;
1066 } else if (empty($this->in_seq[$y])) {
1067 $k = $this->_lcs_pos($y);
1068 USE_ASSERTS && assert($k > 0);
1069 $ymids[$k] = $ymids[$k-1];
1070 }
1071 }
1072 }
1073 wfProfileOut( __METHOD__ . "-chunk" );
1074 }
1075
1076 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
1077 $ymid = $ymids[$this->lcs];
1078 for ($n = 0; $n < $nchunks - 1; $n++) {
1079 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
1080 $y1 = $ymid[$n] + 1;
1081 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
1082 }
1083 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
1084
1085 wfProfileOut( __METHOD__ );
1086 return array($this->lcs, $seps);
1087 }
1088
1089 function _lcs_pos ($ypos) {
1090 wfProfileIn( __METHOD__ );
1091
1092 $end = $this->lcs;
1093 if ($end == 0 || $ypos > $this->seq[$end]) {
1094 $this->seq[++$this->lcs] = $ypos;
1095 $this->in_seq[$ypos] = 1;
1096 wfProfileOut( __METHOD__ );
1097 return $this->lcs;
1098 }
1099
1100 $beg = 1;
1101 while ($beg < $end) {
1102 $mid = (int)(($beg + $end) / 2);
1103 if ( $ypos > $this->seq[$mid] )
1104 $beg = $mid + 1;
1105 else
1106 $end = $mid;
1107 }
1108
1109 USE_ASSERTS && assert($ypos != $this->seq[$end]);
1110
1111 $this->in_seq[$this->seq[$end]] = false;
1112 $this->seq[$end] = $ypos;
1113 $this->in_seq[$ypos] = 1;
1114 wfProfileOut( __METHOD__ );
1115 return $end;
1116 }
1117
1118 /* Find LCS of two sequences.
1119 *
1120 * The results are recorded in the vectors $this->{x,y}changed[], by
1121 * storing a 1 in the element for each line that is an insertion
1122 * or deletion (ie. is not in the LCS).
1123 *
1124 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1125 *
1126 * Note that XLIM, YLIM are exclusive bounds.
1127 * All line numbers are origin-0 and discarded lines are not counted.
1128 */
1129 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1130 wfProfileIn( __METHOD__ );
1131
1132 // Slide down the bottom initial diagonal.
1133 while ($xoff < $xlim && $yoff < $ylim
1134 && $this->xv[$xoff] == $this->yv[$yoff]) {
1135 ++$xoff;
1136 ++$yoff;
1137 }
1138
1139 // Slide up the top initial diagonal.
1140 while ($xlim > $xoff && $ylim > $yoff
1141 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
1142 --$xlim;
1143 --$ylim;
1144 }
1145
1146 if ($xoff == $xlim || $yoff == $ylim)
1147 $lcs = 0;
1148 else {
1149 // This is ad hoc but seems to work well.
1150 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1151 //$nchunks = max(2,min(8,(int)$nchunks));
1152 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
1153 list ($lcs, $seps)
1154 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1155 }
1156
1157 if ($lcs == 0) {
1158 // X and Y sequences have no common subsequence:
1159 // mark all changed.
1160 while ($yoff < $ylim)
1161 $this->ychanged[$this->yind[$yoff++]] = 1;
1162 while ($xoff < $xlim)
1163 $this->xchanged[$this->xind[$xoff++]] = 1;
1164 } else {
1165 // Use the partitions to split this problem into subproblems.
1166 reset($seps);
1167 $pt1 = $seps[0];
1168 while ($pt2 = next($seps)) {
1169 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1170 $pt1 = $pt2;
1171 }
1172 }
1173 wfProfileOut( __METHOD__ );
1174 }
1175
1176 /* Adjust inserts/deletes of identical lines to join changes
1177 * as much as possible.
1178 *
1179 * We do something when a run of changed lines include a
1180 * line at one end and has an excluded, identical line at the other.
1181 * We are free to choose which identical line is included.
1182 * `compareseq' usually chooses the one at the beginning,
1183 * but usually it is cleaner to consider the following identical line
1184 * to be the "change".
1185 *
1186 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1187 */
1188 function _shift_boundaries ($lines, &$changed, $other_changed) {
1189 wfProfileIn( __METHOD__ );
1190 $i = 0;
1191 $j = 0;
1192
1193 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
1194 $len = sizeof($lines);
1195 $other_len = sizeof($other_changed);
1196
1197 while (1) {
1198 /*
1199 * Scan forwards to find beginning of another run of changes.
1200 * Also keep track of the corresponding point in the other file.
1201 *
1202 * Throughout this code, $i and $j are adjusted together so that
1203 * the first $i elements of $changed and the first $j elements
1204 * of $other_changed both contain the same number of zeros
1205 * (unchanged lines).
1206 * Furthermore, $j is always kept so that $j == $other_len or
1207 * $other_changed[$j] == false.
1208 */
1209 while ($j < $other_len && $other_changed[$j])
1210 $j++;
1211
1212 while ($i < $len && ! $changed[$i]) {
1213 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1214 $i++; $j++;
1215 while ($j < $other_len && $other_changed[$j])
1216 $j++;
1217 }
1218
1219 if ($i == $len)
1220 break;
1221
1222 $start = $i;
1223
1224 // Find the end of this run of changes.
1225 while (++$i < $len && $changed[$i])
1226 continue;
1227
1228 do {
1229 /*
1230 * Record the length of this run of changes, so that
1231 * we can later determine whether the run has grown.
1232 */
1233 $runlength = $i - $start;
1234
1235 /*
1236 * Move the changed region back, so long as the
1237 * previous unchanged line matches the last changed one.
1238 * This merges with previous changed regions.
1239 */
1240 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1241 $changed[--$start] = 1;
1242 $changed[--$i] = false;
1243 while ($start > 0 && $changed[$start - 1])
1244 $start--;
1245 USE_ASSERTS && assert('$j > 0');
1246 while ($other_changed[--$j])
1247 continue;
1248 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1249 }
1250
1251 /*
1252 * Set CORRESPONDING to the end of the changed run, at the last
1253 * point where it corresponds to a changed run in the other file.
1254 * CORRESPONDING == LEN means no such point has been found.
1255 */
1256 $corresponding = $j < $other_len ? $i : $len;
1257
1258 /*
1259 * Move the changed region forward, so long as the
1260 * first changed line matches the following unchanged one.
1261 * This merges with following changed regions.
1262 * Do this second, so that if there are no merges,
1263 * the changed region is moved forward as far as possible.
1264 */
1265 while ($i < $len && $lines[$start] == $lines[$i]) {
1266 $changed[$start++] = false;
1267 $changed[$i++] = 1;
1268 while ($i < $len && $changed[$i])
1269 $i++;
1270
1271 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1272 $j++;
1273 if ($j < $other_len && $other_changed[$j]) {
1274 $corresponding = $i;
1275 while ($j < $other_len && $other_changed[$j])
1276 $j++;
1277 }
1278 }
1279 } while ($runlength != $i - $start);
1280
1281 /*
1282 * If possible, move the fully-merged run of changes
1283 * back to a corresponding run in the other file.
1284 */
1285 while ($corresponding < $i) {
1286 $changed[--$start] = 1;
1287 $changed[--$i] = 0;
1288 USE_ASSERTS && assert('$j > 0');
1289 while ($other_changed[--$j])
1290 continue;
1291 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1292 }
1293 }
1294 wfProfileOut( __METHOD__ );
1295 }
1296 }
1297
1298 /**
1299 * Class representing a 'diff' between two sequences of strings.
1300 * @todo document
1301 * @private
1302 * @addtogroup DifferenceEngine
1303 */
1304 class Diff
1305 {
1306 var $edits;
1307
1308 /**
1309 * Constructor.
1310 * Computes diff between sequences of strings.
1311 *
1312 * @param $from_lines array An array of strings.
1313 * (Typically these are lines from a file.)
1314 * @param $to_lines array An array of strings.
1315 */
1316 function Diff($from_lines, $to_lines) {
1317 $eng = new _DiffEngine;
1318 $this->edits = $eng->diff($from_lines, $to_lines);
1319 //$this->_check($from_lines, $to_lines);
1320 }
1321
1322 /**
1323 * Compute reversed Diff.
1324 *
1325 * SYNOPSIS:
1326 *
1327 * $diff = new Diff($lines1, $lines2);
1328 * $rev = $diff->reverse();
1329 * @return object A Diff object representing the inverse of the
1330 * original diff.
1331 */
1332 function reverse () {
1333 $rev = $this;
1334 $rev->edits = array();
1335 foreach ($this->edits as $edit) {
1336 $rev->edits[] = $edit->reverse();
1337 }
1338 return $rev;
1339 }
1340
1341 /**
1342 * Check for empty diff.
1343 *
1344 * @return bool True iff two sequences were identical.
1345 */
1346 function isEmpty () {
1347 foreach ($this->edits as $edit) {
1348 if ($edit->type != 'copy')
1349 return false;
1350 }
1351 return true;
1352 }
1353
1354 /**
1355 * Compute the length of the Longest Common Subsequence (LCS).
1356 *
1357 * This is mostly for diagnostic purposed.
1358 *
1359 * @return int The length of the LCS.
1360 */
1361 function lcs () {
1362 $lcs = 0;
1363 foreach ($this->edits as $edit) {
1364 if ($edit->type == 'copy')
1365 $lcs += sizeof($edit->orig);
1366 }
1367 return $lcs;
1368 }
1369
1370 /**
1371 * Get the original set of lines.
1372 *
1373 * This reconstructs the $from_lines parameter passed to the
1374 * constructor.
1375 *
1376 * @return array The original sequence of strings.
1377 */
1378 function orig() {
1379 $lines = array();
1380
1381 foreach ($this->edits as $edit) {
1382 if ($edit->orig)
1383 array_splice($lines, sizeof($lines), 0, $edit->orig);
1384 }
1385 return $lines;
1386 }
1387
1388 /**
1389 * Get the closing set of lines.
1390 *
1391 * This reconstructs the $to_lines parameter passed to the
1392 * constructor.
1393 *
1394 * @return array The sequence of strings.
1395 */
1396 function closing() {
1397 $lines = array();
1398
1399 foreach ($this->edits as $edit) {
1400 if ($edit->closing)
1401 array_splice($lines, sizeof($lines), 0, $edit->closing);
1402 }
1403 return $lines;
1404 }
1405
1406 /**
1407 * Check a Diff for validity.
1408 *
1409 * This is here only for debugging purposes.
1410 */
1411 function _check ($from_lines, $to_lines) {
1412 wfProfileIn( __METHOD__ );
1413 if (serialize($from_lines) != serialize($this->orig()))
1414 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
1415 if (serialize($to_lines) != serialize($this->closing()))
1416 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
1417
1418 $rev = $this->reverse();
1419 if (serialize($to_lines) != serialize($rev->orig()))
1420 trigger_error("Reversed original doesn't match", E_USER_ERROR);
1421 if (serialize($from_lines) != serialize($rev->closing()))
1422 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
1423
1424
1425 $prevtype = 'none';
1426 foreach ($this->edits as $edit) {
1427 if ( $prevtype == $edit->type )
1428 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
1429 $prevtype = $edit->type;
1430 }
1431
1432 $lcs = $this->lcs();
1433 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
1434 wfProfileOut( __METHOD__ );
1435 }
1436 }
1437
1438 /**
1439 * @todo document, bad name.
1440 * @private
1441 * @addtogroup DifferenceEngine
1442 */
1443 class MappedDiff extends Diff
1444 {
1445 /**
1446 * Constructor.
1447 *
1448 * Computes diff between sequences of strings.
1449 *
1450 * This can be used to compute things like
1451 * case-insensitve diffs, or diffs which ignore
1452 * changes in white-space.
1453 *
1454 * @param $from_lines array An array of strings.
1455 * (Typically these are lines from a file.)
1456 *
1457 * @param $to_lines array An array of strings.
1458 *
1459 * @param $mapped_from_lines array This array should
1460 * have the same size number of elements as $from_lines.
1461 * The elements in $mapped_from_lines and
1462 * $mapped_to_lines are what is actually compared
1463 * when computing the diff.
1464 *
1465 * @param $mapped_to_lines array This array should
1466 * have the same number of elements as $to_lines.
1467 */
1468 function MappedDiff($from_lines, $to_lines,
1469 $mapped_from_lines, $mapped_to_lines) {
1470 wfProfileIn( __METHOD__ );
1471
1472 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1473 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1474
1475 $this->Diff($mapped_from_lines, $mapped_to_lines);
1476
1477 $xi = $yi = 0;
1478 for ($i = 0; $i < sizeof($this->edits); $i++) {
1479 $orig = &$this->edits[$i]->orig;
1480 if (is_array($orig)) {
1481 $orig = array_slice($from_lines, $xi, sizeof($orig));
1482 $xi += sizeof($orig);
1483 }
1484
1485 $closing = &$this->edits[$i]->closing;
1486 if (is_array($closing)) {
1487 $closing = array_slice($to_lines, $yi, sizeof($closing));
1488 $yi += sizeof($closing);
1489 }
1490 }
1491 wfProfileOut( __METHOD__ );
1492 }
1493 }
1494
1495 /**
1496 * A class to format Diffs
1497 *
1498 * This class formats the diff in classic diff format.
1499 * It is intended that this class be customized via inheritance,
1500 * to obtain fancier outputs.
1501 * @todo document
1502 * @private
1503 * @addtogroup DifferenceEngine
1504 */
1505 class DiffFormatter {
1506 /**
1507 * Number of leading context "lines" to preserve.
1508 *
1509 * This should be left at zero for this class, but subclasses
1510 * may want to set this to other values.
1511 */
1512 var $leading_context_lines = 0;
1513
1514 /**
1515 * Number of trailing context "lines" to preserve.
1516 *
1517 * This should be left at zero for this class, but subclasses
1518 * may want to set this to other values.
1519 */
1520 var $trailing_context_lines = 0;
1521
1522 /**
1523 * Format a diff.
1524 *
1525 * @param $diff object A Diff object.
1526 * @return string The formatted output.
1527 */
1528 function format($diff) {
1529 wfProfileIn( __METHOD__ );
1530
1531 $xi = $yi = 1;
1532 $block = false;
1533 $context = array();
1534
1535 $nlead = $this->leading_context_lines;
1536 $ntrail = $this->trailing_context_lines;
1537
1538 $this->_start_diff();
1539
1540 foreach ($diff->edits as $edit) {
1541 if ($edit->type == 'copy') {
1542 if (is_array($block)) {
1543 if (sizeof($edit->orig) <= $nlead + $ntrail) {
1544 $block[] = $edit;
1545 }
1546 else{
1547 if ($ntrail) {
1548 $context = array_slice($edit->orig, 0, $ntrail);
1549 $block[] = new _DiffOp_Copy($context);
1550 }
1551 $this->_block($x0, $ntrail + $xi - $x0,
1552 $y0, $ntrail + $yi - $y0,
1553 $block);
1554 $block = false;
1555 }
1556 }
1557 $context = $edit->orig;
1558 }
1559 else {
1560 if (! is_array($block)) {
1561 $context = array_slice($context, sizeof($context) - $nlead);
1562 $x0 = $xi - sizeof($context);
1563 $y0 = $yi - sizeof($context);
1564 $block = array();
1565 if ($context)
1566 $block[] = new _DiffOp_Copy($context);
1567 }
1568 $block[] = $edit;
1569 }
1570
1571 if ($edit->orig)
1572 $xi += sizeof($edit->orig);
1573 if ($edit->closing)
1574 $yi += sizeof($edit->closing);
1575 }
1576
1577 if (is_array($block))
1578 $this->_block($x0, $xi - $x0,
1579 $y0, $yi - $y0,
1580 $block);
1581
1582 $end = $this->_end_diff();
1583 wfProfileOut( __METHOD__ );
1584 return $end;
1585 }
1586
1587 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1588 wfProfileIn( __METHOD__ );
1589 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1590 foreach ($edits as $edit) {
1591 if ($edit->type == 'copy')
1592 $this->_context($edit->orig);
1593 elseif ($edit->type == 'add')
1594 $this->_added($edit->closing);
1595 elseif ($edit->type == 'delete')
1596 $this->_deleted($edit->orig);
1597 elseif ($edit->type == 'change')
1598 $this->_changed($edit->orig, $edit->closing);
1599 else
1600 trigger_error('Unknown edit type', E_USER_ERROR);
1601 }
1602 $this->_end_block();
1603 wfProfileOut( __METHOD__ );
1604 }
1605
1606 function _start_diff() {
1607 ob_start();
1608 }
1609
1610 function _end_diff() {
1611 $val = ob_get_contents();
1612 ob_end_clean();
1613 return $val;
1614 }
1615
1616 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1617 if ($xlen > 1)
1618 $xbeg .= "," . ($xbeg + $xlen - 1);
1619 if ($ylen > 1)
1620 $ybeg .= "," . ($ybeg + $ylen - 1);
1621
1622 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
1623 }
1624
1625 function _start_block($header) {
1626 echo $header . "\n";
1627 }
1628
1629 function _end_block() {
1630 }
1631
1632 function _lines($lines, $prefix = ' ') {
1633 foreach ($lines as $line)
1634 echo "$prefix $line\n";
1635 }
1636
1637 function _context($lines) {
1638 $this->_lines($lines);
1639 }
1640
1641 function _added($lines) {
1642 $this->_lines($lines, '>');
1643 }
1644 function _deleted($lines) {
1645 $this->_lines($lines, '<');
1646 }
1647
1648 function _changed($orig, $closing) {
1649 $this->_deleted($orig);
1650 echo "---\n";
1651 $this->_added($closing);
1652 }
1653 }
1654
1655 /**
1656 * A formatter that outputs unified diffs
1657 * @addtogroup DifferenceEngine
1658 */
1659
1660 class UnifiedDiffFormatter extends DiffFormatter {
1661 var $leading_context_lines = 2;
1662 var $trailing_context_lines = 2;
1663
1664 function _added($lines) {
1665 $this->_lines($lines, '+');
1666 }
1667 function _deleted($lines) {
1668 $this->_lines($lines, '-');
1669 }
1670 function _changed($orig, $closing) {
1671 $this->_deleted($orig);
1672 $this->_added($closing);
1673 }
1674 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1675 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1676 }
1677 }
1678
1679 /**
1680 * A pseudo-formatter that just passes along the Diff::$edits array
1681 * @addtogroup DifferenceEngine
1682 */
1683 class ArrayDiffFormatter extends DiffFormatter {
1684 function format($diff) {
1685 $oldline = 1;
1686 $newline = 1;
1687 $retval = array();
1688 foreach($diff->edits as $edit)
1689 switch($edit->type) {
1690 case 'add':
1691 foreach($edit->closing as $l) {
1692 $retval[] = array(
1693 'action' => 'add',
1694 'new'=> $l,
1695 'newline' => $newline++
1696 );
1697 }
1698 break;
1699 case 'delete':
1700 foreach($edit->orig as $l) {
1701 $retval[] = array(
1702 'action' => 'delete',
1703 'old' => $l,
1704 'oldline' => $oldline++,
1705 );
1706 }
1707 break;
1708 case 'change':
1709 foreach($edit->orig as $i => $l) {
1710 $retval[] = array(
1711 'action' => 'change',
1712 'old' => $l,
1713 'new' => @$edit->closing[$i],
1714 'oldline' => $oldline++,
1715 'newline' => $newline++,
1716 );
1717 }
1718 break;
1719 case 'copy':
1720 $oldline += count($edit->orig);
1721 $newline += count($edit->orig);
1722 }
1723 return $retval;
1724 }
1725 }
1726
1727 /**
1728 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1729 *
1730 */
1731
1732 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1733
1734 /**
1735 * @todo document
1736 * @private
1737 * @addtogroup DifferenceEngine
1738 */
1739 class _HWLDF_WordAccumulator {
1740 function _HWLDF_WordAccumulator () {
1741 $this->_lines = array();
1742 $this->_line = '';
1743 $this->_group = '';
1744 $this->_tag = '';
1745 }
1746
1747 function _flushGroup ($new_tag) {
1748 if ($this->_group !== '') {
1749 if ($this->_tag == 'ins')
1750 $this->_line .= '<ins class="diffchange diffchange-inline">' .
1751 htmlspecialchars ( $this->_group ) . '</ins>';
1752 elseif ($this->_tag == 'del')
1753 $this->_line .= '<del class="diffchange diffchange-inline">' .
1754 htmlspecialchars ( $this->_group ) . '</del>';
1755 else
1756 $this->_line .= htmlspecialchars ( $this->_group );
1757 }
1758 $this->_group = '';
1759 $this->_tag = $new_tag;
1760 }
1761
1762 function _flushLine ($new_tag) {
1763 $this->_flushGroup($new_tag);
1764 if ($this->_line != '')
1765 array_push ( $this->_lines, $this->_line );
1766 else
1767 # make empty lines visible by inserting an NBSP
1768 array_push ( $this->_lines, NBSP );
1769 $this->_line = '';
1770 }
1771
1772 function addWords ($words, $tag = '') {
1773 if ($tag != $this->_tag)
1774 $this->_flushGroup($tag);
1775
1776 foreach ($words as $word) {
1777 // new-line should only come as first char of word.
1778 if ($word == '')
1779 continue;
1780 if ($word[0] == "\n") {
1781 $this->_flushLine($tag);
1782 $word = substr($word, 1);
1783 }
1784 assert(!strstr($word, "\n"));
1785 $this->_group .= $word;
1786 }
1787 }
1788
1789 function getLines() {
1790 $this->_flushLine('~done');
1791 return $this->_lines;
1792 }
1793 }
1794
1795 /**
1796 * @todo document
1797 * @private
1798 * @addtogroup DifferenceEngine
1799 */
1800 class WordLevelDiff extends MappedDiff {
1801 const MAX_LINE_LENGTH = 10000;
1802
1803 function WordLevelDiff ($orig_lines, $closing_lines) {
1804 wfProfileIn( __METHOD__ );
1805
1806 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1807 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1808
1809 $this->MappedDiff($orig_words, $closing_words,
1810 $orig_stripped, $closing_stripped);
1811 wfProfileOut( __METHOD__ );
1812 }
1813
1814 function _split($lines) {
1815 wfProfileIn( __METHOD__ );
1816
1817 $words = array();
1818 $stripped = array();
1819 $first = true;
1820 foreach ( $lines as $line ) {
1821 # If the line is too long, just pretend the entire line is one big word
1822 # This prevents resource exhaustion problems
1823 if ( $first ) {
1824 $first = false;
1825 } else {
1826 $words[] = "\n";
1827 $stripped[] = "\n";
1828 }
1829 if ( strlen( $line ) > self::MAX_LINE_LENGTH ) {
1830 $words[] = $line;
1831 $stripped[] = $line;
1832 } else {
1833 $m = array();
1834 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1835 $line, $m))
1836 {
1837 $words = array_merge( $words, $m[0] );
1838 $stripped = array_merge( $stripped, $m[1] );
1839 }
1840 }
1841 }
1842 wfProfileOut( __METHOD__ );
1843 return array($words, $stripped);
1844 }
1845
1846 function orig () {
1847 wfProfileIn( __METHOD__ );
1848 $orig = new _HWLDF_WordAccumulator;
1849
1850 foreach ($this->edits as $edit) {
1851 if ($edit->type == 'copy')
1852 $orig->addWords($edit->orig);
1853 elseif ($edit->orig)
1854 $orig->addWords($edit->orig, 'del');
1855 }
1856 $lines = $orig->getLines();
1857 wfProfileOut( __METHOD__ );
1858 return $lines;
1859 }
1860
1861 function closing () {
1862 wfProfileIn( __METHOD__ );
1863 $closing = new _HWLDF_WordAccumulator;
1864
1865 foreach ($this->edits as $edit) {
1866 if ($edit->type == 'copy')
1867 $closing->addWords($edit->closing);
1868 elseif ($edit->closing)
1869 $closing->addWords($edit->closing, 'ins');
1870 }
1871 $lines = $closing->getLines();
1872 wfProfileOut( __METHOD__ );
1873 return $lines;
1874 }
1875 }
1876
1877 /**
1878 * Wikipedia Table style diff formatter.
1879 * @todo document
1880 * @private
1881 * @addtogroup DifferenceEngine
1882 */
1883 class TableDiffFormatter extends DiffFormatter {
1884 function TableDiffFormatter() {
1885 $this->leading_context_lines = 2;
1886 $this->trailing_context_lines = 2;
1887 }
1888
1889 public static function escapeWhiteSpace( $msg ) {
1890 $msg = preg_replace( '/^ /m', '&nbsp; ', $msg );
1891 $msg = preg_replace( '/ $/m', ' &nbsp;', $msg );
1892 $msg = preg_replace( '/ /', '&nbsp; ', $msg );
1893 return $msg;
1894 }
1895
1896 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1897 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
1898 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
1899 return $r;
1900 }
1901
1902 function _start_block( $header ) {
1903 echo $header;
1904 }
1905
1906 function _end_block() {
1907 }
1908
1909 function _lines( $lines, $prefix=' ', $color='white' ) {
1910 }
1911
1912 # HTML-escape parameter before calling this
1913 function addedLine( $line ) {
1914 return $this->wrapLine( '+', 'diff-addedline', $line );
1915 }
1916
1917 # HTML-escape parameter before calling this
1918 function deletedLine( $line ) {
1919 return $this->wrapLine( '-', 'diff-deletedline', $line );
1920 }
1921
1922 # HTML-escape parameter before calling this
1923 function contextLine( $line ) {
1924 return $this->wrapLine( ' ', 'diff-context', $line );
1925 }
1926
1927 private function wrapLine( $marker, $class, $line ) {
1928 if( $line !== '' ) {
1929 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
1930 $line = Xml::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
1931 }
1932 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
1933 }
1934
1935 function emptyLine() {
1936 return '<td colspan="2">&nbsp;</td>';
1937 }
1938
1939 function _added( $lines ) {
1940 foreach ($lines as $line) {
1941 echo '<tr>' . $this->emptyLine() .
1942 $this->addedLine( '<ins class="diffchange">' .
1943 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
1944 }
1945 }
1946
1947 function _deleted($lines) {
1948 foreach ($lines as $line) {
1949 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
1950 htmlspecialchars ( $line ) . '</del>' ) .
1951 $this->emptyLine() . "</tr>\n";
1952 }
1953 }
1954
1955 function _context( $lines ) {
1956 foreach ($lines as $line) {
1957 echo '<tr>' .
1958 $this->contextLine( htmlspecialchars ( $line ) ) .
1959 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1960 }
1961 }
1962
1963 function _changed( $orig, $closing ) {
1964 wfProfileIn( __METHOD__ );
1965
1966 $diff = new WordLevelDiff( $orig, $closing );
1967 $del = $diff->orig();
1968 $add = $diff->closing();
1969
1970 # Notice that WordLevelDiff returns HTML-escaped output.
1971 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1972
1973 while ( $line = array_shift( $del ) ) {
1974 $aline = array_shift( $add );
1975 echo '<tr>' . $this->deletedLine( $line ) .
1976 $this->addedLine( $aline ) . "</tr>\n";
1977 }
1978 foreach ($add as $line) { # If any leftovers
1979 echo '<tr>' . $this->emptyLine() .
1980 $this->addedLine( $line ) . "</tr>\n";
1981 }
1982 wfProfileOut( __METHOD__ );
1983 }
1984 }
1985
1986
1987