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