3 * User interface for the difference engine.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup DifferenceEngine
23 use MediaWiki\MediaWikiServices
;
25 /** @deprecated use class constant instead */
26 define( 'MW_DIFF_VERSION', '1.11a' );
30 * @ingroup DifferenceEngine
32 class DifferenceEngine
extends ContextSource
{
34 * Constant to indicate diff cache compatibility.
35 * Bump this when changing the diff formatting in a way that
36 * fixes important bugs or such to force cached diff views to
39 const DIFF_VERSION
= MW_DIFF_VERSION
;
71 /** @var bool Have the revisions IDs been loaded */
72 private $mRevisionsIdsLoaded = false;
74 /** @var bool Have the revisions been loaded */
75 public $mRevisionsLoaded = false;
77 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
78 public $mTextLoaded = 0;
80 /** @var bool Was the diff fetched from cache? */
81 public $mCacheHit = false;
84 * Set this to true to add debug info to the HTML output.
85 * Warning: this may cause RSS readers to spuriously mark articles as "new"
88 public $enableDebugComment = false;
90 /** @var bool If true, line X is not displayed when X is 1, for example
91 * to increase readability and conserve space with many small diffs.
93 protected $mReducedLineNumbers = false;
95 /** @var string Link to action=markpatrolled */
96 protected $mMarkPatrolledLink = null;
98 /** @var bool Show rev_deleted content if allowed */
99 protected $unhide = false;
101 /** @var bool Refresh the diff cache */
102 protected $mRefreshCache = false;
107 * @param IContextSource $context Context to use, anything else will be ignored
108 * @param int $old Old ID we want to show and diff with.
109 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
110 * @param int $rcid Deprecated, no longer used!
111 * @param bool $refreshCache If set, refreshes the diff cache
112 * @param bool $unhide If set, allow viewing deleted revs
114 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
115 $refreshCache = false, $unhide = false
117 if ( $context instanceof IContextSource
) {
118 $this->setContext( $context );
121 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
123 $this->mOldid
= $old;
124 $this->mNewid
= $new;
125 $this->mRefreshCache
= $refreshCache;
126 $this->unhide
= $unhide;
132 public function setReducedLineNumbers( $value = true ) {
133 $this->mReducedLineNumbers
= $value;
139 public function getDiffLang() {
140 if ( $this->mDiffLang
=== null ) {
141 # Default language in which the diff text is written.
142 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
145 return $this->mDiffLang
;
151 public function wasCacheHit() {
152 return $this->mCacheHit
;
158 public function getOldid() {
159 $this->loadRevisionIds();
161 return $this->mOldid
;
167 public function getNewid() {
168 $this->loadRevisionIds();
170 return $this->mNewid
;
174 * Look up a special:Undelete link to the given deleted revision id,
175 * as a workaround for being unable to load deleted diffs in currently.
177 * @param int $id Revision ID
179 * @return string|bool Link HTML or false
181 public function deletedLink( $id ) {
182 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
183 $dbr = wfGetDB( DB_REPLICA
);
184 $row = $dbr->selectRow( 'archive',
185 Revision
::selectArchiveFields(),
186 [ 'ar_rev_id' => $id ],
189 $rev = Revision
::newFromArchiveRow( $row );
190 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
192 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
193 'target' => $title->getPrefixedText(),
194 'timestamp' => $rev->getTimestamp()
203 * Build a wikitext link toward a deleted revision, if viewable.
205 * @param int $id Revision ID
207 * @return string Wikitext fragment
209 public function deletedIdMarker( $id ) {
210 $link = $this->deletedLink( $id );
212 return "[$link $id]";
218 private function showMissingRevision() {
219 $out = $this->getOutput();
222 if ( $this->mOldRev
=== null ||
223 ( $this->mOldRev
&& $this->mOldContent
=== null )
225 $missing[] = $this->deletedIdMarker( $this->mOldid
);
227 if ( $this->mNewRev
=== null ||
228 ( $this->mNewRev
&& $this->mNewContent
=== null )
230 $missing[] = $this->deletedIdMarker( $this->mNewid
);
233 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
234 $msg = $this->msg( 'difference-missing-revision' )
235 ->params( $this->getLanguage()->listToText( $missing ) )
236 ->numParams( count( $missing ) )
238 $out->addHTML( $msg );
241 public function showDiffPage( $diffOnly = false ) {
242 # Allow frames except in certain special cases
243 $out = $this->getOutput();
244 $out->allowClickjacking();
245 $out->setRobotPolicy( 'noindex,nofollow' );
247 // Allow extensions to add any extra output here
248 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
250 if ( !$this->loadRevisionData() ) {
251 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
252 $this->showMissingRevision();
257 $user = $this->getUser();
258 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
259 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
260 $permErrors = wfMergeErrorArrays( $permErrors,
261 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
263 if ( count( $permErrors ) ) {
264 throw new PermissionsError( 'read', $permErrors );
270 # Carry over 'diffonly' param via navigation links
271 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
272 $query['diffonly'] = $diffOnly;
274 # Cascade unhide param in links for easy deletion browsing
275 if ( $this->unhide
) {
276 $query['unhide'] = 1;
279 # Check if one of the revisions is deleted/suppressed
280 $deleted = $suppressed = false;
281 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
285 # mOldRev is false if the difference engine is called with a "vague" query for
286 # a diff between a version V and its previous version V' AND the version V
287 # is the first version of that article. In that case, V' does not exist.
288 if ( $this->mOldRev
=== false ) {
289 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
292 // Allow extensions to change the $oldHeader variable
293 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
295 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
297 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
298 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
301 $out->setPageTitle( $this->msg( 'difference-title-multipage',
302 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
303 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
307 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
308 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
309 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
310 if ( $rollbackLink ) {
311 $out->preventClickjacking();
312 $rollback = '   ' . $rollbackLink;
316 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
317 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
319 $undoLink = Html
::element( 'a', [
320 'href' => $this->mNewPage
->getLocalURL( [
322 'undoafter' => $this->mOldid
,
323 'undo' => $this->mNewid
325 'title' => Linker
::titleAttrib( 'undo' ),
327 $this->msg( 'editundo' )->text()
329 $revisionTools['mw-diff-undo'] = $undoLink;
333 # Make "previous revision link"
334 if ( $samePage && $this->mOldRev
->getPrevious() ) {
335 $prevlink = Linker
::linkKnown(
337 $this->msg( 'previousdiff' )->escaped(),
338 [ 'id' => 'differences-prevlink' ],
339 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
342 $prevlink = ' ';
345 if ( $this->mOldRev
->isMinor() ) {
346 $oldminor = ChangesList
::flag( 'minor' );
351 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
352 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
353 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
355 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
356 '<div id="mw-diff-otitle2">' .
357 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
358 '<div id="mw-diff-otitle3">' . $oldminor .
359 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
360 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
361 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
363 // Allow extensions to change the $oldHeader variable
364 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
365 $diffOnly, $ldel, $this->unhide
] );
367 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
368 $deleted = true; // old revisions text is hidden
369 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
370 $suppressed = true; // also suppressed
374 # Check if this user can see the revisions
375 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
380 $out->addJsConfigVars( [
381 'wgDiffOldId' => $this->mOldid
,
382 'wgDiffNewId' => $this->mNewid
,
385 # Make "next revision link"
386 # Skip next link on the top revision
387 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
388 $nextlink = Linker
::linkKnown(
390 $this->msg( 'nextdiff' )->escaped(),
391 [ 'id' => 'differences-nextlink' ],
392 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
395 $nextlink = ' ';
398 if ( $this->mNewRev
->isMinor() ) {
399 $newminor = ChangesList
::flag( 'minor' );
404 # Handle RevisionDelete links...
405 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
407 # Allow extensions to define their own revision tools
408 Hooks
::run( 'DiffRevisionTools',
409 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
410 $formattedRevisionTools = [];
411 // Put each one in parentheses (poor man's button)
412 foreach ( $revisionTools as $key => $tool ) {
413 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
414 $element = Html
::rawElement(
416 [ 'class' => $toolClass ],
417 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
419 $formattedRevisionTools[] = $element;
421 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
422 ' ' . implode( ' ', $formattedRevisionTools );
423 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
425 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
426 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
428 '<div id="mw-diff-ntitle3">' . $newminor .
429 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
430 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
431 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
433 // Allow extensions to change the $newHeader variable
434 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
435 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
437 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
438 $deleted = true; // new revisions text is hidden
439 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
440 $suppressed = true; // also suppressed
444 # If the diff cannot be shown due to a deleted revision, then output
445 # the diff header and links to unhide (if available)...
446 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
447 $this->showDiffStyle();
448 $multi = $this->getMultiNotice();
449 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
451 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
452 # Give explanation for why revision is not visible
453 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
456 # Give explanation and add a link to view the diff...
457 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
458 $link = $this->getTitle()->getFullURL( $query );
459 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
461 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
465 # Otherwise, output a regular diff...
467 # Add deletion notice if the user is viewing deleted content
470 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
471 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
472 $this->msg( $msg )->parse() .
475 $this->showDiff( $oldHeader, $newHeader, $notice );
477 $this->renderNewRevision();
483 * Build a link to mark a change as patrolled.
485 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
486 * Side effect: When the patrol link is build, this method will call
487 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
489 * @return string HTML or empty string
491 public function markPatrolledLink() {
492 if ( $this->mMarkPatrolledLink
=== null ) {
493 $linkInfo = $this->getMarkPatrolledLinkInfo();
494 // If false, there is no patrol link needed/allowed
496 $this->mMarkPatrolledLink
= '';
498 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
501 $this->msg( 'markaspatrolleddiff' )->escaped(),
504 'action' => 'markpatrolled',
505 'rcid' => $linkInfo['rcid'],
508 // Allow extensions to change the markpatrolled link
509 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
510 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
513 return $this->mMarkPatrolledLink
;
517 * Returns an array of meta data needed to build a "mark as patrolled" link and
518 * adds the mediawiki.page.patrol.ajax to the output.
520 * @return array|false An array of meta data for a patrol link (rcid only)
521 * or false if no link is needed
523 protected function getMarkPatrolledLinkInfo() {
524 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
526 $user = $this->getUser();
528 // Prepare a change patrol link, if applicable
530 // Is patrolling enabled and the user allowed to?
531 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
532 // Only do this if the revision isn't more than 6 hours older
533 // than the Max RC age (6h because the RC might not be cleaned out regularly)
534 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
536 // Look for an unpatrolled change corresponding to this diff
537 $db = wfGetDB( DB_REPLICA
);
538 $change = RecentChange
::newFromConds(
540 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
541 'rc_this_oldid' => $this->mNewid
,
547 if ( $change && !$change->getPerformer()->equals( $user ) ) {
548 $rcid = $change->getAttribute( 'rc_id' );
550 // None found or the page has been created by the current user.
551 // If the user could patrol this it already would be patrolled
555 // Allow extensions to possibly change the rcid here
556 // For example the rcid might be set to zero due to the user
557 // being the same as the performer of the change but an extension
558 // might still want to show it under certain conditions
559 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
563 $this->getOutput()->preventClickjacking();
564 if ( $wgEnableAPI && $wgEnableWriteAPI
565 && $user->isAllowed( 'writeapi' )
567 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
576 // No mark as patrolled link applicable
581 * @param Revision $rev
585 protected function revisionDeleteLink( $rev ) {
586 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
587 if ( $link !== '' ) {
588 $link = '   ' . $link . ' ';
595 * Show the new revision of the page.
597 public function renderNewRevision() {
598 $out = $this->getOutput();
599 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
600 # Add "current version as of X" title
601 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
602 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
603 # Page content may be handled by a hooked call instead...
604 # @codingStandardsIgnoreStart Ignoring long lines.
605 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
606 $this->loadNewText();
607 $out->setRevisionId( $this->mNewid
);
608 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
609 $out->setArticleFlag( true );
611 if ( !Hooks
::run( 'ArticleContentViewCustom', [ $this->mNewContent
, $this->mNewPage
, $out ] ) ) {
612 // Handled by extension
615 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
616 // If the Title stored in the context is the same as the one
617 // of the new revision, we can use its associated WikiPage
619 $wikiPage = $this->getWikiPage();
621 // Otherwise we need to create our own WikiPage object
622 $wikiPage = WikiPage
::factory( $this->mNewPage
);
625 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
627 # WikiPage::getParserOutput() should not return false, but just in case
628 if ( $parserOutput ) {
629 // Allow extensions to change parser output here
630 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput', [ $this, $out, $parserOutput, $wikiPage ] ) ) {
631 $out->addParserOutput( $parserOutput );
636 # @codingStandardsIgnoreEnd
638 // Allow extensions to optionally not show the final patrolled link
639 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
640 # Add redundant patrol link on bottom...
641 $out->addHTML( $this->markPatrolledLink() );
645 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
646 $parserOptions = $page->makeParserOptions( $this->getContext() );
648 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( 'edit', $this->getUser() ) ) {
649 $parserOptions->setEditSection( false );
652 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
654 return $parserOutput;
658 * Get the diff text, send it to the OutputPage object
659 * Returns false if the diff could not be generated, otherwise returns true
661 * @param string|bool $otitle Header for old text or false
662 * @param string|bool $ntitle Header for new text or false
663 * @param string $notice HTML between diff header and body
667 public function showDiff( $otitle, $ntitle, $notice = '' ) {
668 // Allow extensions to affect the output here
669 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
671 $diff = $this->getDiff( $otitle, $ntitle, $notice );
672 if ( $diff === false ) {
673 $this->showMissingRevision();
677 $this->showDiffStyle();
678 $this->getOutput()->addHTML( $diff );
685 * Add style sheets for diff display.
687 public function showDiffStyle() {
688 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
692 * Get complete diff table, including header
694 * @param string|bool $otitle Header for old text or false
695 * @param string|bool $ntitle Header for new text or false
696 * @param string $notice HTML between diff header and body
700 public function getDiff( $otitle, $ntitle, $notice = '' ) {
701 $body = $this->getDiffBody();
702 if ( $body === false ) {
706 $multi = $this->getMultiNotice();
707 // Display a message when the diff is empty
708 if ( $body === '' ) {
709 $notice .= '<div class="mw-diff-empty">' .
710 $this->msg( 'diff-empty' )->parse() .
714 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
718 * Get the diff table body, without header
720 * @return mixed (string/false)
722 public function getDiffBody() {
723 $this->mCacheHit
= true;
724 // Check if the diff should be hidden from this user
725 if ( !$this->loadRevisionData() ) {
727 } elseif ( $this->mOldRev
&&
728 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
731 } elseif ( $this->mNewRev
&&
732 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
737 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
738 && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
740 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
746 $cache = ObjectCache
::getMainWANInstance();
747 if ( $this->mOldid
&& $this->mNewid
) {
748 $key = $this->getDiffBodyCacheKey();
751 if ( !$this->mRefreshCache
) {
752 $difftext = $cache->get( $key );
754 wfIncrStats( 'diff_cache.hit' );
755 $difftext = $this->localiseLineNumbers( $difftext );
756 $difftext .= "\n<!-- diff cache key $key -->\n";
760 } // don't try to load but save the result
762 $this->mCacheHit
= false;
764 // Loadtext is permission safe, this just clears out the diff
765 if ( !$this->loadText() ) {
769 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
771 // Avoid PHP 7.1 warning from passing $this by reference
774 // Save to cache for 7 days
775 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
776 wfIncrStats( 'diff_cache.uncacheable' );
777 } elseif ( $key !== false && $difftext !== false ) {
778 wfIncrStats( 'diff_cache.miss' );
779 $cache->set( $key, $difftext, 7 * 86400 );
781 wfIncrStats( 'diff_cache.uncacheable' );
783 // Replace line numbers with the text in the user's language
784 if ( $difftext !== false ) {
785 $difftext = $this->localiseLineNumbers( $difftext );
792 * Returns the cache key for diff body text or content.
796 * @throws MWException
799 protected function getDiffBodyCacheKey() {
800 if ( !$this->mOldid ||
!$this->mNewid
) {
801 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
804 return wfMemcKey( 'diff', 'version', self
::DIFF_VERSION
,
805 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
809 * Generate a diff, no caching.
811 * This implementation uses generateTextDiffBody() to generate a diff based on the default
812 * serialization of the given Content objects. This will fail if $old or $new are not
813 * instances of TextContent.
815 * Subclasses may override this to provide a different rendering for the diff,
816 * perhaps taking advantage of the content's native form. This is required for all content
817 * models that are not text based.
821 * @param Content $old Old content
822 * @param Content $new New content
824 * @throws MWException If old or new content is not an instance of TextContent.
825 * @return bool|string
827 public function generateContentDiffBody( Content
$old, Content
$new ) {
828 if ( !( $old instanceof TextContent
) ) {
829 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
830 "override generateContentDiffBody to fix this." );
833 if ( !( $new instanceof TextContent
) ) {
834 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
835 . "override generateContentDiffBody to fix this." );
838 $otext = $old->serialize();
839 $ntext = $new->serialize();
841 return $this->generateTextDiffBody( $otext, $ntext );
845 * Generate a diff, no caching
847 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
849 * @param string $otext Old text, must be already segmented
850 * @param string $ntext New text, must be already segmented
852 * @return bool|string
854 public function generateTextDiffBody( $otext, $ntext ) {
855 $diff = function () use ( $otext, $ntext ) {
856 $time = microtime( true );
858 $result = $this->textDiff( $otext, $ntext );
860 $time = intval( ( microtime( true ) - $time ) * 1000 );
861 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
862 // Log requests slower than 99th percentile
863 if ( $time > 100 && $this->mOldPage
&& $this->mNewPage
) {
865 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
872 * @param Status $status
875 $error = function ( $status ) {
876 throw new FatalError( $status->getWikiText() );
879 // Use PoolCounter if the diff looks like it can be expensive
880 if ( strlen( $otext ) +
strlen( $ntext ) > 20000 ) {
881 $work = new PoolCounterWorkViaCallback( 'diff',
882 md5( $otext ) . md5( $ntext ),
883 [ 'doWork' => $diff, 'error' => $error ]
885 return $work->execute();
892 * Generates diff, to be wrapped internally in a logging/instrumentation
894 * @param string $otext Old text, must be already segmented
895 * @param string $ntext New text, must be already segmented
896 * @return bool|string
898 protected function textDiff( $otext, $ntext ) {
899 global $wgExternalDiffEngine, $wgContLang;
901 $otext = str_replace( "\r\n", "\n", $otext );
902 $ntext = str_replace( "\r\n", "\n", $ntext );
904 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
905 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
906 $wgExternalDiffEngine = false;
907 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
908 // Same as above, but with no deprecation warnings
909 $wgExternalDiffEngine = false;
910 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
911 // And prevent people from shooting themselves in the foot...
912 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
913 $wgExternalDiffEngine = false;
916 // Better external diff engine, the 2 may some day be dropped
917 // This one does the escaping and segmenting itself
918 if ( function_exists( 'wikidiff2_do_diff' ) && $wgExternalDiffEngine === false ) {
919 $wikidiff2Version = phpversion( 'wikidiff2' );
921 $wikidiff2Version !== false &&
922 version_compare( $wikidiff2Version, '0.3', '>=' )
924 $text = wikidiff2_do_diff(
928 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
931 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
932 $text = wikidiff2_do_diff(
938 // Log a warning in case the configuration value is set to not silently ignore it
939 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
940 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
941 effect since the used version of WikiDiff2 does not support it.' );
945 $text .= $this->debug( 'wikidiff2' );
948 } elseif ( $wgExternalDiffEngine !== false && is_executable( $wgExternalDiffEngine ) ) {
950 $tmpDir = wfTempDir();
951 $tempName1 = tempnam( $tmpDir, 'diff_' );
952 $tempName2 = tempnam( $tmpDir, 'diff_' );
954 $tempFile1 = fopen( $tempName1, "w" );
958 $tempFile2 = fopen( $tempName2, "w" );
962 fwrite( $tempFile1, $otext );
963 fwrite( $tempFile2, $ntext );
964 fclose( $tempFile1 );
965 fclose( $tempFile2 );
966 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
967 $difftext = wfShellExec( $cmd );
968 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
969 unlink( $tempName1 );
970 unlink( $tempName2 );
976 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
977 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
978 $diffs = new Diff( $ota, $nta );
979 $formatter = new TableDiffFormatter();
980 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
986 * Generate a debug comment indicating diff generating time,
987 * server node, and generator backend.
989 * @param string $generator : What diff engine was used
993 protected function debug( $generator = "internal" ) {
994 global $wgShowHostnames;
995 if ( !$this->enableDebugComment
) {
998 $data = [ $generator ];
999 if ( $wgShowHostnames ) {
1000 $data[] = wfHostname();
1002 $data[] = wfTimestamp( TS_DB
);
1004 return "<!-- diff generator: " .
1005 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1010 * Replace line numbers with the text in the user's language
1012 * @param string $text
1016 public function localiseLineNumbers( $text ) {
1017 return preg_replace_callback(
1018 '/<!--LINE (\d+)-->/',
1019 [ $this, 'localiseLineNumbersCb' ],
1024 public function localiseLineNumbersCb( $matches ) {
1025 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1029 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1033 * If there are revisions between the ones being compared, return a note saying so.
1037 public function getMultiNotice() {
1038 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
1040 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
1041 // Comparing two different pages? Count would be meaningless.
1045 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1046 $oldRev = $this->mNewRev
; // flip
1047 $newRev = $this->mOldRev
; // flip
1048 } else { // normal case
1049 $oldRev = $this->mOldRev
;
1050 $newRev = $this->mNewRev
;
1053 // Sanity: don't show the notice if too many rows must be scanned
1054 // @todo show some special message for that case
1055 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1056 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1057 $limit = 100; // use diff-multi-manyusers if too many users
1058 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1059 $numUsers = count( $users );
1061 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1062 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1065 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1068 return ''; // nothing
1072 * Get a notice about how many intermediate edits and users there are
1074 * @param int $numEdits
1075 * @param int $numUsers
1080 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1081 if ( $numUsers === 0 ) {
1082 $msg = 'diff-multi-sameuser';
1083 } elseif ( $numUsers > $limit ) {
1084 $msg = 'diff-multi-manyusers';
1087 $msg = 'diff-multi-otherusers';
1090 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1094 * Get a header for a specified revision.
1096 * @param Revision $rev
1097 * @param string $complete 'complete' to get the header wrapped depending
1098 * the visibility of the revision and a link to edit the page.
1100 * @return string HTML fragment
1102 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1103 $lang = $this->getLanguage();
1104 $user = $this->getUser();
1105 $revtimestamp = $rev->getTimestamp();
1106 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1107 $dateofrev = $lang->userDate( $revtimestamp, $user );
1108 $timeofrev = $lang->userTime( $revtimestamp, $user );
1110 $header = $this->msg(
1111 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1117 if ( $complete !== 'complete' ) {
1121 $title = $rev->getTitle();
1123 $header = Linker
::linkKnown( $title, $header, [],
1124 [ 'oldid' => $rev->getId() ] );
1126 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1127 $editQuery = [ 'action' => 'edit' ];
1128 if ( !$rev->isCurrent() ) {
1129 $editQuery['oldid'] = $rev->getId();
1132 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1133 $msg = $this->msg( $key )->escaped();
1134 $editLink = $this->msg( 'parentheses' )->rawParams(
1135 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1136 $header .= ' ' . Html
::rawElement(
1138 [ 'class' => 'mw-diff-edit' ],
1141 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1142 $header = Html
::rawElement(
1144 [ 'class' => 'history-deleted' ],
1149 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1156 * Add the header to a diff body
1158 * @param string $diff Diff body
1159 * @param string $otitle Old revision header
1160 * @param string $ntitle New revision header
1161 * @param string $multi Notice telling user that there are intermediate
1162 * revisions between the ones being compared
1163 * @param string $notice Other notices, e.g. that user is viewing deleted content
1167 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1168 // shared.css sets diff in interface language/dir, but the actual content
1169 // is often in a different language, mostly the page content language/dir
1170 $header = Html
::openElement( 'table', [
1171 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1172 'data-mw' => 'interface',
1174 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1176 if ( !$diff && !$otitle ) {
1178 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1179 <td class=\"diff-ntitle\">{$ntitle}</td>
1183 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1185 <col class=\"diff-marker\" />
1186 <col class=\"diff-content\" />
1187 <col class=\"diff-marker\" />
1188 <col class=\"diff-content\" />";
1195 if ( $otitle ||
$ntitle ) {
1197 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1198 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1199 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1204 if ( $multi != '' ) {
1205 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1206 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1208 if ( $notice != '' ) {
1209 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1210 "lang=\"{$userLang}\">{$notice}</td></tr>";
1213 return $header . $diff . "</table>";
1217 * Use specified text instead of loading from the database
1218 * @param Content $oldContent
1219 * @param Content $newContent
1222 public function setContent( Content
$oldContent, Content
$newContent ) {
1223 $this->mOldContent
= $oldContent;
1224 $this->mNewContent
= $newContent;
1226 $this->mTextLoaded
= 2;
1227 $this->mRevisionsLoaded
= true;
1231 * Set the language in which the diff text is written
1232 * (Defaults to page content language).
1233 * @param Language|string $lang
1236 public function setTextLanguage( $lang ) {
1237 $this->mDiffLang
= wfGetLangObj( $lang );
1241 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1242 * to a pair of actual integers representing revision ids.
1244 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1245 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1247 * @return int[] List of two revision ids, older first, later second.
1248 * Zero signifies invalid argument passed.
1249 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1251 public function mapDiffPrevNext( $old, $new ) {
1252 if ( $new === 'prev' ) {
1253 // Show diff between revision $old and the previous one. Get previous one from DB.
1254 $newid = intval( $old );
1255 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1256 } elseif ( $new === 'next' ) {
1257 // Show diff between revision $old and the next one. Get next one from DB.
1258 $oldid = intval( $old );
1259 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1261 $oldid = intval( $old );
1262 $newid = intval( $new );
1265 return [ $oldid, $newid ];
1271 private function loadRevisionIds() {
1272 if ( $this->mRevisionsIdsLoaded
) {
1276 $this->mRevisionsIdsLoaded
= true;
1278 $old = $this->mOldid
;
1279 $new = $this->mNewid
;
1281 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1282 if ( $new === 'next' && $this->mNewid
=== false ) {
1283 # if no result, NewId points to the newest old revision. The only newer
1284 # revision is cur, which is "0".
1289 'NewDifferenceEngine',
1290 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1295 * Load revision metadata for the specified articles. If newid is 0, then compare
1296 * the old article in oldid to the current article; if oldid is 0, then
1297 * compare the current article to the immediately previous one (ignoring the
1300 * If oldid is false, leave the corresponding revision object set
1301 * to false. This is impossible via ordinary user input, and is provided for
1306 public function loadRevisionData() {
1307 if ( $this->mRevisionsLoaded
) {
1311 // Whether it succeeds or fails, we don't want to try again
1312 $this->mRevisionsLoaded
= true;
1314 $this->loadRevisionIds();
1316 // Load the new revision object
1317 if ( $this->mNewid
) {
1318 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1320 $this->mNewRev
= Revision
::newFromTitle(
1323 Revision
::READ_NORMAL
1327 if ( !$this->mNewRev
instanceof Revision
) {
1331 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1332 $this->mNewid
= $this->mNewRev
->getId();
1333 $this->mNewPage
= $this->mNewRev
->getTitle();
1335 // Load the old revision object
1336 $this->mOldRev
= false;
1337 if ( $this->mOldid
) {
1338 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1339 } elseif ( $this->mOldid
=== 0 ) {
1340 $rev = $this->mNewRev
->getPrevious();
1342 $this->mOldid
= $rev->getId();
1343 $this->mOldRev
= $rev;
1345 // No previous revision; mark to show as first-version only.
1346 $this->mOldid
= false;
1347 $this->mOldRev
= false;
1349 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1351 if ( is_null( $this->mOldRev
) ) {
1355 if ( $this->mOldRev
) {
1356 $this->mOldPage
= $this->mOldRev
->getTitle();
1359 // Load tags information for both revisions
1360 $dbr = wfGetDB( DB_REPLICA
);
1361 if ( $this->mOldid
!== false ) {
1362 $this->mOldTags
= $dbr->selectField(
1365 [ 'ts_rev_id' => $this->mOldid
],
1369 $this->mOldTags
= false;
1371 $this->mNewTags
= $dbr->selectField(
1374 [ 'ts_rev_id' => $this->mNewid
],
1382 * Load the text of the revisions, as well as revision data.
1386 public function loadText() {
1387 if ( $this->mTextLoaded
== 2 ) {
1391 // Whether it succeeds or fails, we don't want to try again
1392 $this->mTextLoaded
= 2;
1394 if ( !$this->loadRevisionData() ) {
1398 if ( $this->mOldRev
) {
1399 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1400 if ( $this->mOldContent
=== null ) {
1405 if ( $this->mNewRev
) {
1406 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1407 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1408 if ( $this->mNewContent
=== null ) {
1417 * Load the text of the new revision, not the old one
1421 public function loadNewText() {
1422 if ( $this->mTextLoaded
>= 1 ) {
1426 $this->mTextLoaded
= 1;
1428 if ( !$this->loadRevisionData() ) {
1432 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1434 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );