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