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