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