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