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