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