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