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