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