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