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