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