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