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