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