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