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