c433f899759877040506397f41b1b49ffef57489
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 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $wgUser );
198 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
199 $permErrors = wfMergeErrorArrays( $permErrors,
200 $this->mOldPage
->getUserPermissionsErrors( 'read', $wgUser ) );
202 if ( count( $permErrors ) ) {
203 wfProfileOut( __METHOD__
);
204 throw new PermissionsError( 'read', $permErrors );
207 # If external diffs are enabled both globally and for the user,
208 # we'll use the application/x-external-editor interface to call
209 # an external diff tool like kompare, kdiff3, etc.
210 if ( $wgUseExternalEditor && $wgUser->getOption( 'externaldiff' ) ) {
211 global $wgCanonicalServer, $wgScript, $wgLang;
213 header ( "Content-type: application/x-external-editor; charset=UTF-8" );
214 # This should be mOldPage, but it may not be set, see below.
215 $url1 = $this->mNewPage
->getCanonicalURL( array(
217 'oldid' => $this->mOldid
219 $url2 = $this->mNewPage
->getCanonicalURL( array(
221 'oldid' => $this->mNewid
223 $special = $wgLang->getNsText( NS_SPECIAL
);
224 $control = <<<CONTROL
228 Script={$wgCanonicalServer}{$wgScript}
229 Special namespace={$special}
241 wfProfileOut( __METHOD__
);
249 # Carry over 'diffonly' param via navigation links
250 if ( $diffOnly != $wgUser->getBoolOption( 'diffonly' ) ) {
251 $query['diffonly'] = $diffOnly;
253 # Cascade unhide param in links for easy deletion browsing
254 if ( $this->unhide
) {
255 $query['unhide'] = 1;
258 # Check if one of the revisions is deleted/suppressed
259 $deleted = $suppressed = false;
260 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
);
262 # mOldRev is false if the difference engine is called with a "vague" query for
263 # a diff between a version V and its previous version V' AND the version V
264 # is the first version of that article. In that case, V' does not exist.
265 if ( $this->mOldRev
=== false ) {
266 $wgOut->setPageTitle( $this->mNewPage
->getPrefixedText() );
267 $wgOut->addSubtitle( wfMessage( 'difference' ) );
271 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
273 $sk = $wgUser->getSkin();
274 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
275 $sk->suppressQuickbar();
278 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
279 $wgOut->setPageTitle( $this->mNewPage
->getPrefixedText() );
280 $wgOut->addSubtitle( wfMessage( 'difference' ) );
283 $wgOut->setPageTitle( $this->mOldPage
->getPrefixedText() . ', ' . $this->mNewPage
->getPrefixedText() );
284 $wgOut->addSubtitle( wfMessage( 'difference-multipage' ) );
288 if ( $samePage && $this->mNewPage
->userCan( 'edit' ) ) {
289 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback' ) ) {
290 $wgOut->preventClickjacking();
291 $rollback = '   ' . Linker
::generateRollback( $this->mNewRev
);
293 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
294 $undoLink = ' ' . wfMsgHtml( 'parentheses', Html
::element( 'a', array(
295 'href' => $this->mNewPage
->getLocalUrl( array(
297 'undoafter' => $this->mOldid
,
298 'undo' => $this->mNewid
) ),
299 'title' => Linker
::titleAttrib( 'undo' )
300 ), wfMsg( 'editundo' ) ) );
304 # Make "previous revision link"
305 if ( $samePage && $this->mOldRev
->getPrevious() ) {
306 $prevlink = Linker
::linkKnown(
308 wfMsgHtml( 'previousdiff' ),
309 array( 'id' => 'differences-prevlink' ),
310 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
313 $prevlink = ' ';
316 if ( $this->mOldRev
->isMinor() ) {
317 $oldminor = ChangesList
::flag( 'minor' );
322 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
323 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
325 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
326 '<div id="mw-diff-otitle2">' .
327 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
328 '<div id="mw-diff-otitle3">' . $oldminor .
329 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
330 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
332 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
333 $deleted = true; // old revisions text is hidden
334 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
335 $suppressed = true; // also suppressed
339 # Check if this user can see the revisions
340 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
345 # Make "next revision link"
346 # Skip next link on the top revision
347 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
348 $nextlink = Linker
::linkKnown(
350 wfMsgHtml( 'nextdiff' ),
351 array( 'id' => 'differences-nextlink' ),
352 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
355 $nextlink = ' ';
358 if ( $this->mNewRev
->isMinor() ) {
359 $newminor = ChangesList
::flag( 'minor' );
364 # Handle RevisionDelete links...
365 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
366 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
368 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
369 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
371 '<div id="mw-diff-ntitle3">' . $newminor .
372 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
373 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
375 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
376 $deleted = true; // new revisions text is hidden
377 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
378 $suppressed = true; // also suppressed
381 # If the diff cannot be shown due to a deleted revision, then output
382 # the diff header and links to unhide (if available)...
383 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
384 $this->showDiffStyle();
385 $multi = $this->getMultiNotice();
386 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
388 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
389 # Give explanation for why revision is not visible
390 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
393 # Give explanation and add a link to view the diff...
394 $link = $this->mTitle
->getFullUrl( $wgRequest->appendQueryValue( 'unhide', '1', true ) );
395 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
396 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
398 # Otherwise, output a regular diff...
400 # Add deletion notice if the user is viewing deleted content
403 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
404 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . wfMsgExt( $msg, 'parseinline' ) . "</div>\n";
406 $this->showDiff( $oldHeader, $newHeader, $notice );
408 $this->renderNewRevision();
411 wfProfileOut( __METHOD__
);
415 * Get a link to mark the change as patrolled, or '' if there's either no
416 * revision to patrol or the user is not allowed to to it.
417 * Side effect: this method will call OutputPage::preventClickjacking()
418 * when a link is builded.
422 protected function markPatrolledLink() {
423 global $wgUseRCPatrol, $wgUser, $wgOut;
425 if ( $this->mMarkPatrolledLink
=== null ) {
426 // Prepare a change patrol link, if applicable
427 if ( $wgUseRCPatrol && $this->mNewPage
->userCan( 'patrol' ) ) {
428 // If we've been given an explicit change identifier, use it; saves time
429 if ( $this->mRcidMarkPatrolled
) {
430 $rcid = $this->mRcidMarkPatrolled
;
431 $rc = RecentChange
::newFromId( $rcid );
432 // Already patrolled?
433 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
435 // Look for an unpatrolled change corresponding to this diff
436 $db = wfGetDB( DB_SLAVE
);
437 $change = RecentChange
::newFromConds(
439 // Redundant user,timestamp condition so we can use the existing index
440 'rc_user_text' => $this->mNewRev
->getRawUserText(),
441 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
442 'rc_this_oldid' => $this->mNewid
,
443 'rc_last_oldid' => $this->mOldid
,
448 if ( $change instanceof RecentChange
) {
449 $rcid = $change->mAttribs
['rc_id'];
450 $this->mRcidMarkPatrolled
= $rcid;
458 $wgOut->preventClickjacking();
459 $token = $wgUser->editToken( $rcid );
460 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
462 wfMsgHtml( 'markaspatrolleddiff' ),
465 'action' => 'markpatrolled',
471 $this->mMarkPatrolledLink
= '';
474 $this->mMarkPatrolledLink
= '';
478 return $this->mMarkPatrolledLink
;
482 * @param $rev Revision
485 protected function revisionDeleteLink( $rev ) {
488 $canHide = $wgUser->isAllowed( 'deleterevision' );
489 // Show del/undel link if:
490 // (a) the user can delete revisions, or
491 // (b) the user can view deleted revision *and* this one is deleted
492 if ( $canHide ||
( $rev->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
493 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
) ) {
494 $link = Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
497 'type' => 'revision',
498 'target' => $rev->getTitle()->getPrefixedDBkey(),
499 'ids' => $rev->getId()
501 $link = Linker
::revDeleteLink( $query,
502 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
504 $link = '   ' . $link . ' ';
510 * Show the new revision of the page.
512 function renderNewRevision() {
514 wfProfileIn( __METHOD__
);
515 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
516 # Add "current version as of X" title
517 $wgOut->addHTML( "<hr class='diff-hr' />
518 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
519 # Page content may be handled by a hooked call instead...
520 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $wgOut ) ) ) {
521 # Use the current version parser cache if applicable
523 if ( !$this->mNewRev
->isCurrent() ) {
524 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
528 $this->loadNewText();
529 $wgOut->setRevisionId( $this->mNewRev
->getId() );
530 $wgOut->setArticleFlag( true );
532 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
533 // Stolen from Article::view --AG 2007-10-11
534 // Give hooks a chance to customise the output
535 // @TODO: standardize this crap into one function
536 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mNewPage
, $wgOut ) ) ) {
537 // Wrap the whole lot in a <pre> and don't parse
539 preg_match( '!\.(css|js)$!u', $this->mNewPage
->getText(), $m );
540 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
541 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
542 $wgOut->addHTML( "\n</pre>\n" );
544 } elseif ( $pCache ) {
545 $article = new Article( $this->mNewPage
, 0 );
546 $pOutput = ParserCache
::singleton()->get( $article, $wgOut->parserOptions() );
548 $wgOut->addParserOutput( $pOutput );
550 $article->doViewParse();
553 $wgOut->addWikiTextTidy( $this->mNewtext
);
556 if ( !$this->mNewRev
->isCurrent() ) {
557 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
560 # Add redundant patrol link on bottom...
561 $wgOut->addHTML( $this->markPatrolledLink() );
563 wfProfileOut( __METHOD__
);
567 * Get the diff text, send it to $wgOut
568 * Returns false if the diff could not be generated, otherwise returns true
572 function showDiff( $otitle, $ntitle, $notice = '' ) {
574 $diff = $this->getDiff( $otitle, $ntitle, $notice );
575 if ( $diff === false ) {
576 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
579 $this->showDiffStyle();
580 $wgOut->addHTML( $diff );
586 * Add style sheets and supporting JS for diff display.
588 function showDiffStyle() {
590 $wgOut->addModuleStyles( 'mediawiki.action.history.diff' );
594 * Get complete diff table, including header
596 * @param $otitle Title: old title
597 * @param $ntitle Title: new title
598 * @param $notice String: HTML between diff header and body
601 function getDiff( $otitle, $ntitle, $notice = '' ) {
602 $body = $this->getDiffBody();
603 if ( $body === false ) {
606 $multi = $this->getMultiNotice();
607 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
612 * Get the diff table body, without header
614 * @return mixed (string/false)
616 public function getDiffBody() {
618 wfProfileIn( __METHOD__
);
619 $this->mCacheHit
= true;
620 // Check if the diff should be hidden from this user
621 if ( !$this->loadRevisionData() ) {
622 wfProfileOut( __METHOD__
);
624 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
625 wfProfileOut( __METHOD__
);
627 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
628 wfProfileOut( __METHOD__
);
632 // If mOldRev is false, it means that the
633 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
634 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
636 wfProfileOut( __METHOD__
);
641 if ( $this->mOldid
&& $this->mNewid
) {
642 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
643 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
645 if ( !$this->mRefreshCache
) {
646 $difftext = $wgMemc->get( $key );
648 wfIncrStats( 'diff_cache_hit' );
649 $difftext = $this->localiseLineNumbers( $difftext );
650 $difftext .= "\n<!-- diff cache key $key -->\n";
651 wfProfileOut( __METHOD__
);
654 } // don't try to load but save the result
656 $this->mCacheHit
= false;
658 // Loadtext is permission safe, this just clears out the diff
659 if ( !$this->loadText() ) {
660 wfProfileOut( __METHOD__
);
664 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
666 // Save to cache for 7 days
667 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
668 wfIncrStats( 'diff_uncacheable' );
669 } elseif ( $key !== false && $difftext !== false ) {
670 wfIncrStats( 'diff_cache_miss' );
671 $wgMemc->set( $key, $difftext, 7 * 86400 );
673 wfIncrStats( 'diff_uncacheable' );
675 // Replace line numbers with the text in the user's language
676 if ( $difftext !== false ) {
677 $difftext = $this->localiseLineNumbers( $difftext );
679 wfProfileOut( __METHOD__
);
684 * Make sure the proper modules are loaded before we try to
687 private function initDiffEngines() {
688 global $wgExternalDiffEngine;
689 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
690 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
691 wfDl( 'php_wikidiff' );
692 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
694 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
695 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
697 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
702 * Generate a diff, no caching
704 * @param $otext String: old text, must be already segmented
705 * @param $ntext String: new text, must be already segmented
707 function generateDiffBody( $otext, $ntext ) {
708 global $wgExternalDiffEngine, $wgContLang;
710 wfProfileIn( __METHOD__
);
712 $otext = str_replace( "\r\n", "\n", $otext );
713 $ntext = str_replace( "\r\n", "\n", $ntext );
715 $this->initDiffEngines();
717 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
718 # For historical reasons, external diff engine expects
719 # input text to be HTML-escaped already
720 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
721 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
722 wfProfileOut( __METHOD__
);
723 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
724 $this->debug( 'wikidiff1' );
727 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
728 # Better external diff engine, the 2 may some day be dropped
729 # This one does the escaping and segmenting itself
730 wfProfileIn( 'wikidiff2_do_diff' );
731 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
732 $text .= $this->debug( 'wikidiff2' );
733 wfProfileOut( 'wikidiff2_do_diff' );
734 wfProfileOut( __METHOD__
);
737 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
739 global $wgTmpDirectory;
740 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
741 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
743 $tempFile1 = fopen( $tempName1, "w" );
745 wfProfileOut( __METHOD__
);
748 $tempFile2 = fopen( $tempName2, "w" );
750 wfProfileOut( __METHOD__
);
753 fwrite( $tempFile1, $otext );
754 fwrite( $tempFile2, $ntext );
755 fclose( $tempFile1 );
756 fclose( $tempFile2 );
757 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
758 wfProfileIn( __METHOD__
. "-shellexec" );
759 $difftext = wfShellExec( $cmd );
760 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
761 wfProfileOut( __METHOD__
. "-shellexec" );
762 unlink( $tempName1 );
763 unlink( $tempName2 );
764 wfProfileOut( __METHOD__
);
769 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
770 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
771 $diffs = new Diff( $ota, $nta );
772 $formatter = new TableDiffFormatter();
773 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
774 wfProfileOut( __METHOD__
);
779 * Generate a debug comment indicating diff generating time,
780 * server node, and generator backend.
782 protected function debug( $generator = "internal" ) {
783 global $wgShowHostnames;
784 if ( !$this->enableDebugComment
) {
787 $data = array( $generator );
788 if ( $wgShowHostnames ) {
789 $data[] = wfHostname();
791 $data[] = wfTimestamp( TS_DB
);
792 return "<!-- diff generator: " .
801 * Replace line numbers with the text in the user's language
803 function localiseLineNumbers( $text ) {
804 return preg_replace_callback( '/<!--LINE (\d+)-->/',
805 array( &$this, 'localiseLineNumbersCb' ), $text );
808 function localiseLineNumbersCb( $matches ) {
810 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
811 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
816 * If there are revisions between the ones being compared, return a note saying so.
819 function getMultiNotice() {
820 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
822 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
823 // Comparing two different pages? Count would be meaningless.
827 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
828 $oldRev = $this->mNewRev
; // flip
829 $newRev = $this->mOldRev
; // flip
830 } else { // normal case
831 $oldRev = $this->mOldRev
;
832 $newRev = $this->mNewRev
;
835 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
837 $limit = 100; // use diff-multi-manyusers if too many users
838 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
839 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
841 return ''; // nothing
845 * Get a notice about how many intermediate edits and users there are
846 * @param $numEdits int
847 * @param $numUsers int
851 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
853 if ( $numUsers > $limit ) {
854 $msg = 'diff-multi-manyusers';
859 return wfMsgExt( $msg, 'parseinline',
860 $wgLang->formatnum( $numEdits ), $wgLang->formatnum( $numUsers ) );
864 * Get a header for a specified revision.
866 * @param $rev Revision
867 * @param $complete String: 'complete' to get the header wrapped depending
868 * the visibility of the revision and a link to edit the page.
869 * @return String HTML fragment
871 private function getRevisionHeader( Revision
$rev, $complete = '' ) {
874 $revtimestamp = $rev->getTimestamp();
875 $timestamp = $wgLang->timeanddate( $revtimestamp, true );
876 $dateofrev = $wgLang->date( $revtimestamp, true );
877 $timeofrev = $wgLang->time( $revtimestamp, true );
879 $header = htmlspecialchars( wfMsg(
880 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
886 if ( $complete !== 'complete' ) {
890 $title = $rev->getTitle();
892 $header = Linker
::linkKnown( $title, $header, array(),
893 array( 'oldid' => $rev->getID() ) );
895 if ( $rev->userCan( Revision
::DELETED_TEXT
) ) {
896 $editQuery = array( 'action' => 'edit' );
897 if ( !$rev->isCurrent() ) {
898 $editQuery['oldid'] = $rev->getID();
901 $msg = wfMsgHtml( $title->userCan( 'edit' ) ?
'editold' : 'viewsourceold' );
902 $header .= ' (' . Linker
::linkKnown( $title, $msg, array(), $editQuery ) . ')';
903 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
904 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
907 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
914 * Add the header to a diff body
918 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
919 // shared.css sets diff in interface language/dir, but the actual content
920 // is often in a different language, mostly the page content language/dir
921 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
922 $header = "<table class='$tableClass'>";
924 if ( !$diff && !$otitle ) {
927 <td class='diff-ntitle'>{$ntitle}</td>
931 if ( $diff ) { // Safari/Chrome show broken output if cols not used
933 <col class='diff-marker' />
934 <col class='diff-content' />
935 <col class='diff-marker' />
936 <col class='diff-content' />";
945 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
946 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
950 if ( $multi != '' ) {
951 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
953 if ( $notice != '' ) {
954 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
957 return $header . $diff . "</table>";
961 * Use specified text instead of loading from the database
963 function setText( $oldText, $newText ) {
964 $this->mOldtext
= $oldText;
965 $this->mNewtext
= $newText;
966 $this->mTextLoaded
= 2;
967 $this->mRevisionsLoaded
= true;
971 * Set the language in which the diff text is written
972 * (Defaults to page content language).
975 function setTextLanguage( $lang ) {
976 $this->mDiffLang
= wfGetLangObj( $lang );
982 private function loadRevisionIds() {
983 if ( $this->mRevisionsIdsLoaded
) {
987 $this->mRevisionsIdsLoaded
= true;
989 $old = $this->mOldid
;
990 $new = $this->mNewid
;
992 if ( $new === 'prev' ) {
993 # Show diff between revision $old and the previous one.
994 # Get previous one from DB.
995 $this->mNewid
= intval( $old );
996 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
997 } elseif ( $new === 'next' ) {
998 # Show diff between revision $old and the next one.
999 # Get next one from DB.
1000 $this->mOldid
= intval( $old );
1001 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
1002 if ( $this->mNewid
=== false ) {
1003 # if no result, NewId points to the newest old revision. The only newer
1004 # revision is cur, which is "0".
1008 $this->mOldid
= intval( $old );
1009 $this->mNewid
= intval( $new );
1010 wfRunHooks( 'NewDifferenceEngine', array( &$this->mTitle
, &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1015 * Load revision metadata for the specified articles. If newid is 0, then compare
1016 * the old article in oldid to the current article; if oldid is 0, then
1017 * compare the current article to the immediately previous one (ignoring the
1020 * If oldid is false, leave the corresponding revision object set
1021 * to false. This is impossible via ordinary user input, and is provided for
1026 function loadRevisionData() {
1027 if ( $this->mRevisionsLoaded
) {
1031 // Whether it succeeds or fails, we don't want to try again
1032 $this->mRevisionsLoaded
= true;
1034 $this->loadRevisionIds();
1036 // Load the new revision object
1037 $this->mNewRev
= $this->mNewid
1038 ? Revision
::newFromId( $this->mNewid
)
1039 : Revision
::newFromTitle( $this->mTitle
);
1041 if ( !$this->mNewRev
instanceof Revision
) {
1045 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1046 $this->mNewid
= $this->mNewRev
->getId();
1047 $this->mNewPage
= $this->mNewRev
->getTitle();
1049 // Load the old revision object
1050 $this->mOldRev
= false;
1051 if ( $this->mOldid
) {
1052 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1053 } elseif ( $this->mOldid
=== 0 ) {
1054 $rev = $this->mNewRev
->getPrevious();
1056 $this->mOldid
= $rev->getId();
1057 $this->mOldRev
= $rev;
1059 // No previous revision; mark to show as first-version only.
1060 $this->mOldid
= false;
1061 $this->mOldRev
= false;
1063 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1065 if ( is_null( $this->mOldRev
) ) {
1069 if ( $this->mOldRev
) {
1070 $this->mOldPage
= $this->mOldRev
->getTitle();
1077 * Load the text of the revisions, as well as revision data.
1081 function loadText() {
1082 if ( $this->mTextLoaded
== 2 ) {
1085 // Whether it succeeds or fails, we don't want to try again
1086 $this->mTextLoaded
= 2;
1089 if ( !$this->loadRevisionData() ) {
1092 if ( $this->mOldRev
) {
1093 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1094 if ( $this->mOldtext
=== false ) {
1098 if ( $this->mNewRev
) {
1099 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1100 if ( $this->mNewtext
=== false ) {
1108 * Load the text of the new revision, not the old one
1112 function loadNewText() {
1113 if ( $this->mTextLoaded
>= 1 ) {
1116 $this->mTextLoaded
= 1;
1118 if ( !$this->loadRevisionData() ) {
1121 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);