3 * User interface for the difference engine
6 * @ingroup DifferenceEngine
10 * Constant to indicate diff cache compatibility.
11 * Bump this when changing the diff formatting in a way that
12 * fixes important bugs or such to force cached diff views to
15 define( 'MW_DIFF_VERSION', '1.11a' );
19 * @ingroup DifferenceEngine
21 class DifferenceEngine
{
26 var $mOldtext, $mNewtext;
32 var $mOldPage, $mNewPage, $mTitle;
33 var $mRcidMarkPatrolled;
38 var $mOldRev, $mNewRev;
39 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
40 var $mRevisionsLoaded = false; // Have the revisions been loaded
41 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
42 var $mCacheHit = false; // Was the diff fetched from cache?
45 * Set this to true to add debug info to the HTML output.
46 * Warning: this may cause RSS readers to spuriously mark articles as "new"
49 var $enableDebugComment = false;
51 // If true, line X is not displayed when X is 1, for example to increase
52 // readability and conserve space with many small diffs.
53 protected $mReducedLineNumbers = false;
55 // Link to action=markpatrolled
56 protected $mMarkPatrolledLink = null;
58 protected $unhide = false; # show rev_deleted content if allowed
63 * @param $titleObj Title object that the diff is associated with
64 * @param $old Integer old ID we want to show and diff with.
65 * @param $new String either 'prev' or 'next'.
66 * @param $rcid Integer ??? FIXME (default 0)
67 * @param $refreshCache boolean If set, refreshes the diff cache
68 * @param $unhide boolean If set, allow viewing deleted revs
70 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0,
71 $refreshCache = false, $unhide = false )
74 $this->mTitle
= $titleObj;
77 $this->mTitle
= $wgTitle; // @TODO: get rid of this
79 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
83 $this->mRcidMarkPatrolled
= intval( $rcid ); # force it to be an integer
84 $this->mRefreshCache
= $refreshCache;
85 $this->unhide
= $unhide;
91 function setReducedLineNumbers( $value = true ) {
92 $this->mReducedLineNumbers
= $value;
98 function getDiffLang() {
99 if ( $this->mDiffLang
=== null ) {
100 # Default language in which the diff text is written.
101 $this->mDiffLang
= $this->mTitle
->getPageLanguage();
103 return $this->mDiffLang
;
109 function getTitle() {
110 return $this->mTitle
;
116 function wasCacheHit() {
117 return $this->mCacheHit
;
123 function getOldid() {
124 $this->loadRevisionIds();
125 return $this->mOldid
;
131 function getNewid() {
132 $this->loadRevisionIds();
133 return $this->mNewid
;
137 * Look up a special:Undelete link to the given deleted revision id,
138 * as a workaround for being unable to load deleted diffs in currently.
140 * @param int $id revision ID
141 * @return mixed URL or false
143 function deletedLink( $id ) {
145 if ( $wgUser->isAllowed( 'deletedhistory' ) ) {
146 $dbr = wfGetDB( DB_SLAVE
);
147 $row = $dbr->selectRow('archive', '*',
148 array( 'ar_rev_id' => $id ),
151 $rev = Revision
::newFromArchiveRow( $row );
152 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
153 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
154 'target' => $title->getPrefixedText(),
155 'timestamp' => $rev->getTimestamp()
163 * Build a wikitext link toward a deleted revision, if viewable.
165 * @param int $id revision ID
166 * @return string wikitext fragment
168 function deletedIdMarker( $id ) {
169 $link = $this->deletedLink( $id );
171 return "[$link $id]";
177 function showDiffPage( $diffOnly = false ) {
178 global $wgUser, $wgOut, $wgRequest, $wgUseExternalEditor;
179 wfProfileIn( __METHOD__
);
181 # Allow frames except in certain special cases
182 $wgOut->allowClickjacking();
183 $wgOut->setRobotPolicy( 'noindex,nofollow' );
185 if ( !$this->loadRevisionData() ) {
186 // Sounds like a deleted revision... Let's see what we can do.
187 $t = $this->mTitle
->getPrefixedText();
188 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ),
189 $this->deletedIdMarker( $this->mOldid
),
190 $this->deletedIdMarker( $this->mNewid
) );
191 $wgOut->setPageTitle( wfMessage( 'errorpagetitle' ) );
192 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
193 wfProfileOut( __METHOD__
);
197 # mOldPage might not be set, see below.
198 if ( !$this->mNewPage
->userCanRead() ||
( $this->mOldPage
&& !$this->mOldPage
->userCanRead() ) ) {
199 wfProfileOut( __METHOD__
);
200 throw new PermissionsError( 'read' );
203 # If external diffs are enabled both globally and for the user,
204 # we'll use the application/x-external-editor interface to call
205 # an external diff tool like kompare, kdiff3, etc.
206 if ( $wgUseExternalEditor && $wgUser->getOption( 'externaldiff' ) ) {
207 global $wgCanonicalServer, $wgScript, $wgLang;
209 header ( "Content-type: application/x-external-editor; charset=UTF-8" );
210 # This should be mOldPage, but it may not be set, see below.
211 $url1 = $this->mNewPage
->getCanonicalURL( array(
213 'oldid' => $this->mOldid
215 $url2 = $this->mNewPage
->getCanonicalURL( array(
217 'oldid' => $this->mNewid
219 $special = $wgLang->getNsText( NS_SPECIAL
);
220 $control = <<<CONTROL
224 Script={$wgCanonicalServer}{$wgScript}
225 Special namespace={$special}
237 wfProfileOut( __METHOD__
);
245 # Carry over 'diffonly' param via navigation links
246 if ( $diffOnly != $wgUser->getBoolOption( 'diffonly' ) ) {
247 $query['diffonly'] = $diffOnly;
249 # Cascade unhide param in links for easy deletion browsing
250 if ( $this->unhide
) {
251 $query['unhide'] = 1;
254 # Check if one of the revisions is deleted/suppressed
255 $deleted = $suppressed = false;
256 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
);
258 # mOldRev is false if the difference engine is called with a "vague" query for
259 # a diff between a version V and its previous version V' AND the version V
260 # is the first version of that article. In that case, V' does not exist.
261 if ( $this->mOldRev
=== false ) {
262 $wgOut->setPageTitle( $this->mNewPage
->getPrefixedText() );
263 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
267 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
269 $sk = $wgUser->getSkin();
270 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
271 $sk->suppressQuickbar();
274 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
275 $wgOut->setPageTitle( $this->mNewPage
->getPrefixedText() );
276 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
279 $wgOut->setPageTitle( $this->mOldPage
->getPrefixedText() . ', ' . $this->mNewPage
->getPrefixedText() );
280 $wgOut->setSubtitle( wfMsgExt( 'difference-multipage', array( 'parseinline' ) ) );
284 if ( $samePage && $this->mNewPage
->userCan( 'edit' ) ) {
285 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback' ) ) {
286 $wgOut->preventClickjacking();
287 $rollback = '   ' . Linker
::generateRollback( $this->mNewRev
);
289 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
290 $undoLink = ' ' . wfMsgHtml( 'parentheses', Html
::element( 'a', array(
291 'href' => $this->mNewPage
->getLocalUrl( array(
293 'undoafter' => $this->mOldid
,
294 'undo' => $this->mNewid
) ),
295 'title' => Linker
::titleAttrib( 'undo' )
296 ), wfMsg( 'editundo' ) ) );
300 # Make "previous revision link"
301 if ( $samePage && $this->mOldRev
->getPrevious() ) {
302 $prevlink = Linker
::linkKnown(
304 wfMsgHtml( 'previousdiff' ),
305 array( 'id' => 'differences-prevlink' ),
306 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
309 $prevlink = ' ';
312 if ( $this->mOldRev
->isMinor() ) {
313 $oldminor = ChangesList
::flag( 'minor' );
318 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
319 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
321 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
322 '<div id="mw-diff-otitle2">' .
323 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
324 '<div id="mw-diff-otitle3">' . $oldminor .
325 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
326 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
328 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
329 $deleted = true; // old revisions text is hidden
330 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
331 $suppressed = true; // also suppressed
335 # Check if this user can see the revisions
336 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
341 # Make "next revision link"
342 # Skip next link on the top revision
343 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
344 $nextlink = Linker
::linkKnown(
346 wfMsgHtml( 'nextdiff' ),
347 array( 'id' => 'differences-nextlink' ),
348 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
351 $nextlink = ' ';
354 if ( $this->mNewRev
->isMinor() ) {
355 $newminor = ChangesList
::flag( 'minor' );
360 # Handle RevisionDelete links...
361 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
362 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
364 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
365 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
367 '<div id="mw-diff-ntitle3">' . $newminor .
368 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
369 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
371 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
372 $deleted = true; // new revisions text is hidden
373 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
374 $suppressed = true; // also suppressed
377 # If the diff cannot be shown due to a deleted revision, then output
378 # the diff header and links to unhide (if available)...
379 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
380 $this->showDiffStyle();
381 $multi = $this->getMultiNotice();
382 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
384 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
385 # Give explanation for why revision is not visible
386 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
389 # Give explanation and add a link to view the diff...
390 $link = $this->mTitle
->getFullUrl( $wgRequest->appendQueryValue( 'unhide', '1', true ) );
391 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
392 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
394 # Otherwise, output a regular diff...
396 # Add deletion notice if the user is viewing deleted content
399 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
400 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . wfMsgExt( $msg, 'parseinline' ) . "</div>\n";
402 $this->showDiff( $oldHeader, $newHeader, $notice );
404 $this->renderNewRevision();
407 wfProfileOut( __METHOD__
);
411 * Get a link to mark the change as patrolled, or '' if there's either no
412 * revision to patrol or the user is not allowed to to it.
413 * Side effect: this method will call OutputPage::preventClickjacking()
414 * when a link is builded.
418 protected function markPatrolledLink() {
419 global $wgUseRCPatrol, $wgUser, $wgOut;
421 if ( $this->mMarkPatrolledLink
=== null ) {
422 // Prepare a change patrol link, if applicable
423 if ( $wgUseRCPatrol && $this->mNewPage
->userCan( 'patrol' ) ) {
424 // If we've been given an explicit change identifier, use it; saves time
425 if ( $this->mRcidMarkPatrolled
) {
426 $rcid = $this->mRcidMarkPatrolled
;
427 $rc = RecentChange
::newFromId( $rcid );
428 // Already patrolled?
429 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
431 // Look for an unpatrolled change corresponding to this diff
432 $db = wfGetDB( DB_SLAVE
);
433 $change = RecentChange
::newFromConds(
435 // Redundant user,timestamp condition so we can use the existing index
436 'rc_user_text' => $this->mNewRev
->getRawUserText(),
437 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
438 'rc_this_oldid' => $this->mNewid
,
439 'rc_last_oldid' => $this->mOldid
,
444 if ( $change instanceof RecentChange
) {
445 $rcid = $change->mAttribs
['rc_id'];
446 $this->mRcidMarkPatrolled
= $rcid;
454 $wgOut->preventClickjacking();
455 $token = $wgUser->editToken( $rcid );
456 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
458 wfMsgHtml( 'markaspatrolleddiff' ),
461 'action' => 'markpatrolled',
467 $this->mMarkPatrolledLink
= '';
470 $this->mMarkPatrolledLink
= '';
474 return $this->mMarkPatrolledLink
;
478 * @param $rev Revision
481 protected function revisionDeleteLink( $rev ) {
484 $canHide = $wgUser->isAllowed( 'deleterevision' );
485 // Show del/undel link if:
486 // (a) the user can delete revisions, or
487 // (b) the user can view deleted revision *and* this one is deleted
488 if ( $canHide ||
( $rev->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
489 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
) ) {
490 $link = Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
493 'type' => 'revision',
494 'target' => $rev->getTitle()->getPrefixedDBkey(),
495 'ids' => $rev->getId()
497 $link = Linker
::revDeleteLink( $query,
498 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
500 $link = '   ' . $link . ' ';
506 * Show the new revision of the page.
508 function renderNewRevision() {
510 wfProfileIn( __METHOD__
);
511 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
512 # Add "current version as of X" title
513 $wgOut->addHTML( "<hr class='diff-hr' />
514 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
515 # Page content may be handled by a hooked call instead...
516 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $wgOut ) ) ) {
517 # Use the current version parser cache if applicable
519 if ( !$this->mNewRev
->isCurrent() ) {
520 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
524 $this->loadNewText();
525 $wgOut->setRevisionId( $this->mNewRev
->getId() );
526 $wgOut->setArticleFlag( true );
528 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
529 // Stolen from Article::view --AG 2007-10-11
530 // Give hooks a chance to customise the output
531 // @TODO: standardize this crap into one function
532 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mNewPage
, $wgOut ) ) ) {
533 // Wrap the whole lot in a <pre> and don't parse
535 preg_match( '!\.(css|js)$!u', $this->mNewPage
->getText(), $m );
536 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
537 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
538 $wgOut->addHTML( "\n</pre>\n" );
540 } elseif ( $pCache ) {
541 $article = new Article( $this->mNewPage
, 0 );
542 $pOutput = ParserCache
::singleton()->get( $article, $wgOut->parserOptions() );
544 $wgOut->addParserOutput( $pOutput );
546 $article->doViewParse();
549 $wgOut->addWikiTextTidy( $this->mNewtext
);
552 if ( !$this->mNewRev
->isCurrent() ) {
553 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
556 # Add redundant patrol link on bottom...
557 $wgOut->addHTML( $this->markPatrolledLink() );
559 wfProfileOut( __METHOD__
);
563 * Get the diff text, send it to $wgOut
564 * Returns false if the diff could not be generated, otherwise returns true
568 function showDiff( $otitle, $ntitle, $notice = '' ) {
570 $diff = $this->getDiff( $otitle, $ntitle, $notice );
571 if ( $diff === false ) {
572 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
575 $this->showDiffStyle();
576 $wgOut->addHTML( $diff );
582 * Add style sheets and supporting JS for diff display.
584 function showDiffStyle() {
586 $wgOut->addModuleStyles( 'mediawiki.action.history.diff' );
590 * Get complete diff table, including header
592 * @param $otitle Title: old title
593 * @param $ntitle Title: new title
594 * @param $notice String: HTML between diff header and body
597 function getDiff( $otitle, $ntitle, $notice = '' ) {
598 $body = $this->getDiffBody();
599 if ( $body === false ) {
602 $multi = $this->getMultiNotice();
603 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
608 * Get the diff table body, without header
610 * @return mixed (string/false)
612 public function getDiffBody() {
614 wfProfileIn( __METHOD__
);
615 $this->mCacheHit
= true;
616 // Check if the diff should be hidden from this user
617 if ( !$this->loadRevisionData() ) {
618 wfProfileOut( __METHOD__
);
620 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
621 wfProfileOut( __METHOD__
);
623 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
624 wfProfileOut( __METHOD__
);
628 // If mOldRev is false, it means that the
629 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
630 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
632 wfProfileOut( __METHOD__
);
637 if ( $this->mOldid
&& $this->mNewid
) {
638 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
639 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
641 if ( !$this->mRefreshCache
) {
642 $difftext = $wgMemc->get( $key );
644 wfIncrStats( 'diff_cache_hit' );
645 $difftext = $this->localiseLineNumbers( $difftext );
646 $difftext .= "\n<!-- diff cache key $key -->\n";
647 wfProfileOut( __METHOD__
);
650 } // don't try to load but save the result
652 $this->mCacheHit
= false;
654 // Loadtext is permission safe, this just clears out the diff
655 if ( !$this->loadText() ) {
656 wfProfileOut( __METHOD__
);
660 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
662 // Save to cache for 7 days
663 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
664 wfIncrStats( 'diff_uncacheable' );
665 } elseif ( $key !== false && $difftext !== false ) {
666 wfIncrStats( 'diff_cache_miss' );
667 $wgMemc->set( $key, $difftext, 7 * 86400 );
669 wfIncrStats( 'diff_uncacheable' );
671 // Replace line numbers with the text in the user's language
672 if ( $difftext !== false ) {
673 $difftext = $this->localiseLineNumbers( $difftext );
675 wfProfileOut( __METHOD__
);
680 * Make sure the proper modules are loaded before we try to
683 private function initDiffEngines() {
684 global $wgExternalDiffEngine;
685 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
686 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
687 wfDl( 'php_wikidiff' );
688 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
690 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
691 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
693 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
698 * Generate a diff, no caching
700 * @param $otext String: old text, must be already segmented
701 * @param $ntext String: new text, must be already segmented
703 function generateDiffBody( $otext, $ntext ) {
704 global $wgExternalDiffEngine, $wgContLang;
706 wfProfileIn( __METHOD__
);
708 $otext = str_replace( "\r\n", "\n", $otext );
709 $ntext = str_replace( "\r\n", "\n", $ntext );
711 $this->initDiffEngines();
713 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
714 # For historical reasons, external diff engine expects
715 # input text to be HTML-escaped already
716 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
717 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
718 wfProfileOut( __METHOD__
);
719 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
720 $this->debug( 'wikidiff1' );
723 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
724 # Better external diff engine, the 2 may some day be dropped
725 # This one does the escaping and segmenting itself
726 wfProfileIn( 'wikidiff2_do_diff' );
727 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
728 $text .= $this->debug( 'wikidiff2' );
729 wfProfileOut( 'wikidiff2_do_diff' );
730 wfProfileOut( __METHOD__
);
733 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
735 global $wgTmpDirectory;
736 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
737 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
739 $tempFile1 = fopen( $tempName1, "w" );
741 wfProfileOut( __METHOD__
);
744 $tempFile2 = fopen( $tempName2, "w" );
746 wfProfileOut( __METHOD__
);
749 fwrite( $tempFile1, $otext );
750 fwrite( $tempFile2, $ntext );
751 fclose( $tempFile1 );
752 fclose( $tempFile2 );
753 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
754 wfProfileIn( __METHOD__
. "-shellexec" );
755 $difftext = wfShellExec( $cmd );
756 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
757 wfProfileOut( __METHOD__
. "-shellexec" );
758 unlink( $tempName1 );
759 unlink( $tempName2 );
760 wfProfileOut( __METHOD__
);
765 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
766 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
767 $diffs = new Diff( $ota, $nta );
768 $formatter = new TableDiffFormatter();
769 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
770 wfProfileOut( __METHOD__
);
775 * Generate a debug comment indicating diff generating time,
776 * server node, and generator backend.
778 protected function debug( $generator = "internal" ) {
779 global $wgShowHostnames;
780 if ( !$this->enableDebugComment
) {
783 $data = array( $generator );
784 if ( $wgShowHostnames ) {
785 $data[] = wfHostname();
787 $data[] = wfTimestamp( TS_DB
);
788 return "<!-- diff generator: " .
797 * Replace line numbers with the text in the user's language
799 function localiseLineNumbers( $text ) {
800 return preg_replace_callback( '/<!--LINE (\d+)-->/',
801 array( &$this, 'localiseLineNumbersCb' ), $text );
804 function localiseLineNumbersCb( $matches ) {
806 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
807 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
812 * If there are revisions between the ones being compared, return a note saying so.
815 function getMultiNotice() {
816 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
818 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
819 // Comparing two different pages? Count would be meaningless.
823 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
824 $oldRev = $this->mNewRev
; // flip
825 $newRev = $this->mOldRev
; // flip
826 } else { // normal case
827 $oldRev = $this->mOldRev
;
828 $newRev = $this->mNewRev
;
831 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
833 $limit = 100; // use diff-multi-manyusers if too many users
834 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
835 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
837 return ''; // nothing
841 * Get a notice about how many intermediate edits and users there are
842 * @param $numEdits int
843 * @param $numUsers int
847 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
849 if ( $numUsers > $limit ) {
850 $msg = 'diff-multi-manyusers';
855 return wfMsgExt( $msg, 'parseinline',
856 $wgLang->formatnum( $numEdits ), $wgLang->formatnum( $numUsers ) );
860 * Get a header for a specified revision.
862 * @param $rev Revision
863 * @param $complete String: 'complete' to get the header wrapped depending
864 * the visibility of the revision and a link to edit the page.
865 * @return String HTML fragment
867 private function getRevisionHeader( Revision
$rev, $complete = '' ) {
870 $revtimestamp = $rev->getTimestamp();
871 $timestamp = $wgLang->timeanddate( $revtimestamp, true );
872 $dateofrev = $wgLang->date( $revtimestamp, true );
873 $timeofrev = $wgLang->time( $revtimestamp, true );
875 $header = htmlspecialchars( wfMsg(
876 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
882 if ( $complete !== 'complete' ) {
886 $title = $rev->getTitle();
888 $header = Linker
::linkKnown( $title, $header, array(),
889 array( 'oldid' => $rev->getID() ) );
891 if ( $rev->userCan( Revision
::DELETED_TEXT
) ) {
892 $editQuery = array( 'action' => 'edit' );
893 if ( !$rev->isCurrent() ) {
894 $editQuery['oldid'] = $rev->getID();
897 $msg = wfMsgHtml( $title->userCan( 'edit' ) ?
'editold' : 'viewsourceold' );
898 $header .= ' (' . Linker
::linkKnown( $title, $msg, array(), $editQuery ) . ')';
899 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
900 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
903 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
910 * Add the header to a diff body
914 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
915 // shared.css sets diff in interface language/dir, but the actual content
916 // is often in a different language, mostly the page content language/dir
917 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
918 $header = "<table class='$tableClass'>";
920 if ( !$diff && !$otitle ) {
923 <td class='diff-ntitle'>{$ntitle}</td>
927 if ( $diff ) { // Safari/Chrome show broken output if cols not used
929 <col class='diff-marker' />
930 <col class='diff-content' />
931 <col class='diff-marker' />
932 <col class='diff-content' />";
941 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
942 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
946 if ( $multi != '' ) {
947 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
949 if ( $notice != '' ) {
950 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
953 return $header . $diff . "</table>";
957 * Use specified text instead of loading from the database
959 function setText( $oldText, $newText ) {
960 $this->mOldtext
= $oldText;
961 $this->mNewtext
= $newText;
962 $this->mTextLoaded
= 2;
963 $this->mRevisionsLoaded
= true;
967 * Set the language in which the diff text is written
968 * (Defaults to page content language).
971 function setTextLanguage( $lang ) {
972 $this->mDiffLang
= wfGetLangObj( $lang );
978 private function loadRevisionIds() {
979 if ( $this->mRevisionsIdsLoaded
) {
983 $this->mRevisionsIdsLoaded
= true;
985 $old = $this->mOldid
;
986 $new = $this->mNewid
;
988 if ( $new === 'prev' ) {
989 # Show diff between revision $old and the previous one.
990 # Get previous one from DB.
991 $this->mNewid
= intval( $old );
992 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
993 } elseif ( $new === 'next' ) {
994 # Show diff between revision $old and the next one.
995 # Get next one from DB.
996 $this->mOldid
= intval( $old );
997 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
998 if ( $this->mNewid
=== false ) {
999 # if no result, NewId points to the newest old revision. The only newer
1000 # revision is cur, which is "0".
1004 $this->mOldid
= intval( $old );
1005 $this->mNewid
= intval( $new );
1006 wfRunHooks( 'NewDifferenceEngine', array( &$this->mTitle
, &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1011 * Load revision metadata for the specified articles. If newid is 0, then compare
1012 * the old article in oldid to the current article; if oldid is 0, then
1013 * compare the current article to the immediately previous one (ignoring the
1016 * If oldid is false, leave the corresponding revision object set
1017 * to false. This is impossible via ordinary user input, and is provided for
1022 function loadRevisionData() {
1023 if ( $this->mRevisionsLoaded
) {
1027 // Whether it succeeds or fails, we don't want to try again
1028 $this->mRevisionsLoaded
= true;
1030 $this->loadRevisionIds();
1032 // Load the new revision object
1033 $this->mNewRev
= $this->mNewid
1034 ? Revision
::newFromId( $this->mNewid
)
1035 : Revision
::newFromTitle( $this->mTitle
);
1037 if ( !$this->mNewRev
instanceof Revision
) {
1041 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1042 $this->mNewid
= $this->mNewRev
->getId();
1043 $this->mNewPage
= $this->mNewRev
->getTitle();
1045 // Load the old revision object
1046 $this->mOldRev
= false;
1047 if ( $this->mOldid
) {
1048 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1049 } elseif ( $this->mOldid
=== 0 ) {
1050 $rev = $this->mNewRev
->getPrevious();
1052 $this->mOldid
= $rev->getId();
1053 $this->mOldRev
= $rev;
1055 // No previous revision; mark to show as first-version only.
1056 $this->mOldid
= false;
1057 $this->mOldRev
= false;
1059 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1061 if ( is_null( $this->mOldRev
) ) {
1065 if ( $this->mOldRev
) {
1066 $this->mOldPage
= $this->mOldRev
->getTitle();
1073 * Load the text of the revisions, as well as revision data.
1077 function loadText() {
1078 if ( $this->mTextLoaded
== 2 ) {
1081 // Whether it succeeds or fails, we don't want to try again
1082 $this->mTextLoaded
= 2;
1085 if ( !$this->loadRevisionData() ) {
1088 if ( $this->mOldRev
) {
1089 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1090 if ( $this->mOldtext
=== false ) {
1094 if ( $this->mNewRev
) {
1095 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1096 if ( $this->mNewtext
=== false ) {
1104 * Load the text of the new revision, not the old one
1108 function loadNewText() {
1109 if ( $this->mTextLoaded
>= 1 ) {
1112 $this->mTextLoaded
= 1;
1114 if ( !$this->loadRevisionData() ) {
1117 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);