* (bug 15196) Free external links should be numbered in a localised manner
[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->getUserText( Revision::FOR_THIS_USER ),
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, $wgUser;
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 = wfMsgHTML( 'currentrev-asof', $timestamp );
768 $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit' );
769
770 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
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 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
820 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
821 if( $editable && !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) && !$this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
822 $this->mNewtitle .= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
823 }
824
825 if( !$this->mOldRev->userCan( Revision::DELETED_TEXT ) ) {
826 $this->mOldtitle = '<span class="history-deleted">' . $this->mOldPagetitle . '</span>';
827 } else if( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
828 $this->mOldtitle = '<span class="history-deleted">' . $this->mOldtitle . '</span>';
829 }
830 }
831
832 return true;
833 }
834
835 /**
836 * Load the text of the revisions, as well as revision data.
837 */
838 function loadText() {
839 if ( $this->mTextLoaded == 2 ) {
840 return true;
841 } else {
842 // Whether it succeeds or fails, we don't want to try again
843 $this->mTextLoaded = 2;
844 }
845
846 if ( !$this->loadRevisionData() ) {
847 return false;
848 }
849 if ( $this->mOldRev ) {
850 $this->mOldtext = $this->mOldRev->getText( Revision::FOR_THIS_USER );
851 if ( $this->mOldtext === false ) {
852 return false;
853 }
854 }
855 if ( $this->mNewRev ) {
856 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
857 if ( $this->mNewtext === false ) {
858 return false;
859 }
860 }
861 return true;
862 }
863
864 /**
865 * Load the text of the new revision, not the old one
866 */
867 function loadNewText() {
868 if ( $this->mTextLoaded >= 1 ) {
869 return true;
870 } else {
871 $this->mTextLoaded = 1;
872 }
873 if ( !$this->loadRevisionData() ) {
874 return false;
875 }
876 $this->mNewtext = $this->mNewRev->getText();
877 return true;
878 }
879
880
881 }
882
883 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
884 //
885 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
886 // You may copy this code freely under the conditions of the GPL.
887 //
888
889 define('USE_ASSERTS', function_exists('assert'));
890
891 /**
892 * @todo document
893 * @private
894 * @ingroup DifferenceEngine
895 */
896 class _DiffOp {
897 var $type;
898 var $orig;
899 var $closing;
900
901 function reverse() {
902 trigger_error('pure virtual', E_USER_ERROR);
903 }
904
905 function norig() {
906 return $this->orig ? sizeof($this->orig) : 0;
907 }
908
909 function nclosing() {
910 return $this->closing ? sizeof($this->closing) : 0;
911 }
912 }
913
914 /**
915 * @todo document
916 * @private
917 * @ingroup DifferenceEngine
918 */
919 class _DiffOp_Copy extends _DiffOp {
920 var $type = 'copy';
921
922 function _DiffOp_Copy ($orig, $closing = false) {
923 if (!is_array($closing))
924 $closing = $orig;
925 $this->orig = $orig;
926 $this->closing = $closing;
927 }
928
929 function reverse() {
930 return new _DiffOp_Copy($this->closing, $this->orig);
931 }
932 }
933
934 /**
935 * @todo document
936 * @private
937 * @ingroup DifferenceEngine
938 */
939 class _DiffOp_Delete extends _DiffOp {
940 var $type = 'delete';
941
942 function _DiffOp_Delete ($lines) {
943 $this->orig = $lines;
944 $this->closing = false;
945 }
946
947 function reverse() {
948 return new _DiffOp_Add($this->orig);
949 }
950 }
951
952 /**
953 * @todo document
954 * @private
955 * @ingroup DifferenceEngine
956 */
957 class _DiffOp_Add extends _DiffOp {
958 var $type = 'add';
959
960 function _DiffOp_Add ($lines) {
961 $this->closing = $lines;
962 $this->orig = false;
963 }
964
965 function reverse() {
966 return new _DiffOp_Delete($this->closing);
967 }
968 }
969
970 /**
971 * @todo document
972 * @private
973 * @ingroup DifferenceEngine
974 */
975 class _DiffOp_Change extends _DiffOp {
976 var $type = 'change';
977
978 function _DiffOp_Change ($orig, $closing) {
979 $this->orig = $orig;
980 $this->closing = $closing;
981 }
982
983 function reverse() {
984 return new _DiffOp_Change($this->closing, $this->orig);
985 }
986 }
987
988 /**
989 * Class used internally by Diff to actually compute the diffs.
990 *
991 * The algorithm used here is mostly lifted from the perl module
992 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
993 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
994 *
995 * More ideas are taken from:
996 * http://www.ics.uci.edu/~eppstein/161/960229.html
997 *
998 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
999 * diffutils-2.7, which can be found at:
1000 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
1001 *
1002 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
1003 * are my own.
1004 *
1005 * Line length limits for robustness added by Tim Starling, 2005-08-31
1006 * Alternative implementation added by Guy Van den Broeck, 2008-07-30
1007 *
1008 * @author Geoffrey T. Dairiki, Tim Starling, Guy Van den Broeck
1009 * @private
1010 * @ingroup DifferenceEngine
1011 */
1012 class _DiffEngine {
1013
1014 const MAX_XREF_LENGTH = 10000;
1015
1016 function diff ($from_lines, $to_lines){
1017 wfProfileIn( __METHOD__ );
1018
1019 // Diff and store locally
1020 $this->diff_local($from_lines, $to_lines);
1021
1022 // Merge edits when possible
1023 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
1024 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
1025
1026 // Compute the edit operations.
1027 $n_from = sizeof($from_lines);
1028 $n_to = sizeof($to_lines);
1029
1030 $edits = array();
1031 $xi = $yi = 0;
1032 while ($xi < $n_from || $yi < $n_to) {
1033 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
1034 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
1035
1036 // Skip matching "snake".
1037 $copy = array();
1038 while ( $xi < $n_from && $yi < $n_to
1039 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
1040 $copy[] = $from_lines[$xi++];
1041 ++$yi;
1042 }
1043 if ($copy)
1044 $edits[] = new _DiffOp_Copy($copy);
1045
1046 // Find deletes & adds.
1047 $delete = array();
1048 while ($xi < $n_from && $this->xchanged[$xi])
1049 $delete[] = $from_lines[$xi++];
1050
1051 $add = array();
1052 while ($yi < $n_to && $this->ychanged[$yi])
1053 $add[] = $to_lines[$yi++];
1054
1055 if ($delete && $add)
1056 $edits[] = new _DiffOp_Change($delete, $add);
1057 elseif ($delete)
1058 $edits[] = new _DiffOp_Delete($delete);
1059 elseif ($add)
1060 $edits[] = new _DiffOp_Add($add);
1061 }
1062 wfProfileOut( __METHOD__ );
1063 return $edits;
1064 }
1065
1066 function diff_local ($from_lines, $to_lines) {
1067 global $wgExternalDiffEngine;
1068 wfProfileIn( __METHOD__);
1069
1070 if($wgExternalDiffEngine == 'wikidiff3'){
1071 // wikidiff3
1072 $wikidiff3 = new WikiDiff3();
1073 $wikidiff3->diff($from_lines, $to_lines);
1074 $this->xchanged = $wikidiff3->removed;
1075 $this->ychanged = $wikidiff3->added;
1076 unset($wikidiff3);
1077 }else{
1078 // old diff
1079 $n_from = sizeof($from_lines);
1080 $n_to = sizeof($to_lines);
1081 $this->xchanged = $this->ychanged = array();
1082 $this->xv = $this->yv = array();
1083 $this->xind = $this->yind = array();
1084 unset($this->seq);
1085 unset($this->in_seq);
1086 unset($this->lcs);
1087
1088 // Skip leading common lines.
1089 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
1090 if ($from_lines[$skip] !== $to_lines[$skip])
1091 break;
1092 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
1093 }
1094 // Skip trailing common lines.
1095 $xi = $n_from; $yi = $n_to;
1096 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
1097 if ($from_lines[$xi] !== $to_lines[$yi])
1098 break;
1099 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
1100 }
1101
1102 // Ignore lines which do not exist in both files.
1103 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
1104 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
1105 }
1106
1107 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
1108 $line = $to_lines[$yi];
1109 if ( ($this->ychanged[$yi] = empty($xhash[$this->_line_hash($line)])) )
1110 continue;
1111 $yhash[$this->_line_hash($line)] = 1;
1112 $this->yv[] = $line;
1113 $this->yind[] = $yi;
1114 }
1115 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
1116 $line = $from_lines[$xi];
1117 if ( ($this->xchanged[$xi] = empty($yhash[$this->_line_hash($line)])) )
1118 continue;
1119 $this->xv[] = $line;
1120 $this->xind[] = $xi;
1121 }
1122
1123 // Find the LCS.
1124 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
1125 }
1126 wfProfileOut( __METHOD__ );
1127 }
1128
1129 /**
1130 * Returns the whole line if it's small enough, or the MD5 hash otherwise
1131 */
1132 function _line_hash( $line ) {
1133 if ( strlen( $line ) > self::MAX_XREF_LENGTH ) {
1134 return md5( $line );
1135 } else {
1136 return $line;
1137 }
1138 }
1139
1140 /* Divide the Largest Common Subsequence (LCS) of the sequences
1141 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
1142 * sized segments.
1143 *
1144 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
1145 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
1146 * sub sequences. The first sub-sequence is contained in [X0, X1),
1147 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
1148 * that (X0, Y0) == (XOFF, YOFF) and
1149 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
1150 *
1151 * This function assumes that the first lines of the specified portions
1152 * of the two files do not match, and likewise that the last lines do not
1153 * match. The caller must trim matching lines from the beginning and end
1154 * of the portions it is going to specify.
1155 */
1156 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
1157 $flip = false;
1158
1159 if ($xlim - $xoff > $ylim - $yoff) {
1160 // Things seems faster (I'm not sure I understand why)
1161 // when the shortest sequence in X.
1162 $flip = true;
1163 list ($xoff, $xlim, $yoff, $ylim)
1164 = array( $yoff, $ylim, $xoff, $xlim);
1165 }
1166
1167 if ($flip)
1168 for ($i = $ylim - 1; $i >= $yoff; $i--)
1169 $ymatches[$this->xv[$i]][] = $i;
1170 else
1171 for ($i = $ylim - 1; $i >= $yoff; $i--)
1172 $ymatches[$this->yv[$i]][] = $i;
1173
1174 $this->lcs = 0;
1175 $this->seq[0]= $yoff - 1;
1176 $this->in_seq = array();
1177 $ymids[0] = array();
1178
1179 $numer = $xlim - $xoff + $nchunks - 1;
1180 $x = $xoff;
1181 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
1182 if ($chunk > 0)
1183 for ($i = 0; $i <= $this->lcs; $i++)
1184 $ymids[$i][$chunk-1] = $this->seq[$i];
1185
1186 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
1187 for ( ; $x < $x1; $x++) {
1188 $line = $flip ? $this->yv[$x] : $this->xv[$x];
1189 if (empty($ymatches[$line]))
1190 continue;
1191 $matches = $ymatches[$line];
1192 reset($matches);
1193 while (list ($junk, $y) = each($matches))
1194 if (empty($this->in_seq[$y])) {
1195 $k = $this->_lcs_pos($y);
1196 USE_ASSERTS && assert($k > 0);
1197 $ymids[$k] = $ymids[$k-1];
1198 break;
1199 }
1200 while (list ( /* $junk */, $y) = each($matches)) {
1201 if ($y > $this->seq[$k-1]) {
1202 USE_ASSERTS && assert($y < $this->seq[$k]);
1203 // Optimization: this is a common case:
1204 // next match is just replacing previous match.
1205 $this->in_seq[$this->seq[$k]] = false;
1206 $this->seq[$k] = $y;
1207 $this->in_seq[$y] = 1;
1208 } else if (empty($this->in_seq[$y])) {
1209 $k = $this->_lcs_pos($y);
1210 USE_ASSERTS && assert($k > 0);
1211 $ymids[$k] = $ymids[$k-1];
1212 }
1213 }
1214 }
1215 }
1216
1217 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
1218 $ymid = $ymids[$this->lcs];
1219 for ($n = 0; $n < $nchunks - 1; $n++) {
1220 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
1221 $y1 = $ymid[$n] + 1;
1222 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
1223 }
1224 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
1225
1226 return array($this->lcs, $seps);
1227 }
1228
1229 function _lcs_pos ($ypos) {
1230 $end = $this->lcs;
1231 if ($end == 0 || $ypos > $this->seq[$end]) {
1232 $this->seq[++$this->lcs] = $ypos;
1233 $this->in_seq[$ypos] = 1;
1234 return $this->lcs;
1235 }
1236
1237 $beg = 1;
1238 while ($beg < $end) {
1239 $mid = (int)(($beg + $end) / 2);
1240 if ( $ypos > $this->seq[$mid] )
1241 $beg = $mid + 1;
1242 else
1243 $end = $mid;
1244 }
1245
1246 USE_ASSERTS && assert($ypos != $this->seq[$end]);
1247
1248 $this->in_seq[$this->seq[$end]] = false;
1249 $this->seq[$end] = $ypos;
1250 $this->in_seq[$ypos] = 1;
1251 return $end;
1252 }
1253
1254 /* Find LCS of two sequences.
1255 *
1256 * The results are recorded in the vectors $this->{x,y}changed[], by
1257 * storing a 1 in the element for each line that is an insertion
1258 * or deletion (ie. is not in the LCS).
1259 *
1260 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
1261 *
1262 * Note that XLIM, YLIM are exclusive bounds.
1263 * All line numbers are origin-0 and discarded lines are not counted.
1264 */
1265 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
1266 // Slide down the bottom initial diagonal.
1267 while ($xoff < $xlim && $yoff < $ylim
1268 && $this->xv[$xoff] == $this->yv[$yoff]) {
1269 ++$xoff;
1270 ++$yoff;
1271 }
1272
1273 // Slide up the top initial diagonal.
1274 while ($xlim > $xoff && $ylim > $yoff
1275 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
1276 --$xlim;
1277 --$ylim;
1278 }
1279
1280 if ($xoff == $xlim || $yoff == $ylim)
1281 $lcs = 0;
1282 else {
1283 // This is ad hoc but seems to work well.
1284 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
1285 //$nchunks = max(2,min(8,(int)$nchunks));
1286 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
1287 list ($lcs, $seps)
1288 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
1289 }
1290
1291 if ($lcs == 0) {
1292 // X and Y sequences have no common subsequence:
1293 // mark all changed.
1294 while ($yoff < $ylim)
1295 $this->ychanged[$this->yind[$yoff++]] = 1;
1296 while ($xoff < $xlim)
1297 $this->xchanged[$this->xind[$xoff++]] = 1;
1298 } else {
1299 // Use the partitions to split this problem into subproblems.
1300 reset($seps);
1301 $pt1 = $seps[0];
1302 while ($pt2 = next($seps)) {
1303 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
1304 $pt1 = $pt2;
1305 }
1306 }
1307 }
1308
1309 /* Adjust inserts/deletes of identical lines to join changes
1310 * as much as possible.
1311 *
1312 * We do something when a run of changed lines include a
1313 * line at one end and has an excluded, identical line at the other.
1314 * We are free to choose which identical line is included.
1315 * `compareseq' usually chooses the one at the beginning,
1316 * but usually it is cleaner to consider the following identical line
1317 * to be the "change".
1318 *
1319 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1320 */
1321 function _shift_boundaries ($lines, &$changed, $other_changed) {
1322 wfProfileIn( __METHOD__ );
1323 $i = 0;
1324 $j = 0;
1325
1326 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
1327 $len = sizeof($lines);
1328 $other_len = sizeof($other_changed);
1329
1330 while (1) {
1331 /*
1332 * Scan forwards to find beginning of another run of changes.
1333 * Also keep track of the corresponding point in the other file.
1334 *
1335 * Throughout this code, $i and $j are adjusted together so that
1336 * the first $i elements of $changed and the first $j elements
1337 * of $other_changed both contain the same number of zeros
1338 * (unchanged lines).
1339 * Furthermore, $j is always kept so that $j == $other_len or
1340 * $other_changed[$j] == false.
1341 */
1342 while ($j < $other_len && $other_changed[$j])
1343 $j++;
1344
1345 while ($i < $len && ! $changed[$i]) {
1346 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1347 $i++; $j++;
1348 while ($j < $other_len && $other_changed[$j])
1349 $j++;
1350 }
1351
1352 if ($i == $len)
1353 break;
1354
1355 $start = $i;
1356
1357 // Find the end of this run of changes.
1358 while (++$i < $len && $changed[$i])
1359 continue;
1360
1361 do {
1362 /*
1363 * Record the length of this run of changes, so that
1364 * we can later determine whether the run has grown.
1365 */
1366 $runlength = $i - $start;
1367
1368 /*
1369 * Move the changed region back, so long as the
1370 * previous unchanged line matches the last changed one.
1371 * This merges with previous changed regions.
1372 */
1373 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1374 $changed[--$start] = 1;
1375 $changed[--$i] = false;
1376 while ($start > 0 && $changed[$start - 1])
1377 $start--;
1378 USE_ASSERTS && assert('$j > 0');
1379 while ($other_changed[--$j])
1380 continue;
1381 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1382 }
1383
1384 /*
1385 * Set CORRESPONDING to the end of the changed run, at the last
1386 * point where it corresponds to a changed run in the other file.
1387 * CORRESPONDING == LEN means no such point has been found.
1388 */
1389 $corresponding = $j < $other_len ? $i : $len;
1390
1391 /*
1392 * Move the changed region forward, so long as the
1393 * first changed line matches the following unchanged one.
1394 * This merges with following changed regions.
1395 * Do this second, so that if there are no merges,
1396 * the changed region is moved forward as far as possible.
1397 */
1398 while ($i < $len && $lines[$start] == $lines[$i]) {
1399 $changed[$start++] = false;
1400 $changed[$i++] = 1;
1401 while ($i < $len && $changed[$i])
1402 $i++;
1403
1404 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1405 $j++;
1406 if ($j < $other_len && $other_changed[$j]) {
1407 $corresponding = $i;
1408 while ($j < $other_len && $other_changed[$j])
1409 $j++;
1410 }
1411 }
1412 } while ($runlength != $i - $start);
1413
1414 /*
1415 * If possible, move the fully-merged run of changes
1416 * back to a corresponding run in the other file.
1417 */
1418 while ($corresponding < $i) {
1419 $changed[--$start] = 1;
1420 $changed[--$i] = 0;
1421 USE_ASSERTS && assert('$j > 0');
1422 while ($other_changed[--$j])
1423 continue;
1424 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1425 }
1426 }
1427 wfProfileOut( __METHOD__ );
1428 }
1429 }
1430
1431 /**
1432 * Class representing a 'diff' between two sequences of strings.
1433 * @todo document
1434 * @private
1435 * @ingroup DifferenceEngine
1436 */
1437 class Diff
1438 {
1439 var $edits;
1440
1441 /**
1442 * Constructor.
1443 * Computes diff between sequences of strings.
1444 *
1445 * @param $from_lines array An array of strings.
1446 * (Typically these are lines from a file.)
1447 * @param $to_lines array An array of strings.
1448 */
1449 function Diff($from_lines, $to_lines) {
1450 $eng = new _DiffEngine;
1451 $this->edits = $eng->diff($from_lines, $to_lines);
1452 //$this->_check($from_lines, $to_lines);
1453 }
1454
1455 /**
1456 * Compute reversed Diff.
1457 *
1458 * SYNOPSIS:
1459 *
1460 * $diff = new Diff($lines1, $lines2);
1461 * $rev = $diff->reverse();
1462 * @return object A Diff object representing the inverse of the
1463 * original diff.
1464 */
1465 function reverse () {
1466 $rev = $this;
1467 $rev->edits = array();
1468 foreach ($this->edits as $edit) {
1469 $rev->edits[] = $edit->reverse();
1470 }
1471 return $rev;
1472 }
1473
1474 /**
1475 * Check for empty diff.
1476 *
1477 * @return bool True iff two sequences were identical.
1478 */
1479 function isEmpty () {
1480 foreach ($this->edits as $edit) {
1481 if ($edit->type != 'copy')
1482 return false;
1483 }
1484 return true;
1485 }
1486
1487 /**
1488 * Compute the length of the Longest Common Subsequence (LCS).
1489 *
1490 * This is mostly for diagnostic purposed.
1491 *
1492 * @return int The length of the LCS.
1493 */
1494 function lcs () {
1495 $lcs = 0;
1496 foreach ($this->edits as $edit) {
1497 if ($edit->type == 'copy')
1498 $lcs += sizeof($edit->orig);
1499 }
1500 return $lcs;
1501 }
1502
1503 /**
1504 * Get the original set of lines.
1505 *
1506 * This reconstructs the $from_lines parameter passed to the
1507 * constructor.
1508 *
1509 * @return array The original sequence of strings.
1510 */
1511 function orig() {
1512 $lines = array();
1513
1514 foreach ($this->edits as $edit) {
1515 if ($edit->orig)
1516 array_splice($lines, sizeof($lines), 0, $edit->orig);
1517 }
1518 return $lines;
1519 }
1520
1521 /**
1522 * Get the closing set of lines.
1523 *
1524 * This reconstructs the $to_lines parameter passed to the
1525 * constructor.
1526 *
1527 * @return array The sequence of strings.
1528 */
1529 function closing() {
1530 $lines = array();
1531
1532 foreach ($this->edits as $edit) {
1533 if ($edit->closing)
1534 array_splice($lines, sizeof($lines), 0, $edit->closing);
1535 }
1536 return $lines;
1537 }
1538
1539 /**
1540 * Check a Diff for validity.
1541 *
1542 * This is here only for debugging purposes.
1543 */
1544 function _check ($from_lines, $to_lines) {
1545 wfProfileIn( __METHOD__ );
1546 if (serialize($from_lines) != serialize($this->orig()))
1547 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
1548 if (serialize($to_lines) != serialize($this->closing()))
1549 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
1550
1551 $rev = $this->reverse();
1552 if (serialize($to_lines) != serialize($rev->orig()))
1553 trigger_error("Reversed original doesn't match", E_USER_ERROR);
1554 if (serialize($from_lines) != serialize($rev->closing()))
1555 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
1556
1557
1558 $prevtype = 'none';
1559 foreach ($this->edits as $edit) {
1560 if ( $prevtype == $edit->type )
1561 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
1562 $prevtype = $edit->type;
1563 }
1564
1565 $lcs = $this->lcs();
1566 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
1567 wfProfileOut( __METHOD__ );
1568 }
1569 }
1570
1571 /**
1572 * @todo document, bad name.
1573 * @private
1574 * @ingroup DifferenceEngine
1575 */
1576 class MappedDiff extends Diff
1577 {
1578 /**
1579 * Constructor.
1580 *
1581 * Computes diff between sequences of strings.
1582 *
1583 * This can be used to compute things like
1584 * case-insensitve diffs, or diffs which ignore
1585 * changes in white-space.
1586 *
1587 * @param $from_lines array An array of strings.
1588 * (Typically these are lines from a file.)
1589 *
1590 * @param $to_lines array An array of strings.
1591 *
1592 * @param $mapped_from_lines array This array should
1593 * have the same size number of elements as $from_lines.
1594 * The elements in $mapped_from_lines and
1595 * $mapped_to_lines are what is actually compared
1596 * when computing the diff.
1597 *
1598 * @param $mapped_to_lines array This array should
1599 * have the same number of elements as $to_lines.
1600 */
1601 function MappedDiff($from_lines, $to_lines,
1602 $mapped_from_lines, $mapped_to_lines) {
1603 wfProfileIn( __METHOD__ );
1604
1605 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1606 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1607
1608 $this->Diff($mapped_from_lines, $mapped_to_lines);
1609
1610 $xi = $yi = 0;
1611 for ($i = 0; $i < sizeof($this->edits); $i++) {
1612 $orig = &$this->edits[$i]->orig;
1613 if (is_array($orig)) {
1614 $orig = array_slice($from_lines, $xi, sizeof($orig));
1615 $xi += sizeof($orig);
1616 }
1617
1618 $closing = &$this->edits[$i]->closing;
1619 if (is_array($closing)) {
1620 $closing = array_slice($to_lines, $yi, sizeof($closing));
1621 $yi += sizeof($closing);
1622 }
1623 }
1624 wfProfileOut( __METHOD__ );
1625 }
1626 }
1627
1628 /**
1629 * A class to format Diffs
1630 *
1631 * This class formats the diff in classic diff format.
1632 * It is intended that this class be customized via inheritance,
1633 * to obtain fancier outputs.
1634 * @todo document
1635 * @private
1636 * @ingroup DifferenceEngine
1637 */
1638 class DiffFormatter {
1639 /**
1640 * Number of leading context "lines" to preserve.
1641 *
1642 * This should be left at zero for this class, but subclasses
1643 * may want to set this to other values.
1644 */
1645 var $leading_context_lines = 0;
1646
1647 /**
1648 * Number of trailing context "lines" to preserve.
1649 *
1650 * This should be left at zero for this class, but subclasses
1651 * may want to set this to other values.
1652 */
1653 var $trailing_context_lines = 0;
1654
1655 /**
1656 * Format a diff.
1657 *
1658 * @param $diff object A Diff object.
1659 * @return string The formatted output.
1660 */
1661 function format($diff) {
1662 wfProfileIn( __METHOD__ );
1663
1664 $xi = $yi = 1;
1665 $block = false;
1666 $context = array();
1667
1668 $nlead = $this->leading_context_lines;
1669 $ntrail = $this->trailing_context_lines;
1670
1671 $this->_start_diff();
1672
1673 foreach ($diff->edits as $edit) {
1674 if ($edit->type == 'copy') {
1675 if (is_array($block)) {
1676 if (sizeof($edit->orig) <= $nlead + $ntrail) {
1677 $block[] = $edit;
1678 }
1679 else{
1680 if ($ntrail) {
1681 $context = array_slice($edit->orig, 0, $ntrail);
1682 $block[] = new _DiffOp_Copy($context);
1683 }
1684 $this->_block($x0, $ntrail + $xi - $x0,
1685 $y0, $ntrail + $yi - $y0,
1686 $block);
1687 $block = false;
1688 }
1689 }
1690 $context = $edit->orig;
1691 }
1692 else {
1693 if (! is_array($block)) {
1694 $context = array_slice($context, sizeof($context) - $nlead);
1695 $x0 = $xi - sizeof($context);
1696 $y0 = $yi - sizeof($context);
1697 $block = array();
1698 if ($context)
1699 $block[] = new _DiffOp_Copy($context);
1700 }
1701 $block[] = $edit;
1702 }
1703
1704 if ($edit->orig)
1705 $xi += sizeof($edit->orig);
1706 if ($edit->closing)
1707 $yi += sizeof($edit->closing);
1708 }
1709
1710 if (is_array($block))
1711 $this->_block($x0, $xi - $x0,
1712 $y0, $yi - $y0,
1713 $block);
1714
1715 $end = $this->_end_diff();
1716 wfProfileOut( __METHOD__ );
1717 return $end;
1718 }
1719
1720 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1721 wfProfileIn( __METHOD__ );
1722 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1723 foreach ($edits as $edit) {
1724 if ($edit->type == 'copy')
1725 $this->_context($edit->orig);
1726 elseif ($edit->type == 'add')
1727 $this->_added($edit->closing);
1728 elseif ($edit->type == 'delete')
1729 $this->_deleted($edit->orig);
1730 elseif ($edit->type == 'change')
1731 $this->_changed($edit->orig, $edit->closing);
1732 else
1733 trigger_error('Unknown edit type', E_USER_ERROR);
1734 }
1735 $this->_end_block();
1736 wfProfileOut( __METHOD__ );
1737 }
1738
1739 function _start_diff() {
1740 ob_start();
1741 }
1742
1743 function _end_diff() {
1744 $val = ob_get_contents();
1745 ob_end_clean();
1746 return $val;
1747 }
1748
1749 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1750 if ($xlen > 1)
1751 $xbeg .= "," . ($xbeg + $xlen - 1);
1752 if ($ylen > 1)
1753 $ybeg .= "," . ($ybeg + $ylen - 1);
1754
1755 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
1756 }
1757
1758 function _start_block($header) {
1759 echo $header . "\n";
1760 }
1761
1762 function _end_block() {
1763 }
1764
1765 function _lines($lines, $prefix = ' ') {
1766 foreach ($lines as $line)
1767 echo "$prefix $line\n";
1768 }
1769
1770 function _context($lines) {
1771 $this->_lines($lines);
1772 }
1773
1774 function _added($lines) {
1775 $this->_lines($lines, '>');
1776 }
1777 function _deleted($lines) {
1778 $this->_lines($lines, '<');
1779 }
1780
1781 function _changed($orig, $closing) {
1782 $this->_deleted($orig);
1783 echo "---\n";
1784 $this->_added($closing);
1785 }
1786 }
1787
1788 /**
1789 * A formatter that outputs unified diffs
1790 * @ingroup DifferenceEngine
1791 */
1792
1793 class UnifiedDiffFormatter extends DiffFormatter {
1794 var $leading_context_lines = 2;
1795 var $trailing_context_lines = 2;
1796
1797 function _added($lines) {
1798 $this->_lines($lines, '+');
1799 }
1800 function _deleted($lines) {
1801 $this->_lines($lines, '-');
1802 }
1803 function _changed($orig, $closing) {
1804 $this->_deleted($orig);
1805 $this->_added($closing);
1806 }
1807 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1808 return "@@ -$xbeg,$xlen +$ybeg,$ylen @@";
1809 }
1810 }
1811
1812 /**
1813 * A pseudo-formatter that just passes along the Diff::$edits array
1814 * @ingroup DifferenceEngine
1815 */
1816 class ArrayDiffFormatter extends DiffFormatter {
1817 function format($diff) {
1818 $oldline = 1;
1819 $newline = 1;
1820 $retval = array();
1821 foreach($diff->edits as $edit)
1822 switch($edit->type) {
1823 case 'add':
1824 foreach($edit->closing as $l) {
1825 $retval[] = array(
1826 'action' => 'add',
1827 'new'=> $l,
1828 'newline' => $newline++
1829 );
1830 }
1831 break;
1832 case 'delete':
1833 foreach($edit->orig as $l) {
1834 $retval[] = array(
1835 'action' => 'delete',
1836 'old' => $l,
1837 'oldline' => $oldline++,
1838 );
1839 }
1840 break;
1841 case 'change':
1842 foreach($edit->orig as $i => $l) {
1843 $retval[] = array(
1844 'action' => 'change',
1845 'old' => $l,
1846 'new' => @$edit->closing[$i],
1847 'oldline' => $oldline++,
1848 'newline' => $newline++,
1849 );
1850 }
1851 break;
1852 case 'copy':
1853 $oldline += count($edit->orig);
1854 $newline += count($edit->orig);
1855 }
1856 return $retval;
1857 }
1858 }
1859
1860 /**
1861 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1862 *
1863 */
1864
1865 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1866
1867 /**
1868 * @todo document
1869 * @private
1870 * @ingroup DifferenceEngine
1871 */
1872 class _HWLDF_WordAccumulator {
1873 function _HWLDF_WordAccumulator () {
1874 $this->_lines = array();
1875 $this->_line = '';
1876 $this->_group = '';
1877 $this->_tag = '';
1878 }
1879
1880 function _flushGroup ($new_tag) {
1881 if ($this->_group !== '') {
1882 if ($this->_tag == 'ins')
1883 $this->_line .= '<ins class="diffchange diffchange-inline">' .
1884 htmlspecialchars ( $this->_group ) . '</ins>';
1885 elseif ($this->_tag == 'del')
1886 $this->_line .= '<del class="diffchange diffchange-inline">' .
1887 htmlspecialchars ( $this->_group ) . '</del>';
1888 else
1889 $this->_line .= htmlspecialchars ( $this->_group );
1890 }
1891 $this->_group = '';
1892 $this->_tag = $new_tag;
1893 }
1894
1895 function _flushLine ($new_tag) {
1896 $this->_flushGroup($new_tag);
1897 if ($this->_line != '')
1898 array_push ( $this->_lines, $this->_line );
1899 else
1900 # make empty lines visible by inserting an NBSP
1901 array_push ( $this->_lines, NBSP );
1902 $this->_line = '';
1903 }
1904
1905 function addWords ($words, $tag = '') {
1906 if ($tag != $this->_tag)
1907 $this->_flushGroup($tag);
1908
1909 foreach ($words as $word) {
1910 // new-line should only come as first char of word.
1911 if ($word == '')
1912 continue;
1913 if ($word[0] == "\n") {
1914 $this->_flushLine($tag);
1915 $word = substr($word, 1);
1916 }
1917 assert(!strstr($word, "\n"));
1918 $this->_group .= $word;
1919 }
1920 }
1921
1922 function getLines() {
1923 $this->_flushLine('~done');
1924 return $this->_lines;
1925 }
1926 }
1927
1928 /**
1929 * @todo document
1930 * @private
1931 * @ingroup DifferenceEngine
1932 */
1933 class WordLevelDiff extends MappedDiff {
1934 const MAX_LINE_LENGTH = 10000;
1935
1936 function WordLevelDiff ($orig_lines, $closing_lines) {
1937 wfProfileIn( __METHOD__ );
1938
1939 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1940 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1941
1942 $this->MappedDiff($orig_words, $closing_words,
1943 $orig_stripped, $closing_stripped);
1944 wfProfileOut( __METHOD__ );
1945 }
1946
1947 function _split($lines) {
1948 wfProfileIn( __METHOD__ );
1949
1950 $words = array();
1951 $stripped = array();
1952 $first = true;
1953 foreach ( $lines as $line ) {
1954 # If the line is too long, just pretend the entire line is one big word
1955 # This prevents resource exhaustion problems
1956 if ( $first ) {
1957 $first = false;
1958 } else {
1959 $words[] = "\n";
1960 $stripped[] = "\n";
1961 }
1962 if ( strlen( $line ) > self::MAX_LINE_LENGTH ) {
1963 $words[] = $line;
1964 $stripped[] = $line;
1965 } else {
1966 $m = array();
1967 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1968 $line, $m))
1969 {
1970 $words = array_merge( $words, $m[0] );
1971 $stripped = array_merge( $stripped, $m[1] );
1972 }
1973 }
1974 }
1975 wfProfileOut( __METHOD__ );
1976 return array($words, $stripped);
1977 }
1978
1979 function orig () {
1980 wfProfileIn( __METHOD__ );
1981 $orig = new _HWLDF_WordAccumulator;
1982
1983 foreach ($this->edits as $edit) {
1984 if ($edit->type == 'copy')
1985 $orig->addWords($edit->orig);
1986 elseif ($edit->orig)
1987 $orig->addWords($edit->orig, 'del');
1988 }
1989 $lines = $orig->getLines();
1990 wfProfileOut( __METHOD__ );
1991 return $lines;
1992 }
1993
1994 function closing () {
1995 wfProfileIn( __METHOD__ );
1996 $closing = new _HWLDF_WordAccumulator;
1997
1998 foreach ($this->edits as $edit) {
1999 if ($edit->type == 'copy')
2000 $closing->addWords($edit->closing);
2001 elseif ($edit->closing)
2002 $closing->addWords($edit->closing, 'ins');
2003 }
2004 $lines = $closing->getLines();
2005 wfProfileOut( __METHOD__ );
2006 return $lines;
2007 }
2008 }
2009
2010 /**
2011 * Wikipedia Table style diff formatter.
2012 * @todo document
2013 * @private
2014 * @ingroup DifferenceEngine
2015 */
2016 class TableDiffFormatter extends DiffFormatter {
2017 function TableDiffFormatter() {
2018 $this->leading_context_lines = 2;
2019 $this->trailing_context_lines = 2;
2020 }
2021
2022 public static function escapeWhiteSpace( $msg ) {
2023 $msg = preg_replace( '/^ /m', '&nbsp; ', $msg );
2024 $msg = preg_replace( '/ $/m', ' &nbsp;', $msg );
2025 $msg = preg_replace( '/ /', '&nbsp; ', $msg );
2026 return $msg;
2027 }
2028
2029 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
2030 $r = '<tr><td colspan="2" class="diff-lineno"><!--LINE '.$xbeg."--></td>\n" .
2031 '<td colspan="2" class="diff-lineno"><!--LINE '.$ybeg."--></td></tr>\n";
2032 return $r;
2033 }
2034
2035 function _start_block( $header ) {
2036 echo $header;
2037 }
2038
2039 function _end_block() {
2040 }
2041
2042 function _lines( $lines, $prefix=' ', $color='white' ) {
2043 }
2044
2045 # HTML-escape parameter before calling this
2046 function addedLine( $line ) {
2047 return $this->wrapLine( '+', 'diff-addedline', $line );
2048 }
2049
2050 # HTML-escape parameter before calling this
2051 function deletedLine( $line ) {
2052 return $this->wrapLine( '-', 'diff-deletedline', $line );
2053 }
2054
2055 # HTML-escape parameter before calling this
2056 function contextLine( $line ) {
2057 return $this->wrapLine( ' ', 'diff-context', $line );
2058 }
2059
2060 private function wrapLine( $marker, $class, $line ) {
2061 if( $line !== '' ) {
2062 // The <div> wrapper is needed for 'overflow: auto' style to scroll properly
2063 $line = Xml::tags( 'div', null, $this->escapeWhiteSpace( $line ) );
2064 }
2065 return "<td class='diff-marker'>$marker</td><td class='$class'>$line</td>";
2066 }
2067
2068 function emptyLine() {
2069 return '<td colspan="2">&nbsp;</td>';
2070 }
2071
2072 function _added( $lines ) {
2073 foreach ($lines as $line) {
2074 echo '<tr>' . $this->emptyLine() .
2075 $this->addedLine( '<ins class="diffchange">' .
2076 htmlspecialchars ( $line ) . '</ins>' ) . "</tr>\n";
2077 }
2078 }
2079
2080 function _deleted($lines) {
2081 foreach ($lines as $line) {
2082 echo '<tr>' . $this->deletedLine( '<del class="diffchange">' .
2083 htmlspecialchars ( $line ) . '</del>' ) .
2084 $this->emptyLine() . "</tr>\n";
2085 }
2086 }
2087
2088 function _context( $lines ) {
2089 foreach ($lines as $line) {
2090 echo '<tr>' .
2091 $this->contextLine( htmlspecialchars ( $line ) ) .
2092 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
2093 }
2094 }
2095
2096 function _changed( $orig, $closing ) {
2097 wfProfileIn( __METHOD__ );
2098
2099 $diff = new WordLevelDiff( $orig, $closing );
2100 $del = $diff->orig();
2101 $add = $diff->closing();
2102
2103 # Notice that WordLevelDiff returns HTML-escaped output.
2104 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
2105
2106 while ( $line = array_shift( $del ) ) {
2107 $aline = array_shift( $add );
2108 echo '<tr>' . $this->deletedLine( $line ) .
2109 $this->addedLine( $aline ) . "</tr>\n";
2110 }
2111 foreach ($add as $line) { # If any leftovers
2112 echo '<tr>' . $this->emptyLine() .
2113 $this->addedLine( $line ) . "</tr>\n";
2114 }
2115 wfProfileOut( __METHOD__ );
2116 }
2117 }