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