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
extends ContextSource
{
26 var $mOldtext, $mNewtext;
32 var $mOldPage, $mNewPage;
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 $context IContextSource context to use, anything else will be ignored
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( $context = null, $old = 0, $new = 0, $rcid = 0,
71 $refreshCache = false, $unhide = false )
73 if ( $context instanceof IContextSource
) {
74 $this->setContext( $context );
77 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
81 $this->mRcidMarkPatrolled
= intval( $rcid ); # force it to be an integer
82 $this->mRefreshCache
= $refreshCache;
83 $this->unhide
= $unhide;
89 function setReducedLineNumbers( $value = true ) {
90 $this->mReducedLineNumbers
= $value;
96 function getDiffLang() {
97 if ( $this->mDiffLang
=== null ) {
98 # Default language in which the diff text is written.
99 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
101 return $this->mDiffLang
;
107 function wasCacheHit() {
108 return $this->mCacheHit
;
114 function getOldid() {
115 $this->loadRevisionIds();
116 return $this->mOldid
;
122 function getNewid() {
123 $this->loadRevisionIds();
124 return $this->mNewid
;
128 * Look up a special:Undelete link to the given deleted revision id,
129 * as a workaround for being unable to load deleted diffs in currently.
131 * @param int $id revision ID
132 * @return mixed URL or false
134 function deletedLink( $id ) {
135 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
136 $dbr = wfGetDB( DB_SLAVE
);
137 $row = $dbr->selectRow('archive', '*',
138 array( 'ar_rev_id' => $id ),
141 $rev = Revision
::newFromArchiveRow( $row );
142 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
143 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
144 'target' => $title->getPrefixedText(),
145 'timestamp' => $rev->getTimestamp()
153 * Build a wikitext link toward a deleted revision, if viewable.
155 * @param int $id revision ID
156 * @return string wikitext fragment
158 function deletedIdMarker( $id ) {
159 $link = $this->deletedLink( $id );
161 return "[$link $id]";
167 function showDiffPage( $diffOnly = false ) {
168 wfProfileIn( __METHOD__
);
170 # Allow frames except in certain special cases
171 $out = $this->getOutput();
172 $out->allowClickjacking();
173 $out->setRobotPolicy( 'noindex,nofollow' );
175 if ( !$this->loadRevisionData() ) {
176 // Sounds like a deleted revision... Let's see what we can do.
177 $t = $this->getTitle()->getPrefixedText();
178 $d = $this->msg( 'missingarticle-diff',
179 $this->deletedIdMarker( $this->mOldid
),
180 $this->deletedIdMarker( $this->mNewid
) )->escaped();
181 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
182 $out->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
183 wfProfileOut( __METHOD__
);
187 $user = $this->getUser();
188 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
189 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
190 $permErrors = wfMergeErrorArrays( $permErrors,
191 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
193 if ( count( $permErrors ) ) {
194 wfProfileOut( __METHOD__
);
195 throw new PermissionsError( 'read', $permErrors );
198 # If external diffs are enabled both globally and for the user,
199 # we'll use the application/x-external-editor interface to call
200 # an external diff tool like kompare, kdiff3, etc.
201 if ( ExternalEdit
::useExternalEngine( $this->getContext(), 'diff' ) ) {
203 'File' => array( 'Extension' => 'wiki', 'URL' =>
204 # This should be mOldPage, but it may not be set, see below.
205 $this->mNewPage
->getCanonicalURL( array(
206 'action' => 'raw', 'oldid' => $this->mOldid
) )
208 'File2' => array( 'Extension' => 'wiki', 'URL' =>
209 $this->mNewPage
->getCanonicalURL( array(
210 'action' => 'raw', 'oldid' => $this->mNewid
) )
214 $externalEditor = new ExternalEdit( $this->getContext(), $urls );
215 $externalEditor->execute();
217 wfProfileOut( __METHOD__
);
225 # Carry over 'diffonly' param via navigation links
226 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
227 $query['diffonly'] = $diffOnly;
229 # Cascade unhide param in links for easy deletion browsing
230 if ( $this->unhide
) {
231 $query['unhide'] = 1;
234 # Check if one of the revisions is deleted/suppressed
235 $deleted = $suppressed = false;
236 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
238 # mOldRev is false if the difference engine is called with a "vague" query for
239 # a diff between a version V and its previous version V' AND the version V
240 # is the first version of that article. In that case, V' does not exist.
241 if ( $this->mOldRev
=== false ) {
242 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
246 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
248 $sk = $this->getSkin();
249 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
250 $sk->suppressQuickbar();
253 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
254 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
257 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
258 $this->mNewPage
->getPrefixedText() ) );
259 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
263 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
264 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
265 $out->preventClickjacking();
266 $rollback = '   ' . Linker
::generateRollback( $this->mNewRev
);
268 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
269 $undoLink = ' ' . $this->msg( 'parentheses' )->rawParams(
270 Html
::element( 'a', array(
271 'href' => $this->mNewPage
->getLocalUrl( array(
273 'undoafter' => $this->mOldid
,
274 'undo' => $this->mNewid
) ),
275 'title' => Linker
::titleAttrib( 'undo' )
277 $this->msg( 'editundo' )->text()
282 # Make "previous revision link"
283 if ( $samePage && $this->mOldRev
->getPrevious() ) {
284 $prevlink = Linker
::linkKnown(
286 $this->msg( 'previousdiff' )->escaped(),
287 array( 'id' => 'differences-prevlink' ),
288 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
291 $prevlink = ' ';
294 if ( $this->mOldRev
->isMinor() ) {
295 $oldminor = ChangesList
::flag( 'minor' );
300 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
301 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
303 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
304 '<div id="mw-diff-otitle2">' .
305 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
306 '<div id="mw-diff-otitle3">' . $oldminor .
307 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
308 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
310 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
311 $deleted = true; // old revisions text is hidden
312 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
313 $suppressed = true; // also suppressed
317 # Check if this user can see the revisions
318 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
323 # Make "next revision link"
324 # Skip next link on the top revision
325 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
326 $nextlink = Linker
::linkKnown(
328 $this->msg( 'nextdiff' )->escaped(),
329 array( 'id' => 'differences-nextlink' ),
330 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
333 $nextlink = ' ';
336 if ( $this->mNewRev
->isMinor() ) {
337 $newminor = ChangesList
::flag( 'minor' );
342 # Handle RevisionDelete links...
343 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
344 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
346 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
347 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
349 '<div id="mw-diff-ntitle3">' . $newminor .
350 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
351 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
353 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
354 $deleted = true; // new revisions text is hidden
355 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
356 $suppressed = true; // also suppressed
359 # If the diff cannot be shown due to a deleted revision, then output
360 # the diff header and links to unhide (if available)...
361 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
362 $this->showDiffStyle();
363 $multi = $this->getMultiNotice();
364 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
366 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
367 # Give explanation for why revision is not visible
368 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
371 # Give explanation and add a link to view the diff...
372 $link = $this->getTitle()->getFullUrl( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
373 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
374 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
376 # Otherwise, output a regular diff...
378 # Add deletion notice if the user is viewing deleted content
381 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
382 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
384 $this->showDiff( $oldHeader, $newHeader, $notice );
386 $this->renderNewRevision();
389 wfProfileOut( __METHOD__
);
393 * Get a link to mark the change as patrolled, or '' if there's either no
394 * revision to patrol or the user is not allowed to to it.
395 * Side effect: this method will call OutputPage::preventClickjacking()
396 * when a link is builded.
400 protected function markPatrolledLink() {
401 global $wgUseRCPatrol;
403 if ( $this->mMarkPatrolledLink
=== null ) {
404 // Prepare a change patrol link, if applicable
405 if ( $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $this->getUser() ) ) {
406 // If we've been given an explicit change identifier, use it; saves time
407 if ( $this->mRcidMarkPatrolled
) {
408 $rcid = $this->mRcidMarkPatrolled
;
409 $rc = RecentChange
::newFromId( $rcid );
410 // Already patrolled?
411 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
413 // Look for an unpatrolled change corresponding to this diff
414 $db = wfGetDB( DB_SLAVE
);
415 $change = RecentChange
::newFromConds(
417 // Redundant user,timestamp condition so we can use the existing index
418 'rc_user_text' => $this->mNewRev
->getRawUserText(),
419 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
420 'rc_this_oldid' => $this->mNewid
,
421 'rc_last_oldid' => $this->mOldid
,
426 if ( $change instanceof RecentChange
) {
427 $rcid = $change->mAttribs
['rc_id'];
428 $this->mRcidMarkPatrolled
= $rcid;
436 $this->getOutput()->preventClickjacking();
437 $token = $this->getUser()->getEditToken( $rcid );
438 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
440 $this->msg( 'markaspatrolleddiff' )->escaped(),
443 'action' => 'markpatrolled',
449 $this->mMarkPatrolledLink
= '';
452 $this->mMarkPatrolledLink
= '';
456 return $this->mMarkPatrolledLink
;
460 * @param $rev Revision
463 protected function revisionDeleteLink( $rev ) {
464 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
465 if ( $link !== '' ) {
466 $link = '   ' . $link . ' ';
472 * Show the new revision of the page.
474 function renderNewRevision() {
475 wfProfileIn( __METHOD__
);
476 $out = $this->getOutput();
477 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
478 # Add "current version as of X" title
479 $out->addHTML( "<hr class='diff-hr' />
480 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
481 # Page content may be handled by a hooked call instead...
482 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
483 $this->loadNewText();
484 $out->setRevisionId( $this->mNewid
);
485 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
486 $out->setArticleFlag( true );
488 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
489 // Stolen from Article::view --AG 2007-10-11
490 // Give hooks a chance to customise the output
491 // @TODO: standardize this crap into one function
492 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mNewPage
, $out ) ) ) {
493 // Wrap the whole lot in a <pre> and don't parse
495 preg_match( '!\.(css|js)$!u', $this->mNewPage
->getText(), $m );
496 $out->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
497 $out->addHTML( htmlspecialchars( $this->mNewtext
) );
498 $out->addHTML( "\n</pre>\n" );
500 } elseif ( !wfRunHooks( 'ArticleViewCustom', array( $this->mNewtext
, $this->mNewPage
, $out ) ) ) {
501 // Handled by extension
504 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
505 // If the Title stored in the context is the same as the one
506 // of the new revision, we can use its associated WikiPage
508 $wikiPage = $this->getWikiPage();
510 // Otherwise we need to create our own WikiPage object
511 $wikiPage = WikiPage
::factory( $this->mNewPage
);
514 $parserOptions = ParserOptions
::newFromContext( $this->getContext() );
515 $parserOptions->enableLimitReport();
516 $parserOptions->setTidy( true );
518 if ( !$this->mNewRev
->isCurrent() ) {
519 $parserOptions->setEditSection( false );
522 $parserOutput = $wikiPage->getParserOutput( $parserOptions, $this->mNewid
);
524 # WikiPage::getParserOutput() should not return false, but just in case
525 if( $parserOutput ) {
526 $out->addParserOutput( $parserOutput );
530 # Add redundant patrol link on bottom...
531 $out->addHTML( $this->markPatrolledLink() );
533 wfProfileOut( __METHOD__
);
537 * Get the diff text, send it to the OutputPage object
538 * Returns false if the diff could not be generated, otherwise returns true
542 function showDiff( $otitle, $ntitle, $notice = '' ) {
543 $diff = $this->getDiff( $otitle, $ntitle, $notice );
544 if ( $diff === false ) {
545 $this->getOutput()->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
548 $this->showDiffStyle();
549 $this->getOutput()->addHTML( $diff );
555 * Add style sheets and supporting JS for diff display.
557 function showDiffStyle() {
558 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
562 * Get complete diff table, including header
564 * @param $otitle Title: old title
565 * @param $ntitle Title: new title
566 * @param $notice String: HTML between diff header and body
569 function getDiff( $otitle, $ntitle, $notice = '' ) {
570 $body = $this->getDiffBody();
571 if ( $body === false ) {
574 $multi = $this->getMultiNotice();
575 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
580 * Get the diff table body, without header
582 * @return mixed (string/false)
584 public function getDiffBody() {
586 wfProfileIn( __METHOD__
);
587 $this->mCacheHit
= true;
588 // Check if the diff should be hidden from this user
589 if ( !$this->loadRevisionData() ) {
590 wfProfileOut( __METHOD__
);
592 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
593 wfProfileOut( __METHOD__
);
595 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
596 wfProfileOut( __METHOD__
);
600 // If mOldRev is false, it means that the
601 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
602 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
604 wfProfileOut( __METHOD__
);
609 if ( $this->mOldid
&& $this->mNewid
) {
610 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
611 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
613 if ( !$this->mRefreshCache
) {
614 $difftext = $wgMemc->get( $key );
616 wfIncrStats( 'diff_cache_hit' );
617 $difftext = $this->localiseLineNumbers( $difftext );
618 $difftext .= "\n<!-- diff cache key $key -->\n";
619 wfProfileOut( __METHOD__
);
622 } // don't try to load but save the result
624 $this->mCacheHit
= false;
626 // Loadtext is permission safe, this just clears out the diff
627 if ( !$this->loadText() ) {
628 wfProfileOut( __METHOD__
);
632 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
634 // Save to cache for 7 days
635 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
636 wfIncrStats( 'diff_uncacheable' );
637 } elseif ( $key !== false && $difftext !== false ) {
638 wfIncrStats( 'diff_cache_miss' );
639 $wgMemc->set( $key, $difftext, 7 * 86400 );
641 wfIncrStats( 'diff_uncacheable' );
643 // Replace line numbers with the text in the user's language
644 if ( $difftext !== false ) {
645 $difftext = $this->localiseLineNumbers( $difftext );
647 wfProfileOut( __METHOD__
);
652 * Make sure the proper modules are loaded before we try to
655 private function initDiffEngines() {
656 global $wgExternalDiffEngine;
657 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
658 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
659 wfDl( 'php_wikidiff' );
660 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
662 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
663 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
665 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
670 * Generate a diff, no caching
672 * @param $otext String: old text, must be already segmented
673 * @param $ntext String: new text, must be already segmented
674 * @return bool|string
676 function generateDiffBody( $otext, $ntext ) {
677 global $wgExternalDiffEngine, $wgContLang;
679 wfProfileIn( __METHOD__
);
681 $otext = str_replace( "\r\n", "\n", $otext );
682 $ntext = str_replace( "\r\n", "\n", $ntext );
684 $this->initDiffEngines();
686 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
687 # For historical reasons, external diff engine expects
688 # input text to be HTML-escaped already
689 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
690 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
691 wfProfileOut( __METHOD__
);
692 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
693 $this->debug( 'wikidiff1' );
696 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
697 # Better external diff engine, the 2 may some day be dropped
698 # This one does the escaping and segmenting itself
699 wfProfileIn( 'wikidiff2_do_diff' );
700 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
701 $text .= $this->debug( 'wikidiff2' );
702 wfProfileOut( 'wikidiff2_do_diff' );
703 wfProfileOut( __METHOD__
);
706 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
708 global $wgTmpDirectory;
709 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
710 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
712 $tempFile1 = fopen( $tempName1, "w" );
714 wfProfileOut( __METHOD__
);
717 $tempFile2 = fopen( $tempName2, "w" );
719 wfProfileOut( __METHOD__
);
722 fwrite( $tempFile1, $otext );
723 fwrite( $tempFile2, $ntext );
724 fclose( $tempFile1 );
725 fclose( $tempFile2 );
726 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
727 wfProfileIn( __METHOD__
. "-shellexec" );
728 $difftext = wfShellExec( $cmd );
729 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
730 wfProfileOut( __METHOD__
. "-shellexec" );
731 unlink( $tempName1 );
732 unlink( $tempName2 );
733 wfProfileOut( __METHOD__
);
738 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
739 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
740 $diffs = new Diff( $ota, $nta );
741 $formatter = new TableDiffFormatter();
742 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
743 wfProfileOut( __METHOD__
);
748 * Generate a debug comment indicating diff generating time,
749 * server node, and generator backend.
752 protected function debug( $generator = "internal" ) {
753 global $wgShowHostnames;
754 if ( !$this->enableDebugComment
) {
757 $data = array( $generator );
758 if ( $wgShowHostnames ) {
759 $data[] = wfHostname();
761 $data[] = wfTimestamp( TS_DB
);
762 return "<!-- diff generator: " .
771 * Replace line numbers with the text in the user's language
774 function localiseLineNumbers( $text ) {
775 return preg_replace_callback( '/<!--LINE (\d+)-->/',
776 array( &$this, 'localiseLineNumbersCb' ), $text );
779 function localiseLineNumbersCb( $matches ) {
780 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
781 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
786 * If there are revisions between the ones being compared, return a note saying so.
789 function getMultiNotice() {
790 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
792 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
793 // Comparing two different pages? Count would be meaningless.
797 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
798 $oldRev = $this->mNewRev
; // flip
799 $newRev = $this->mOldRev
; // flip
800 } else { // normal case
801 $oldRev = $this->mOldRev
;
802 $newRev = $this->mNewRev
;
805 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
807 $limit = 100; // use diff-multi-manyusers if too many users
808 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
809 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
811 return ''; // nothing
815 * Get a notice about how many intermediate edits and users there are
816 * @param $numEdits int
817 * @param $numUsers int
821 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
822 if ( $numUsers > $limit ) {
823 $msg = 'diff-multi-manyusers';
828 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
832 * Get a header for a specified revision.
834 * @param $rev Revision
835 * @param $complete String: 'complete' to get the header wrapped depending
836 * the visibility of the revision and a link to edit the page.
837 * @return String HTML fragment
839 private function getRevisionHeader( Revision
$rev, $complete = '' ) {
840 $lang = $this->getLanguage();
841 $user = $this->getUser();
842 $revtimestamp = $rev->getTimestamp();
843 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
844 $dateofrev = $lang->userDate( $revtimestamp, $user );
845 $timeofrev = $lang->userTime( $revtimestamp, $user );
847 $header = $this->msg(
848 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
854 if ( $complete !== 'complete' ) {
858 $title = $rev->getTitle();
860 $header = Linker
::linkKnown( $title, $header, array(),
861 array( 'oldid' => $rev->getID() ) );
863 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
864 $editQuery = array( 'action' => 'edit' );
865 if ( !$rev->isCurrent() ) {
866 $editQuery['oldid'] = $rev->getID();
869 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
870 $header .= ' (' . Linker
::linkKnown( $title, $msg, array(), $editQuery ) . ')';
871 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
872 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
875 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
882 * Add the header to a diff body
886 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
887 // shared.css sets diff in interface language/dir, but the actual content
888 // is often in a different language, mostly the page content language/dir
889 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
890 $header = "<table class='$tableClass'>";
892 if ( !$diff && !$otitle ) {
895 <td class='diff-ntitle'>{$ntitle}</td>
899 if ( $diff ) { // Safari/Chrome show broken output if cols not used
901 <col class='diff-marker' />
902 <col class='diff-content' />
903 <col class='diff-marker' />
904 <col class='diff-content' />";
913 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
914 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
918 if ( $multi != '' ) {
919 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
921 if ( $notice != '' ) {
922 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
925 return $header . $diff . "</table>";
929 * Use specified text instead of loading from the database
931 function setText( $oldText, $newText ) {
932 $this->mOldtext
= $oldText;
933 $this->mNewtext
= $newText;
934 $this->mTextLoaded
= 2;
935 $this->mRevisionsLoaded
= true;
939 * Set the language in which the diff text is written
940 * (Defaults to page content language).
943 function setTextLanguage( $lang ) {
944 $this->mDiffLang
= wfGetLangObj( $lang );
950 private function loadRevisionIds() {
951 if ( $this->mRevisionsIdsLoaded
) {
955 $this->mRevisionsIdsLoaded
= true;
957 $old = $this->mOldid
;
958 $new = $this->mNewid
;
960 if ( $new === 'prev' ) {
961 # Show diff between revision $old and the previous one.
962 # Get previous one from DB.
963 $this->mNewid
= intval( $old );
964 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
965 } elseif ( $new === 'next' ) {
966 # Show diff between revision $old and the next one.
967 # Get next one from DB.
968 $this->mOldid
= intval( $old );
969 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
970 if ( $this->mNewid
=== false ) {
971 # if no result, NewId points to the newest old revision. The only newer
972 # revision is cur, which is "0".
976 $this->mOldid
= intval( $old );
977 $this->mNewid
= intval( $new );
978 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
983 * Load revision metadata for the specified articles. If newid is 0, then compare
984 * the old article in oldid to the current article; if oldid is 0, then
985 * compare the current article to the immediately previous one (ignoring the
988 * If oldid is false, leave the corresponding revision object set
989 * to false. This is impossible via ordinary user input, and is provided for
994 function loadRevisionData() {
995 if ( $this->mRevisionsLoaded
) {
999 // Whether it succeeds or fails, we don't want to try again
1000 $this->mRevisionsLoaded
= true;
1002 $this->loadRevisionIds();
1004 // Load the new revision object
1005 $this->mNewRev
= $this->mNewid
1006 ? Revision
::newFromId( $this->mNewid
)
1007 : Revision
::newFromTitle( $this->getTitle() );
1009 if ( !$this->mNewRev
instanceof Revision
) {
1013 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1014 $this->mNewid
= $this->mNewRev
->getId();
1015 $this->mNewPage
= $this->mNewRev
->getTitle();
1017 // Load the old revision object
1018 $this->mOldRev
= false;
1019 if ( $this->mOldid
) {
1020 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1021 } elseif ( $this->mOldid
=== 0 ) {
1022 $rev = $this->mNewRev
->getPrevious();
1024 $this->mOldid
= $rev->getId();
1025 $this->mOldRev
= $rev;
1027 // No previous revision; mark to show as first-version only.
1028 $this->mOldid
= false;
1029 $this->mOldRev
= false;
1031 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1033 if ( is_null( $this->mOldRev
) ) {
1037 if ( $this->mOldRev
) {
1038 $this->mOldPage
= $this->mOldRev
->getTitle();
1045 * Load the text of the revisions, as well as revision data.
1049 function loadText() {
1050 if ( $this->mTextLoaded
== 2 ) {
1053 // Whether it succeeds or fails, we don't want to try again
1054 $this->mTextLoaded
= 2;
1057 if ( !$this->loadRevisionData() ) {
1060 if ( $this->mOldRev
) {
1061 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1062 if ( $this->mOldtext
=== false ) {
1066 if ( $this->mNewRev
) {
1067 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1068 if ( $this->mNewtext
=== false ) {
1076 * Load the text of the new revision, not the old one
1080 function loadNewText() {
1081 if ( $this->mTextLoaded
>= 1 ) {
1084 $this->mTextLoaded
= 1;
1086 if ( !$this->loadRevisionData() ) {
1089 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);