baba6dc634eadd7076157c134b142358bd5b704a
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 /// @todo Make RequestContext::getMain() go away when we have a context available
208 $context = RequestContext
::getMain();
210 # If external diffs are enabled both globally and for the user,
211 # we'll use the application/x-external-editor interface to call
212 # an external diff tool like kompare, kdiff3, etc.
213 if ( ExternalEdit
::useExternalEngine( $context, 'diff' ) ) {
215 'File' => array( 'Extension' => 'wiki', 'URL' =>
216 # This should be mOldPage, but it may not be set, see below.
217 $this->mNewPage
->getCanonicalURL( array(
218 'action' => 'raw', 'oldid' => $this->mOldid
) )
220 'File2' => array( 'Extension' => 'wiki', 'URL' =>
221 $this->mNewPage
->getCanonicalURL( array(
222 'action' => 'raw', 'oldid' => $this->mNewid
) )
226 $externalEditor = new ExternalEdit( $context, $urls );
227 $externalEditor->execute();
229 wfProfileOut( __METHOD__
);
237 # Carry over 'diffonly' param via navigation links
238 if ( $diffOnly != $wgUser->getBoolOption( 'diffonly' ) ) {
239 $query['diffonly'] = $diffOnly;
241 # Cascade unhide param in links for easy deletion browsing
242 if ( $this->unhide
) {
243 $query['unhide'] = 1;
246 # Check if one of the revisions is deleted/suppressed
247 $deleted = $suppressed = false;
248 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
);
250 # mOldRev is false if the difference engine is called with a "vague" query for
251 # a diff between a version V and its previous version V' AND the version V
252 # is the first version of that article. In that case, V' does not exist.
253 if ( $this->mOldRev
=== false ) {
254 $wgOut->setPageTitle( $this->mNewPage
->getPrefixedText() );
255 $wgOut->addSubtitle( wfMessage( 'difference' ) );
259 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
261 $sk = $wgUser->getSkin();
262 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
263 $sk->suppressQuickbar();
266 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
267 $wgOut->setPageTitle( $this->mNewPage
->getPrefixedText() );
268 $wgOut->addSubtitle( wfMessage( 'difference' ) );
271 $wgOut->setPageTitle( $this->mOldPage
->getPrefixedText() . ', ' . $this->mNewPage
->getPrefixedText() );
272 $wgOut->addSubtitle( wfMessage( 'difference-multipage' ) );
276 if ( $samePage && $this->mNewPage
->userCan( 'edit' ) ) {
277 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback' ) ) {
278 $wgOut->preventClickjacking();
279 $rollback = '   ' . Linker
::generateRollback( $this->mNewRev
);
281 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
282 $undoLink = ' ' . wfMsgHtml( 'parentheses', Html
::element( 'a', array(
283 'href' => $this->mNewPage
->getLocalUrl( array(
285 'undoafter' => $this->mOldid
,
286 'undo' => $this->mNewid
) ),
287 'title' => Linker
::titleAttrib( 'undo' )
288 ), wfMsg( 'editundo' ) ) );
292 # Make "previous revision link"
293 if ( $samePage && $this->mOldRev
->getPrevious() ) {
294 $prevlink = Linker
::linkKnown(
296 wfMsgHtml( 'previousdiff' ),
297 array( 'id' => 'differences-prevlink' ),
298 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
301 $prevlink = ' ';
304 if ( $this->mOldRev
->isMinor() ) {
305 $oldminor = ChangesList
::flag( 'minor' );
310 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
311 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
313 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
314 '<div id="mw-diff-otitle2">' .
315 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
316 '<div id="mw-diff-otitle3">' . $oldminor .
317 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
318 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
320 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
321 $deleted = true; // old revisions text is hidden
322 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
323 $suppressed = true; // also suppressed
327 # Check if this user can see the revisions
328 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
333 # Make "next revision link"
334 # Skip next link on the top revision
335 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
336 $nextlink = Linker
::linkKnown(
338 wfMsgHtml( 'nextdiff' ),
339 array( 'id' => 'differences-nextlink' ),
340 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
343 $nextlink = ' ';
346 if ( $this->mNewRev
->isMinor() ) {
347 $newminor = ChangesList
::flag( 'minor' );
352 # Handle RevisionDelete links...
353 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
354 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
356 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
357 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
359 '<div id="mw-diff-ntitle3">' . $newminor .
360 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
361 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
363 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
364 $deleted = true; // new revisions text is hidden
365 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
366 $suppressed = true; // also suppressed
369 # If the diff cannot be shown due to a deleted revision, then output
370 # the diff header and links to unhide (if available)...
371 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
372 $this->showDiffStyle();
373 $multi = $this->getMultiNotice();
374 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
376 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
377 # Give explanation for why revision is not visible
378 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
381 # Give explanation and add a link to view the diff...
382 $link = $this->mTitle
->getFullUrl( $wgRequest->appendQueryValue( 'unhide', '1', true ) );
383 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
384 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
386 # Otherwise, output a regular diff...
388 # Add deletion notice if the user is viewing deleted content
391 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
392 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . wfMsgExt( $msg, 'parseinline' ) . "</div>\n";
394 $this->showDiff( $oldHeader, $newHeader, $notice );
396 $this->renderNewRevision();
399 wfProfileOut( __METHOD__
);
403 * Get a link to mark the change as patrolled, or '' if there's either no
404 * revision to patrol or the user is not allowed to to it.
405 * Side effect: this method will call OutputPage::preventClickjacking()
406 * when a link is builded.
410 protected function markPatrolledLink() {
411 global $wgUseRCPatrol, $wgUser, $wgOut;
413 if ( $this->mMarkPatrolledLink
=== null ) {
414 // Prepare a change patrol link, if applicable
415 if ( $wgUseRCPatrol && $this->mNewPage
->userCan( 'patrol' ) ) {
416 // If we've been given an explicit change identifier, use it; saves time
417 if ( $this->mRcidMarkPatrolled
) {
418 $rcid = $this->mRcidMarkPatrolled
;
419 $rc = RecentChange
::newFromId( $rcid );
420 // Already patrolled?
421 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
423 // Look for an unpatrolled change corresponding to this diff
424 $db = wfGetDB( DB_SLAVE
);
425 $change = RecentChange
::newFromConds(
427 // Redundant user,timestamp condition so we can use the existing index
428 'rc_user_text' => $this->mNewRev
->getRawUserText(),
429 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
430 'rc_this_oldid' => $this->mNewid
,
431 'rc_last_oldid' => $this->mOldid
,
436 if ( $change instanceof RecentChange
) {
437 $rcid = $change->mAttribs
['rc_id'];
438 $this->mRcidMarkPatrolled
= $rcid;
446 $wgOut->preventClickjacking();
447 $token = $wgUser->editToken( $rcid );
448 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
450 wfMsgHtml( 'markaspatrolleddiff' ),
453 'action' => 'markpatrolled',
459 $this->mMarkPatrolledLink
= '';
462 $this->mMarkPatrolledLink
= '';
466 return $this->mMarkPatrolledLink
;
470 * @param $rev Revision
473 protected function revisionDeleteLink( $rev ) {
476 $canHide = $wgUser->isAllowed( 'deleterevision' );
477 // Show del/undel link if:
478 // (a) the user can delete revisions, or
479 // (b) the user can view deleted revision *and* this one is deleted
480 if ( $canHide ||
( $rev->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
481 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
) ) {
482 $link = Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
485 'type' => 'revision',
486 'target' => $rev->getTitle()->getPrefixedDBkey(),
487 'ids' => $rev->getId()
489 $link = Linker
::revDeleteLink( $query,
490 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
492 $link = '   ' . $link . ' ';
498 * Show the new revision of the page.
500 function renderNewRevision() {
502 wfProfileIn( __METHOD__
);
503 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
504 # Add "current version as of X" title
505 $wgOut->addHTML( "<hr class='diff-hr' />
506 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
507 # Page content may be handled by a hooked call instead...
508 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $wgOut ) ) ) {
509 # Use the current version parser cache if applicable
511 if ( !$this->mNewRev
->isCurrent() ) {
512 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
516 $this->loadNewText();
517 $wgOut->setRevisionId( $this->mNewRev
->getId() );
518 $wgOut->setArticleFlag( true );
520 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
521 // Stolen from Article::view --AG 2007-10-11
522 // Give hooks a chance to customise the output
523 // @TODO: standardize this crap into one function
524 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mNewPage
, $wgOut ) ) ) {
525 // Wrap the whole lot in a <pre> and don't parse
527 preg_match( '!\.(css|js)$!u', $this->mNewPage
->getText(), $m );
528 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
529 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
530 $wgOut->addHTML( "\n</pre>\n" );
532 } elseif ( $pCache ) {
533 $article = new Article( $this->mNewPage
, 0 );
534 $pOutput = ParserCache
::singleton()->get( $article, $wgOut->parserOptions() );
536 $wgOut->addParserOutput( $pOutput );
538 $article->doViewParse();
541 $wgOut->addWikiTextTidy( $this->mNewtext
);
544 if ( !$this->mNewRev
->isCurrent() ) {
545 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
548 # Add redundant patrol link on bottom...
549 $wgOut->addHTML( $this->markPatrolledLink() );
551 wfProfileOut( __METHOD__
);
555 * Get the diff text, send it to $wgOut
556 * Returns false if the diff could not be generated, otherwise returns true
560 function showDiff( $otitle, $ntitle, $notice = '' ) {
562 $diff = $this->getDiff( $otitle, $ntitle, $notice );
563 if ( $diff === false ) {
564 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
567 $this->showDiffStyle();
568 $wgOut->addHTML( $diff );
574 * Add style sheets and supporting JS for diff display.
576 function showDiffStyle() {
578 $wgOut->addModuleStyles( 'mediawiki.action.history.diff' );
582 * Get complete diff table, including header
584 * @param $otitle Title: old title
585 * @param $ntitle Title: new title
586 * @param $notice String: HTML between diff header and body
589 function getDiff( $otitle, $ntitle, $notice = '' ) {
590 $body = $this->getDiffBody();
591 if ( $body === false ) {
594 $multi = $this->getMultiNotice();
595 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
600 * Get the diff table body, without header
602 * @return mixed (string/false)
604 public function getDiffBody() {
606 wfProfileIn( __METHOD__
);
607 $this->mCacheHit
= true;
608 // Check if the diff should be hidden from this user
609 if ( !$this->loadRevisionData() ) {
610 wfProfileOut( __METHOD__
);
612 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
613 wfProfileOut( __METHOD__
);
615 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
616 wfProfileOut( __METHOD__
);
620 // If mOldRev is false, it means that the
621 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
622 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
624 wfProfileOut( __METHOD__
);
629 if ( $this->mOldid
&& $this->mNewid
) {
630 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
631 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
633 if ( !$this->mRefreshCache
) {
634 $difftext = $wgMemc->get( $key );
636 wfIncrStats( 'diff_cache_hit' );
637 $difftext = $this->localiseLineNumbers( $difftext );
638 $difftext .= "\n<!-- diff cache key $key -->\n";
639 wfProfileOut( __METHOD__
);
642 } // don't try to load but save the result
644 $this->mCacheHit
= false;
646 // Loadtext is permission safe, this just clears out the diff
647 if ( !$this->loadText() ) {
648 wfProfileOut( __METHOD__
);
652 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
654 // Save to cache for 7 days
655 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
656 wfIncrStats( 'diff_uncacheable' );
657 } elseif ( $key !== false && $difftext !== false ) {
658 wfIncrStats( 'diff_cache_miss' );
659 $wgMemc->set( $key, $difftext, 7 * 86400 );
661 wfIncrStats( 'diff_uncacheable' );
663 // Replace line numbers with the text in the user's language
664 if ( $difftext !== false ) {
665 $difftext = $this->localiseLineNumbers( $difftext );
667 wfProfileOut( __METHOD__
);
672 * Make sure the proper modules are loaded before we try to
675 private function initDiffEngines() {
676 global $wgExternalDiffEngine;
677 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
678 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
679 wfDl( 'php_wikidiff' );
680 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
682 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
683 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
685 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
690 * Generate a diff, no caching
692 * @param $otext String: old text, must be already segmented
693 * @param $ntext String: new text, must be already segmented
695 function generateDiffBody( $otext, $ntext ) {
696 global $wgExternalDiffEngine, $wgContLang;
698 wfProfileIn( __METHOD__
);
700 $otext = str_replace( "\r\n", "\n", $otext );
701 $ntext = str_replace( "\r\n", "\n", $ntext );
703 $this->initDiffEngines();
705 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
706 # For historical reasons, external diff engine expects
707 # input text to be HTML-escaped already
708 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
709 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
710 wfProfileOut( __METHOD__
);
711 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
712 $this->debug( 'wikidiff1' );
715 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
716 # Better external diff engine, the 2 may some day be dropped
717 # This one does the escaping and segmenting itself
718 wfProfileIn( 'wikidiff2_do_diff' );
719 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
720 $text .= $this->debug( 'wikidiff2' );
721 wfProfileOut( 'wikidiff2_do_diff' );
722 wfProfileOut( __METHOD__
);
725 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
727 global $wgTmpDirectory;
728 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
729 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
731 $tempFile1 = fopen( $tempName1, "w" );
733 wfProfileOut( __METHOD__
);
736 $tempFile2 = fopen( $tempName2, "w" );
738 wfProfileOut( __METHOD__
);
741 fwrite( $tempFile1, $otext );
742 fwrite( $tempFile2, $ntext );
743 fclose( $tempFile1 );
744 fclose( $tempFile2 );
745 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
746 wfProfileIn( __METHOD__
. "-shellexec" );
747 $difftext = wfShellExec( $cmd );
748 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
749 wfProfileOut( __METHOD__
. "-shellexec" );
750 unlink( $tempName1 );
751 unlink( $tempName2 );
752 wfProfileOut( __METHOD__
);
757 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
758 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
759 $diffs = new Diff( $ota, $nta );
760 $formatter = new TableDiffFormatter();
761 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
762 wfProfileOut( __METHOD__
);
767 * Generate a debug comment indicating diff generating time,
768 * server node, and generator backend.
770 protected function debug( $generator = "internal" ) {
771 global $wgShowHostnames;
772 if ( !$this->enableDebugComment
) {
775 $data = array( $generator );
776 if ( $wgShowHostnames ) {
777 $data[] = wfHostname();
779 $data[] = wfTimestamp( TS_DB
);
780 return "<!-- diff generator: " .
789 * Replace line numbers with the text in the user's language
791 function localiseLineNumbers( $text ) {
792 return preg_replace_callback( '/<!--LINE (\d+)-->/',
793 array( &$this, 'localiseLineNumbersCb' ), $text );
796 function localiseLineNumbersCb( $matches ) {
798 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
799 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
804 * If there are revisions between the ones being compared, return a note saying so.
807 function getMultiNotice() {
808 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
810 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
811 // Comparing two different pages? Count would be meaningless.
815 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
816 $oldRev = $this->mNewRev
; // flip
817 $newRev = $this->mOldRev
; // flip
818 } else { // normal case
819 $oldRev = $this->mOldRev
;
820 $newRev = $this->mNewRev
;
823 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
825 $limit = 100; // use diff-multi-manyusers if too many users
826 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
827 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
829 return ''; // nothing
833 * Get a notice about how many intermediate edits and users there are
834 * @param $numEdits int
835 * @param $numUsers int
839 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
841 if ( $numUsers > $limit ) {
842 $msg = 'diff-multi-manyusers';
847 return wfMsgExt( $msg, 'parseinline',
848 $wgLang->formatnum( $numEdits ), $wgLang->formatnum( $numUsers ) );
852 * Get a header for a specified revision.
854 * @param $rev Revision
855 * @param $complete String: 'complete' to get the header wrapped depending
856 * the visibility of the revision and a link to edit the page.
857 * @return String HTML fragment
859 private function getRevisionHeader( Revision
$rev, $complete = '' ) {
862 $revtimestamp = $rev->getTimestamp();
863 $timestamp = $wgLang->timeanddate( $revtimestamp, true );
864 $dateofrev = $wgLang->date( $revtimestamp, true );
865 $timeofrev = $wgLang->time( $revtimestamp, true );
867 $header = htmlspecialchars( wfMsg(
868 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
874 if ( $complete !== 'complete' ) {
878 $title = $rev->getTitle();
880 $header = Linker
::linkKnown( $title, $header, array(),
881 array( 'oldid' => $rev->getID() ) );
883 if ( $rev->userCan( Revision
::DELETED_TEXT
) ) {
884 $editQuery = array( 'action' => 'edit' );
885 if ( !$rev->isCurrent() ) {
886 $editQuery['oldid'] = $rev->getID();
889 $msg = wfMsgHtml( $title->userCan( 'edit' ) ?
'editold' : 'viewsourceold' );
890 $header .= ' (' . Linker
::linkKnown( $title, $msg, array(), $editQuery ) . ')';
891 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
892 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
895 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
902 * Add the header to a diff body
906 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
907 // shared.css sets diff in interface language/dir, but the actual content
908 // is often in a different language, mostly the page content language/dir
909 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
910 $header = "<table class='$tableClass'>";
912 if ( !$diff && !$otitle ) {
915 <td class='diff-ntitle'>{$ntitle}</td>
919 if ( $diff ) { // Safari/Chrome show broken output if cols not used
921 <col class='diff-marker' />
922 <col class='diff-content' />
923 <col class='diff-marker' />
924 <col class='diff-content' />";
933 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
934 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
938 if ( $multi != '' ) {
939 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
941 if ( $notice != '' ) {
942 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
945 return $header . $diff . "</table>";
949 * Use specified text instead of loading from the database
951 function setText( $oldText, $newText ) {
952 $this->mOldtext
= $oldText;
953 $this->mNewtext
= $newText;
954 $this->mTextLoaded
= 2;
955 $this->mRevisionsLoaded
= true;
959 * Set the language in which the diff text is written
960 * (Defaults to page content language).
963 function setTextLanguage( $lang ) {
964 $this->mDiffLang
= wfGetLangObj( $lang );
970 private function loadRevisionIds() {
971 if ( $this->mRevisionsIdsLoaded
) {
975 $this->mRevisionsIdsLoaded
= true;
977 $old = $this->mOldid
;
978 $new = $this->mNewid
;
980 if ( $new === 'prev' ) {
981 # Show diff between revision $old and the previous one.
982 # Get previous one from DB.
983 $this->mNewid
= intval( $old );
984 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
985 } elseif ( $new === 'next' ) {
986 # Show diff between revision $old and the next one.
987 # Get next one from DB.
988 $this->mOldid
= intval( $old );
989 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
990 if ( $this->mNewid
=== false ) {
991 # if no result, NewId points to the newest old revision. The only newer
992 # revision is cur, which is "0".
996 $this->mOldid
= intval( $old );
997 $this->mNewid
= intval( $new );
998 wfRunHooks( 'NewDifferenceEngine', array( &$this->mTitle
, &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1003 * Load revision metadata for the specified articles. If newid is 0, then compare
1004 * the old article in oldid to the current article; if oldid is 0, then
1005 * compare the current article to the immediately previous one (ignoring the
1008 * If oldid is false, leave the corresponding revision object set
1009 * to false. This is impossible via ordinary user input, and is provided for
1014 function loadRevisionData() {
1015 if ( $this->mRevisionsLoaded
) {
1019 // Whether it succeeds or fails, we don't want to try again
1020 $this->mRevisionsLoaded
= true;
1022 $this->loadRevisionIds();
1024 // Load the new revision object
1025 $this->mNewRev
= $this->mNewid
1026 ? Revision
::newFromId( $this->mNewid
)
1027 : Revision
::newFromTitle( $this->mTitle
);
1029 if ( !$this->mNewRev
instanceof Revision
) {
1033 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1034 $this->mNewid
= $this->mNewRev
->getId();
1035 $this->mNewPage
= $this->mNewRev
->getTitle();
1037 // Load the old revision object
1038 $this->mOldRev
= false;
1039 if ( $this->mOldid
) {
1040 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1041 } elseif ( $this->mOldid
=== 0 ) {
1042 $rev = $this->mNewRev
->getPrevious();
1044 $this->mOldid
= $rev->getId();
1045 $this->mOldRev
= $rev;
1047 // No previous revision; mark to show as first-version only.
1048 $this->mOldid
= false;
1049 $this->mOldRev
= false;
1051 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1053 if ( is_null( $this->mOldRev
) ) {
1057 if ( $this->mOldRev
) {
1058 $this->mOldPage
= $this->mOldRev
->getTitle();
1065 * Load the text of the revisions, as well as revision data.
1069 function loadText() {
1070 if ( $this->mTextLoaded
== 2 ) {
1073 // Whether it succeeds or fails, we don't want to try again
1074 $this->mTextLoaded
= 2;
1077 if ( !$this->loadRevisionData() ) {
1080 if ( $this->mOldRev
) {
1081 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1082 if ( $this->mOldtext
=== false ) {
1086 if ( $this->mNewRev
) {
1087 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1088 if ( $this->mNewtext
=== false ) {
1096 * Load the text of the new revision, not the old one
1100 function loadNewText() {
1101 if ( $this->mTextLoaded
>= 1 ) {
1104 $this->mTextLoaded
= 1;
1106 if ( !$this->loadRevisionData() ) {
1109 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);