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