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