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 $wgOut->loginToUse();
202 wfProfileOut( __METHOD__
);
206 # If external diffs are enabled both globally and for the user,
207 # we'll use the application/x-external-editor interface to call
208 # an external diff tool like kompare, kdiff3, etc.
209 if ( $wgUseExternalEditor && $wgUser->getOption( 'externaldiff' ) ) {
210 global $wgCanonicalServer, $wgScript, $wgLang;
212 header ( "Content-type: application/x-external-editor; charset=UTF-8" );
213 # This should be mOldPage, but it may not be set, see below.
214 $url1 = $this->mNewPage
->getCanonicalURL( array(
216 'oldid' => $this->mOldid
218 $url2 = $this->mNewPage
->getCanonicalURL( array(
220 'oldid' => $this->mNewid
222 $special = $wgLang->getNsText( NS_SPECIAL
);
223 $control = <<<CONTROL
227 Script={$wgCanonicalServer}{$wgScript}
228 Special namespace={$special}
240 wfProfileOut( __METHOD__
);
248 # Carry over 'diffonly' param via navigation links
249 if ( $diffOnly != $wgUser->getBoolOption( 'diffonly' ) ) {
250 $query['diffonly'] = $diffOnly;
252 # Cascade unhide param in links for easy deletion browsing
253 if ( $this->unhide
) {
254 $query['unhide'] = 1;
257 # Check if one of the revisions is deleted/suppressed
258 $deleted = $suppressed = false;
259 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
);
261 # mOldRev is false if the difference engine is called with a "vague" query for
262 # a diff between a version V and its previous version V' AND the version V
263 # is the first version of that article. In that case, V' does not exist.
264 if ( $this->mOldRev
=== false ) {
265 $wgOut->setPageTitle( $this->mNewPage
->getPrefixedText() );
266 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
270 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
272 $sk = $wgUser->getSkin();
273 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
274 $sk->suppressQuickbar();
277 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
278 $wgOut->setPageTitle( $this->mNewPage
->getPrefixedText() );
279 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
282 $wgOut->setPageTitle( $this->mOldPage
->getPrefixedText() . ', ' . $this->mNewPage
->getPrefixedText() );
283 $wgOut->setSubtitle( wfMsgExt( 'difference-multipage', array( 'parseinline' ) ) );
287 if ( $samePage && $this->mNewPage
->userCan( 'edit' ) ) {
288 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback' ) ) {
289 $wgOut->preventClickjacking();
290 $rollback = '   ' . Linker
::generateRollback( $this->mNewRev
);
292 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
293 $undoLink = ' ' . wfMsgHtml( 'parentheses', Html
::element( 'a', array(
294 'href' => $this->mNewPage
->getLocalUrl( array(
296 'undoafter' => $this->mOldid
,
297 'undo' => $this->mNewid
) ),
298 'title' => Linker
::titleAttrib( 'undo' )
299 ), wfMsg( 'editundo' ) ) );
303 # Make "previous revision link"
304 if ( $samePage && $this->mOldRev
->getPrevious() ) {
305 $prevlink = Linker
::linkKnown(
307 wfMsgHtml( 'previousdiff' ),
308 array( 'id' => 'differences-prevlink' ),
309 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
312 $prevlink = ' ';
315 if ( $this->mOldRev
->isMinor() ) {
316 $oldminor = ChangesList
::flag( 'minor' );
321 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
322 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
324 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
325 '<div id="mw-diff-otitle2">' .
326 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
327 '<div id="mw-diff-otitle3">' . $oldminor .
328 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
329 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
331 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
332 $deleted = true; // old revisions text is hidden
333 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
334 $suppressed = true; // also suppressed
338 # Check if this user can see the revisions
339 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
344 # Make "next revision link"
345 # Skip next link on the top revision
346 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
347 $nextlink = Linker
::linkKnown(
349 wfMsgHtml( 'nextdiff' ),
350 array( 'id' => 'differences-nextlink' ),
351 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
354 $nextlink = ' ';
357 if ( $this->mNewRev
->isMinor() ) {
358 $newminor = ChangesList
::flag( 'minor' );
363 # Handle RevisionDelete links...
364 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
365 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
367 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
368 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
370 '<div id="mw-diff-ntitle3">' . $newminor .
371 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
372 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
374 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
375 $deleted = true; // new revisions text is hidden
376 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
377 $suppressed = true; // also suppressed
380 # If the diff cannot be shown due to a deleted revision, then output
381 # the diff header and links to unhide (if available)...
382 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
383 $this->showDiffStyle();
384 $multi = $this->getMultiNotice();
385 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
387 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
388 # Give explanation for why revision is not visible
389 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
392 # Give explanation and add a link to view the diff...
393 $link = $this->mTitle
->getFullUrl( $wgRequest->appendQueryValue( 'unhide', '1', true ) );
394 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
395 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
397 # Otherwise, output a regular diff...
399 # Add deletion notice if the user is viewing deleted content
402 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
403 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . wfMsgExt( $msg, 'parseinline' ) . "</div>\n";
405 $this->showDiff( $oldHeader, $newHeader, $notice );
407 $this->renderNewRevision();
410 wfProfileOut( __METHOD__
);
414 * Get a link to mark the change as patrolled, or '' if there's either no
415 * revision to patrol or the user is not allowed to to it.
416 * Side effect: this method will call OutputPage::preventClickjacking()
417 * when a link is builded.
421 protected function markPatrolledLink() {
422 global $wgUseRCPatrol, $wgUser, $wgOut;
424 if ( $this->mMarkPatrolledLink
=== null ) {
425 // Prepare a change patrol link, if applicable
426 if ( $wgUseRCPatrol && $this->mNewPage
->userCan( 'patrol' ) ) {
427 // If we've been given an explicit change identifier, use it; saves time
428 if ( $this->mRcidMarkPatrolled
) {
429 $rcid = $this->mRcidMarkPatrolled
;
430 $rc = RecentChange
::newFromId( $rcid );
431 // Already patrolled?
432 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
434 // Look for an unpatrolled change corresponding to this diff
435 $db = wfGetDB( DB_SLAVE
);
436 $change = RecentChange
::newFromConds(
438 // Redundant user,timestamp condition so we can use the existing index
439 'rc_user_text' => $this->mNewRev
->getRawUserText(),
440 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
441 'rc_this_oldid' => $this->mNewid
,
442 'rc_last_oldid' => $this->mOldid
,
447 if ( $change instanceof RecentChange
) {
448 $rcid = $change->mAttribs
['rc_id'];
449 $this->mRcidMarkPatrolled
= $rcid;
457 $wgOut->preventClickjacking();
458 $token = $wgUser->editToken( $rcid );
459 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
461 wfMsgHtml( 'markaspatrolleddiff' ),
464 'action' => 'markpatrolled',
470 $this->mMarkPatrolledLink
= '';
473 $this->mMarkPatrolledLink
= '';
477 return $this->mMarkPatrolledLink
;
481 * @param $rev Revision
484 protected function revisionDeleteLink( $rev ) {
487 $canHide = $wgUser->isAllowed( 'deleterevision' );
488 // Show del/undel link if:
489 // (a) the user can delete revisions, or
490 // (b) the user can view deleted revision *and* this one is deleted
491 if ( $canHide ||
( $rev->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
492 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
) ) {
493 $link = Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
496 'type' => 'revision',
497 'target' => $rev->getTitle()->getPrefixedDBkey(),
498 'ids' => $rev->getId()
500 $link = Linker
::revDeleteLink( $query,
501 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
503 $link = '   ' . $link . ' ';
509 * Show the new revision of the page.
511 function renderNewRevision() {
513 wfProfileIn( __METHOD__
);
514 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
515 # Add "current version as of X" title
516 $wgOut->addHTML( "<hr class='diff-hr' />
517 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
518 # Page content may be handled by a hooked call instead...
519 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $wgOut ) ) ) {
520 # Use the current version parser cache if applicable
522 if ( !$this->mNewRev
->isCurrent() ) {
523 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
527 $this->loadNewText();
528 $wgOut->setRevisionId( $this->mNewRev
->getId() );
529 $wgOut->setArticleFlag( true );
531 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
532 // Stolen from Article::view --AG 2007-10-11
533 // Give hooks a chance to customise the output
534 // @TODO: standardize this crap into one function
535 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mNewPage
, $wgOut ) ) ) {
536 // Wrap the whole lot in a <pre> and don't parse
538 preg_match( '!\.(css|js)$!u', $this->mNewPage
->getText(), $m );
539 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
540 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
541 $wgOut->addHTML( "\n</pre>\n" );
543 } elseif ( $pCache ) {
544 $article = new Article( $this->mNewPage
, 0 );
545 $pOutput = ParserCache
::singleton()->get( $article, $wgOut->parserOptions() );
547 $wgOut->addParserOutput( $pOutput );
549 $article->doViewParse();
552 $wgOut->addWikiTextTidy( $this->mNewtext
);
555 if ( !$this->mNewRev
->isCurrent() ) {
556 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
559 # Add redundant patrol link on bottom...
560 $wgOut->addHTML( $this->markPatrolledLink() );
562 wfProfileOut( __METHOD__
);
566 * Get the diff text, send it to $wgOut
567 * Returns false if the diff could not be generated, otherwise returns true
571 function showDiff( $otitle, $ntitle, $notice = '' ) {
573 $diff = $this->getDiff( $otitle, $ntitle, $notice );
574 if ( $diff === false ) {
575 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
578 $this->showDiffStyle();
579 $wgOut->addHTML( $diff );
585 * Add style sheets and supporting JS for diff display.
587 function showDiffStyle() {
589 $wgOut->addModuleStyles( 'mediawiki.action.history.diff' );
593 * Get complete diff table, including header
595 * @param $otitle Title: old title
596 * @param $ntitle Title: new title
597 * @param $notice String: HTML between diff header and body
600 function getDiff( $otitle, $ntitle, $notice = '' ) {
601 $body = $this->getDiffBody();
602 if ( $body === false ) {
605 $multi = $this->getMultiNotice();
606 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
611 * Get the diff table body, without header
613 * @return mixed (string/false)
615 public function getDiffBody() {
617 wfProfileIn( __METHOD__
);
618 $this->mCacheHit
= true;
619 // Check if the diff should be hidden from this user
620 if ( !$this->loadRevisionData() ) {
621 wfProfileOut( __METHOD__
);
623 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
624 wfProfileOut( __METHOD__
);
626 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
627 wfProfileOut( __METHOD__
);
631 // If mOldRev is false, it means that the
632 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
633 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
635 wfProfileOut( __METHOD__
);
640 if ( $this->mOldid
&& $this->mNewid
) {
641 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
642 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
644 if ( !$this->mRefreshCache
) {
645 $difftext = $wgMemc->get( $key );
647 wfIncrStats( 'diff_cache_hit' );
648 $difftext = $this->localiseLineNumbers( $difftext );
649 $difftext .= "\n<!-- diff cache key $key -->\n";
650 wfProfileOut( __METHOD__
);
653 } // don't try to load but save the result
655 $this->mCacheHit
= false;
657 // Loadtext is permission safe, this just clears out the diff
658 if ( !$this->loadText() ) {
659 wfProfileOut( __METHOD__
);
663 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
665 // Save to cache for 7 days
666 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
667 wfIncrStats( 'diff_uncacheable' );
668 } elseif ( $key !== false && $difftext !== false ) {
669 wfIncrStats( 'diff_cache_miss' );
670 $wgMemc->set( $key, $difftext, 7 * 86400 );
672 wfIncrStats( 'diff_uncacheable' );
674 // Replace line numbers with the text in the user's language
675 if ( $difftext !== false ) {
676 $difftext = $this->localiseLineNumbers( $difftext );
678 wfProfileOut( __METHOD__
);
683 * Make sure the proper modules are loaded before we try to
686 private function initDiffEngines() {
687 global $wgExternalDiffEngine;
688 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
689 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
690 wfDl( 'php_wikidiff' );
691 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
693 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
694 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
696 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
701 * Generate a diff, no caching
703 * @param $otext String: old text, must be already segmented
704 * @param $ntext String: new text, must be already segmented
706 function generateDiffBody( $otext, $ntext ) {
707 global $wgExternalDiffEngine, $wgContLang;
709 wfProfileIn( __METHOD__
);
711 $otext = str_replace( "\r\n", "\n", $otext );
712 $ntext = str_replace( "\r\n", "\n", $ntext );
714 $this->initDiffEngines();
716 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
717 # For historical reasons, external diff engine expects
718 # input text to be HTML-escaped already
719 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
720 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
721 wfProfileOut( __METHOD__
);
722 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
723 $this->debug( 'wikidiff1' );
726 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
727 # Better external diff engine, the 2 may some day be dropped
728 # This one does the escaping and segmenting itself
729 wfProfileIn( 'wikidiff2_do_diff' );
730 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
731 $text .= $this->debug( 'wikidiff2' );
732 wfProfileOut( 'wikidiff2_do_diff' );
733 wfProfileOut( __METHOD__
);
736 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
738 global $wgTmpDirectory;
739 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
740 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
742 $tempFile1 = fopen( $tempName1, "w" );
744 wfProfileOut( __METHOD__
);
747 $tempFile2 = fopen( $tempName2, "w" );
749 wfProfileOut( __METHOD__
);
752 fwrite( $tempFile1, $otext );
753 fwrite( $tempFile2, $ntext );
754 fclose( $tempFile1 );
755 fclose( $tempFile2 );
756 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
757 wfProfileIn( __METHOD__
. "-shellexec" );
758 $difftext = wfShellExec( $cmd );
759 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
760 wfProfileOut( __METHOD__
. "-shellexec" );
761 unlink( $tempName1 );
762 unlink( $tempName2 );
763 wfProfileOut( __METHOD__
);
768 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
769 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
770 $diffs = new Diff( $ota, $nta );
771 $formatter = new TableDiffFormatter();
772 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
773 wfProfileOut( __METHOD__
);
778 * Generate a debug comment indicating diff generating time,
779 * server node, and generator backend.
781 protected function debug( $generator = "internal" ) {
782 global $wgShowHostnames;
783 if ( !$this->enableDebugComment
) {
786 $data = array( $generator );
787 if ( $wgShowHostnames ) {
788 $data[] = wfHostname();
790 $data[] = wfTimestamp( TS_DB
);
791 return "<!-- diff generator: " .
800 * Replace line numbers with the text in the user's language
802 function localiseLineNumbers( $text ) {
803 return preg_replace_callback( '/<!--LINE (\d+)-->/',
804 array( &$this, 'localiseLineNumbersCb' ), $text );
807 function localiseLineNumbersCb( $matches ) {
809 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
810 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
815 * If there are revisions between the ones being compared, return a note saying so.
818 function getMultiNotice() {
819 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
821 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
822 // Comparing two different pages? Count would be meaningless.
826 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
827 $oldRev = $this->mNewRev
; // flip
828 $newRev = $this->mOldRev
; // flip
829 } else { // normal case
830 $oldRev = $this->mOldRev
;
831 $newRev = $this->mNewRev
;
834 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
836 $limit = 100; // use diff-multi-manyusers if too many users
837 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
838 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
840 return ''; // nothing
844 * Get a notice about how many intermediate edits and users there are
845 * @param $numEdits int
846 * @param $numUsers int
850 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
852 if ( $numUsers > $limit ) {
853 $msg = 'diff-multi-manyusers';
858 return wfMsgExt( $msg, 'parseinline',
859 $wgLang->formatnum( $numEdits ), $wgLang->formatnum( $numUsers ) );
863 * Get a header for a specified revision.
865 * @param $rev Revision
866 * @param $complete String: 'complete' to get the header wrapped depending
867 * the visibility of the revision and a link to edit the page.
868 * @return String HTML fragment
870 private function getRevisionHeader( Revision
$rev, $complete = '' ) {
873 $revtimestamp = $rev->getTimestamp();
874 $timestamp = $wgLang->timeanddate( $revtimestamp, true );
875 $dateofrev = $wgLang->date( $revtimestamp, true );
876 $timeofrev = $wgLang->time( $revtimestamp, true );
878 $header = htmlspecialchars( wfMsg(
879 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
885 if ( $complete !== 'complete' ) {
889 $title = $rev->getTitle();
891 $header = Linker
::linkKnown( $title, $header, array(),
892 array( 'oldid' => $rev->getID() ) );
894 if ( $rev->userCan( Revision
::DELETED_TEXT
) ) {
895 $editQuery = array( 'action' => 'edit' );
896 if ( !$rev->isCurrent() ) {
897 $editQuery['oldid'] = $rev->getID();
900 $msg = wfMsgHtml( $title->userCan( 'edit' ) ?
'editold' : 'viewsourceold' );
901 $header .= ' (' . Linker
::linkKnown( $title, $msg, array(), $editQuery ) . ')';
902 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
903 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
906 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
913 * Add the header to a diff body
917 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
918 // shared.css sets diff in interface language/dir, but the actual content
919 // is often in a different language, mostly the page content language/dir
920 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
921 $header = "<table class='$tableClass'>";
923 if ( !$diff && !$otitle ) {
926 <td class='diff-ntitle'>{$ntitle}</td>
930 if ( $diff ) { // Safari/Chrome show broken output if cols not used
932 <col class='diff-marker' />
933 <col class='diff-content' />
934 <col class='diff-marker' />
935 <col class='diff-content' />";
944 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
945 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
949 if ( $multi != '' ) {
950 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
952 if ( $notice != '' ) {
953 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
956 return $header . $diff . "</table>";
960 * Use specified text instead of loading from the database
962 function setText( $oldText, $newText ) {
963 $this->mOldtext
= $oldText;
964 $this->mNewtext
= $newText;
965 $this->mTextLoaded
= 2;
966 $this->mRevisionsLoaded
= true;
970 * Set the language in which the diff text is written
971 * (Defaults to page content language).
974 function setTextLanguage( $lang ) {
975 $this->mDiffLang
= wfGetLangObj( $lang );
981 private function loadRevisionIds() {
982 if ( $this->mRevisionsIdsLoaded
) {
986 $this->mRevisionsIdsLoaded
= true;
988 $old = $this->mOldid
;
989 $new = $this->mNewid
;
991 if ( $new === 'prev' ) {
992 # Show diff between revision $old and the previous one.
993 # Get previous one from DB.
994 $this->mNewid
= intval( $old );
995 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
996 } elseif ( $new === 'next' ) {
997 # Show diff between revision $old and the next one.
998 # Get next one from DB.
999 $this->mOldid
= intval( $old );
1000 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
1001 if ( $this->mNewid
=== false ) {
1002 # if no result, NewId points to the newest old revision. The only newer
1003 # revision is cur, which is "0".
1007 $this->mOldid
= intval( $old );
1008 $this->mNewid
= intval( $new );
1009 wfRunHooks( 'NewDifferenceEngine', array( &$this->mTitle
, &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1014 * Load revision metadata for the specified articles. If newid is 0, then compare
1015 * the old article in oldid to the current article; if oldid is 0, then
1016 * compare the current article to the immediately previous one (ignoring the
1019 * If oldid is false, leave the corresponding revision object set
1020 * to false. This is impossible via ordinary user input, and is provided for
1025 function loadRevisionData() {
1026 if ( $this->mRevisionsLoaded
) {
1030 // Whether it succeeds or fails, we don't want to try again
1031 $this->mRevisionsLoaded
= true;
1033 $this->loadRevisionIds();
1035 // Load the new revision object
1036 $this->mNewRev
= $this->mNewid
1037 ? Revision
::newFromId( $this->mNewid
)
1038 : Revision
::newFromTitle( $this->mTitle
);
1040 if ( !$this->mNewRev
instanceof Revision
) {
1044 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1045 $this->mNewid
= $this->mNewRev
->getId();
1046 $this->mNewPage
= $this->mNewRev
->getTitle();
1048 // Load the old revision object
1049 $this->mOldRev
= false;
1050 if ( $this->mOldid
) {
1051 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1052 } elseif ( $this->mOldid
=== 0 ) {
1053 $rev = $this->mNewRev
->getPrevious();
1055 $this->mOldid
= $rev->getId();
1056 $this->mOldRev
= $rev;
1058 // No previous revision; mark to show as first-version only.
1059 $this->mOldid
= false;
1060 $this->mOldRev
= false;
1062 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1064 if ( is_null( $this->mOldRev
) ) {
1068 if ( $this->mOldRev
) {
1069 $this->mOldPage
= $this->mOldRev
->getTitle();
1076 * Load the text of the revisions, as well as revision data.
1080 function loadText() {
1081 if ( $this->mTextLoaded
== 2 ) {
1084 // Whether it succeeds or fails, we don't want to try again
1085 $this->mTextLoaded
= 2;
1088 if ( !$this->loadRevisionData() ) {
1091 if ( $this->mOldRev
) {
1092 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1093 if ( $this->mOldtext
=== false ) {
1097 if ( $this->mNewRev
) {
1098 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1099 if ( $this->mNewtext
=== false ) {
1107 * Load the text of the new revision, not the old one
1111 function loadNewText() {
1112 if ( $this->mTextLoaded
>= 1 ) {
1115 $this->mTextLoaded
= 1;
1117 if ( !$this->loadRevisionData() ) {
1120 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);