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
;
24 use MediaWiki\Shell\Shell
;
26 /** @deprecated use class constant instead */
27 define( 'MW_DIFF_VERSION', '1.11a' );
31 * @ingroup DifferenceEngine
33 class DifferenceEngine
extends ContextSource
{
35 * Constant to indicate diff cache compatibility.
36 * Bump this when changing the diff formatting in a way that
37 * fixes important bugs or such to force cached diff views to
40 const DIFF_VERSION
= MW_DIFF_VERSION
;
72 /** @var bool Have the revisions IDs been loaded */
73 private $mRevisionsIdsLoaded = false;
75 /** @var bool Have the revisions been loaded */
76 public $mRevisionsLoaded = false;
78 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
79 public $mTextLoaded = 0;
81 /** @var bool Was the diff fetched from cache? */
82 public $mCacheHit = false;
85 * Set this to true to add debug info to the HTML output.
86 * Warning: this may cause RSS readers to spuriously mark articles as "new"
89 public $enableDebugComment = false;
91 /** @var bool If true, line X is not displayed when X is 1, for example
92 * to increase readability and conserve space with many small diffs.
94 protected $mReducedLineNumbers = false;
96 /** @var string Link to action=markpatrolled */
97 protected $mMarkPatrolledLink = null;
99 /** @var bool Show rev_deleted content if allowed */
100 protected $unhide = false;
102 /** @var bool Refresh the diff cache */
103 protected $mRefreshCache = false;
108 * @param IContextSource $context Context to use, anything else will be ignored
109 * @param int $old Old ID we want to show and diff with.
110 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
111 * @param int $rcid Deprecated, no longer used!
112 * @param bool $refreshCache If set, refreshes the diff cache
113 * @param bool $unhide If set, allow viewing deleted revs
115 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
116 $refreshCache = false, $unhide = false
118 if ( $context instanceof IContextSource
) {
119 $this->setContext( $context );
122 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
124 $this->mOldid
= $old;
125 $this->mNewid
= $new;
126 $this->mRefreshCache
= $refreshCache;
127 $this->unhide
= $unhide;
133 public function setReducedLineNumbers( $value = true ) {
134 $this->mReducedLineNumbers
= $value;
140 public function getDiffLang() {
141 if ( $this->mDiffLang
=== null ) {
142 # Default language in which the diff text is written.
143 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
146 return $this->mDiffLang
;
152 public function wasCacheHit() {
153 return $this->mCacheHit
;
159 public function getOldid() {
160 $this->loadRevisionIds();
162 return $this->mOldid
;
168 public function getNewid() {
169 $this->loadRevisionIds();
171 return $this->mNewid
;
175 * Look up a special:Undelete link to the given deleted revision id,
176 * as a workaround for being unable to load deleted diffs in currently.
178 * @param int $id Revision ID
180 * @return string|bool Link HTML or false
182 public function deletedLink( $id ) {
183 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
184 $dbr = wfGetDB( DB_REPLICA
);
185 $row = $dbr->selectRow( 'archive',
187 Revision
::selectArchiveFields(),
188 [ 'ar_namespace', 'ar_title' ]
190 [ 'ar_rev_id' => $id ],
193 $rev = Revision
::newFromArchiveRow( $row );
194 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
196 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
197 'target' => $title->getPrefixedText(),
198 'timestamp' => $rev->getTimestamp()
207 * Build a wikitext link toward a deleted revision, if viewable.
209 * @param int $id Revision ID
211 * @return string Wikitext fragment
213 public function deletedIdMarker( $id ) {
214 $link = $this->deletedLink( $id );
216 return "[$link $id]";
222 private function showMissingRevision() {
223 $out = $this->getOutput();
226 if ( $this->mOldRev
=== null ||
227 ( $this->mOldRev
&& $this->mOldContent
=== null )
229 $missing[] = $this->deletedIdMarker( $this->mOldid
);
231 if ( $this->mNewRev
=== null ||
232 ( $this->mNewRev
&& $this->mNewContent
=== null )
234 $missing[] = $this->deletedIdMarker( $this->mNewid
);
237 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
238 $msg = $this->msg( 'difference-missing-revision' )
239 ->params( $this->getLanguage()->listToText( $missing ) )
240 ->numParams( count( $missing ) )
242 $out->addHTML( $msg );
245 public function showDiffPage( $diffOnly = false ) {
246 # Allow frames except in certain special cases
247 $out = $this->getOutput();
248 $out->allowClickjacking();
249 $out->setRobotPolicy( 'noindex,nofollow' );
251 // Allow extensions to add any extra output here
252 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
254 if ( !$this->loadRevisionData() ) {
255 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
256 $this->showMissingRevision();
261 $user = $this->getUser();
262 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
263 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
264 $permErrors = wfMergeErrorArrays( $permErrors,
265 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
267 if ( count( $permErrors ) ) {
268 throw new PermissionsError( 'read', $permErrors );
274 # Carry over 'diffonly' param via navigation links
275 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
276 $query['diffonly'] = $diffOnly;
278 # Cascade unhide param in links for easy deletion browsing
279 if ( $this->unhide
) {
280 $query['unhide'] = 1;
283 # Check if one of the revisions is deleted/suppressed
284 $deleted = $suppressed = false;
285 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
289 # mOldRev is false if the difference engine is called with a "vague" query for
290 # a diff between a version V and its previous version V' AND the version V
291 # is the first version of that article. In that case, V' does not exist.
292 if ( $this->mOldRev
=== false ) {
293 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
296 // Allow extensions to change the $oldHeader variable
297 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
299 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
301 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
302 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
305 $out->setPageTitle( $this->msg( 'difference-title-multipage',
306 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
307 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
311 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
312 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
313 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
314 if ( $rollbackLink ) {
315 $out->preventClickjacking();
316 $rollback = '   ' . $rollbackLink;
320 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
321 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
323 $undoLink = Html
::element( 'a', [
324 'href' => $this->mNewPage
->getLocalURL( [
326 'undoafter' => $this->mOldid
,
327 'undo' => $this->mNewid
329 'title' => Linker
::titleAttrib( 'undo' ),
331 $this->msg( 'editundo' )->text()
333 $revisionTools['mw-diff-undo'] = $undoLink;
337 # Make "previous revision link"
338 if ( $samePage && $this->mOldRev
->getPrevious() ) {
339 $prevlink = Linker
::linkKnown(
341 $this->msg( 'previousdiff' )->escaped(),
342 [ 'id' => 'differences-prevlink' ],
343 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
346 $prevlink = ' ';
349 if ( $this->mOldRev
->isMinor() ) {
350 $oldminor = ChangesList
::flag( 'minor' );
355 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
356 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
357 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
359 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
360 '<div id="mw-diff-otitle2">' .
361 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
362 '<div id="mw-diff-otitle3">' . $oldminor .
363 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
364 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
365 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
367 // Allow extensions to change the $oldHeader variable
368 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
369 $diffOnly, $ldel, $this->unhide
] );
371 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
372 $deleted = true; // old revisions text is hidden
373 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
374 $suppressed = true; // also suppressed
378 # Check if this user can see the revisions
379 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
384 $out->addJsConfigVars( [
385 'wgDiffOldId' => $this->mOldid
,
386 'wgDiffNewId' => $this->mNewid
,
389 # Make "next revision link"
390 # Skip next link on the top revision
391 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
392 $nextlink = Linker
::linkKnown(
394 $this->msg( 'nextdiff' )->escaped(),
395 [ 'id' => 'differences-nextlink' ],
396 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
399 $nextlink = ' ';
402 if ( $this->mNewRev
->isMinor() ) {
403 $newminor = ChangesList
::flag( 'minor' );
408 # Handle RevisionDelete links...
409 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
411 # Allow extensions to define their own revision tools
412 Hooks
::run( 'DiffRevisionTools',
413 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
414 $formattedRevisionTools = [];
415 // Put each one in parentheses (poor man's button)
416 foreach ( $revisionTools as $key => $tool ) {
417 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
418 $element = Html
::rawElement(
420 [ 'class' => $toolClass ],
421 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
423 $formattedRevisionTools[] = $element;
425 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
426 ' ' . implode( ' ', $formattedRevisionTools );
427 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
429 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
430 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
432 '<div id="mw-diff-ntitle3">' . $newminor .
433 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
434 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
435 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
437 // Allow extensions to change the $newHeader variable
438 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
439 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
441 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
442 $deleted = true; // new revisions text is hidden
443 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
444 $suppressed = true; // also suppressed
448 # If the diff cannot be shown due to a deleted revision, then output
449 # the diff header and links to unhide (if available)...
450 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
451 $this->showDiffStyle();
452 $multi = $this->getMultiNotice();
453 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
455 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
456 # Give explanation for why revision is not visible
457 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
460 # Give explanation and add a link to view the diff...
461 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
462 $link = $this->getTitle()->getFullURL( $query );
463 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
465 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
469 # Otherwise, output a regular diff...
471 # Add deletion notice if the user is viewing deleted content
474 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
475 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
476 $this->msg( $msg )->parse() .
479 $this->showDiff( $oldHeader, $newHeader, $notice );
481 $this->renderNewRevision();
487 * Build a link to mark a change as patrolled.
489 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
490 * Side effect: When the patrol link is build, this method will call
491 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
493 * @return string HTML or empty string
495 public function markPatrolledLink() {
496 if ( $this->mMarkPatrolledLink
=== null ) {
497 $linkInfo = $this->getMarkPatrolledLinkInfo();
498 // If false, there is no patrol link needed/allowed
500 $this->mMarkPatrolledLink
= '';
502 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
505 $this->msg( 'markaspatrolleddiff' )->escaped(),
508 'action' => 'markpatrolled',
509 'rcid' => $linkInfo['rcid'],
512 // Allow extensions to change the markpatrolled link
513 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
514 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
517 return $this->mMarkPatrolledLink
;
521 * Returns an array of meta data needed to build a "mark as patrolled" link and
522 * adds the mediawiki.page.patrol.ajax to the output.
524 * @return array|false An array of meta data for a patrol link (rcid only)
525 * or false if no link is needed
527 protected function getMarkPatrolledLinkInfo() {
528 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
530 $user = $this->getUser();
532 // Prepare a change patrol link, if applicable
534 // Is patrolling enabled and the user allowed to?
535 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
536 // Only do this if the revision isn't more than 6 hours older
537 // than the Max RC age (6h because the RC might not be cleaned out regularly)
538 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
540 // Look for an unpatrolled change corresponding to this diff
541 $db = wfGetDB( DB_REPLICA
);
542 $change = RecentChange
::newFromConds(
544 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
545 'rc_this_oldid' => $this->mNewid
,
551 if ( $change && !$change->getPerformer()->equals( $user ) ) {
552 $rcid = $change->getAttribute( 'rc_id' );
554 // None found or the page has been created by the current user.
555 // If the user could patrol this it already would be patrolled
559 // Allow extensions to possibly change the rcid here
560 // For example the rcid might be set to zero due to the user
561 // being the same as the performer of the change but an extension
562 // might still want to show it under certain conditions
563 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
567 $this->getOutput()->preventClickjacking();
568 if ( $wgEnableAPI && $wgEnableWriteAPI
569 && $user->isAllowed( 'writeapi' )
571 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
580 // No mark as patrolled link applicable
585 * @param Revision $rev
589 protected function revisionDeleteLink( $rev ) {
590 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
591 if ( $link !== '' ) {
592 $link = '   ' . $link . ' ';
599 * Show the new revision of the page.
601 public function renderNewRevision() {
602 $out = $this->getOutput();
603 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
604 # Add "current version as of X" title
605 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
606 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
607 # Page content may be handled by a hooked call instead...
608 # @codingStandardsIgnoreStart Ignoring long lines.
609 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
610 $this->loadNewText();
611 $out->setRevisionId( $this->mNewid
);
612 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
613 $out->setArticleFlag( true );
615 if ( !Hooks
::run( 'ArticleContentViewCustom', [ $this->mNewContent
, $this->mNewPage
, $out ] ) ) {
616 // Handled by extension
619 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
620 // If the Title stored in the context is the same as the one
621 // of the new revision, we can use its associated WikiPage
623 $wikiPage = $this->getWikiPage();
625 // Otherwise we need to create our own WikiPage object
626 $wikiPage = WikiPage
::factory( $this->mNewPage
);
629 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
631 # WikiPage::getParserOutput() should not return false, but just in case
632 if ( $parserOutput ) {
633 // Allow extensions to change parser output here
634 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput', [ $this, $out, $parserOutput, $wikiPage ] ) ) {
635 $out->addParserOutput( $parserOutput );
640 # @codingStandardsIgnoreEnd
642 // Allow extensions to optionally not show the final patrolled link
643 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
644 # Add redundant patrol link on bottom...
645 $out->addHTML( $this->markPatrolledLink() );
649 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
650 $parserOptions = $page->makeParserOptions( $this->getContext() );
652 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( 'edit', $this->getUser() ) ) {
653 $parserOptions->setEditSection( false );
656 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
658 return $parserOutput;
662 * Get the diff text, send it to the OutputPage object
663 * Returns false if the diff could not be generated, otherwise returns true
665 * @param string|bool $otitle Header for old text or false
666 * @param string|bool $ntitle Header for new text or false
667 * @param string $notice HTML between diff header and body
671 public function showDiff( $otitle, $ntitle, $notice = '' ) {
672 // Allow extensions to affect the output here
673 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
675 $diff = $this->getDiff( $otitle, $ntitle, $notice );
676 if ( $diff === false ) {
677 $this->showMissingRevision();
681 $this->showDiffStyle();
682 $this->getOutput()->addHTML( $diff );
689 * Add style sheets for diff display.
691 public function showDiffStyle() {
692 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
696 * Get complete diff table, including header
698 * @param string|bool $otitle Header for old text or false
699 * @param string|bool $ntitle Header for new text or false
700 * @param string $notice HTML between diff header and body
704 public function getDiff( $otitle, $ntitle, $notice = '' ) {
705 $body = $this->getDiffBody();
706 if ( $body === false ) {
710 $multi = $this->getMultiNotice();
711 // Display a message when the diff is empty
712 if ( $body === '' ) {
713 $notice .= '<div class="mw-diff-empty">' .
714 $this->msg( 'diff-empty' )->parse() .
718 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
722 * Get the diff table body, without header
724 * @return mixed (string/false)
726 public function getDiffBody() {
727 $this->mCacheHit
= true;
728 // Check if the diff should be hidden from this user
729 if ( !$this->loadRevisionData() ) {
731 } elseif ( $this->mOldRev
&&
732 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
735 } elseif ( $this->mNewRev
&&
736 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
741 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
742 && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
744 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
750 $cache = ObjectCache
::getMainWANInstance();
751 if ( $this->mOldid
&& $this->mNewid
) {
752 $key = $this->getDiffBodyCacheKey();
755 if ( !$this->mRefreshCache
) {
756 $difftext = $cache->get( $key );
758 wfIncrStats( 'diff_cache.hit' );
759 $difftext = $this->localiseLineNumbers( $difftext );
760 $difftext .= "\n<!-- diff cache key $key -->\n";
764 } // don't try to load but save the result
766 $this->mCacheHit
= false;
768 // Loadtext is permission safe, this just clears out the diff
769 if ( !$this->loadText() ) {
773 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
775 // Avoid PHP 7.1 warning from passing $this by reference
778 // Save to cache for 7 days
779 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
780 wfIncrStats( 'diff_cache.uncacheable' );
781 } elseif ( $key !== false && $difftext !== false ) {
782 wfIncrStats( 'diff_cache.miss' );
783 $cache->set( $key, $difftext, 7 * 86400 );
785 wfIncrStats( 'diff_cache.uncacheable' );
787 // Replace line numbers with the text in the user's language
788 if ( $difftext !== false ) {
789 $difftext = $this->localiseLineNumbers( $difftext );
796 * Returns the cache key for diff body text or content.
800 * @throws MWException
803 protected function getDiffBodyCacheKey() {
804 if ( !$this->mOldid ||
!$this->mNewid
) {
805 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
808 return wfMemcKey( 'diff', 'version', self
::DIFF_VERSION
,
809 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
813 * Generate a diff, no caching.
815 * This implementation uses generateTextDiffBody() to generate a diff based on the default
816 * serialization of the given Content objects. This will fail if $old or $new are not
817 * instances of TextContent.
819 * Subclasses may override this to provide a different rendering for the diff,
820 * perhaps taking advantage of the content's native form. This is required for all content
821 * models that are not text based.
825 * @param Content $old Old content
826 * @param Content $new New content
828 * @throws MWException If old or new content is not an instance of TextContent.
829 * @return bool|string
831 public function generateContentDiffBody( Content
$old, Content
$new ) {
832 if ( !( $old instanceof TextContent
) ) {
833 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
834 "override generateContentDiffBody to fix this." );
837 if ( !( $new instanceof TextContent
) ) {
838 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
839 . "override generateContentDiffBody to fix this." );
842 $otext = $old->serialize();
843 $ntext = $new->serialize();
845 return $this->generateTextDiffBody( $otext, $ntext );
849 * Generate a diff, no caching
851 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
853 * @param string $otext Old text, must be already segmented
854 * @param string $ntext New text, must be already segmented
856 * @return bool|string
858 public function generateTextDiffBody( $otext, $ntext ) {
859 $diff = function () use ( $otext, $ntext ) {
860 $time = microtime( true );
862 $result = $this->textDiff( $otext, $ntext );
864 $time = intval( ( microtime( true ) - $time ) * 1000 );
865 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
866 // Log requests slower than 99th percentile
867 if ( $time > 100 && $this->mOldPage
&& $this->mNewPage
) {
869 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
876 * @param Status $status
879 $error = function ( $status ) {
880 throw new FatalError( $status->getWikiText() );
883 // Use PoolCounter if the diff looks like it can be expensive
884 if ( strlen( $otext ) +
strlen( $ntext ) > 20000 ) {
885 $work = new PoolCounterWorkViaCallback( 'diff',
886 md5( $otext ) . md5( $ntext ),
887 [ 'doWork' => $diff, 'error' => $error ]
889 return $work->execute();
896 * Generates diff, to be wrapped internally in a logging/instrumentation
898 * @param string $otext Old text, must be already segmented
899 * @param string $ntext New text, must be already segmented
900 * @return bool|string
902 protected function textDiff( $otext, $ntext ) {
903 global $wgExternalDiffEngine, $wgContLang;
905 $otext = str_replace( "\r\n", "\n", $otext );
906 $ntext = str_replace( "\r\n", "\n", $ntext );
908 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
909 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
910 $wgExternalDiffEngine = false;
911 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
912 // Same as above, but with no deprecation warnings
913 $wgExternalDiffEngine = false;
914 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
915 // And prevent people from shooting themselves in the foot...
916 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
917 $wgExternalDiffEngine = false;
920 // Better external diff engine, the 2 may some day be dropped
921 // This one does the escaping and segmenting itself
922 if ( function_exists( 'wikidiff2_do_diff' ) && $wgExternalDiffEngine === false ) {
923 $wikidiff2Version = phpversion( 'wikidiff2' );
925 $wikidiff2Version !== false &&
926 version_compare( $wikidiff2Version, '0.3', '>=' )
928 $text = wikidiff2_do_diff(
932 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
935 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
936 $text = wikidiff2_do_diff(
942 // Log a warning in case the configuration value is set to not silently ignore it
943 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
944 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
945 effect since the used version of WikiDiff2 does not support it.' );
949 $text .= $this->debug( 'wikidiff2' );
952 } elseif ( $wgExternalDiffEngine !== false && is_executable( $wgExternalDiffEngine ) ) {
954 $tmpDir = wfTempDir();
955 $tempName1 = tempnam( $tmpDir, 'diff_' );
956 $tempName2 = tempnam( $tmpDir, 'diff_' );
958 $tempFile1 = fopen( $tempName1, "w" );
962 $tempFile2 = fopen( $tempName2, "w" );
966 fwrite( $tempFile1, $otext );
967 fwrite( $tempFile2, $ntext );
968 fclose( $tempFile1 );
969 fclose( $tempFile2 );
970 $cmd = [ $wgExternalDiffEngine, $tempName1, $tempName2 ];
971 $result = Shell
::command( $cmd )
973 $exitCode = $result->getExitCode();
974 if ( $exitCode !== 0 ) {
975 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
976 . wfEscapeWikiText( $result->getStderr() )
979 $difftext = $result->getStdout();
980 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
981 unlink( $tempName1 );
982 unlink( $tempName2 );
988 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
989 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
990 $diffs = new Diff( $ota, $nta );
991 $formatter = new TableDiffFormatter();
992 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
998 * Generate a debug comment indicating diff generating time,
999 * server node, and generator backend.
1001 * @param string $generator : What diff engine was used
1005 protected function debug( $generator = "internal" ) {
1006 global $wgShowHostnames;
1007 if ( !$this->enableDebugComment
) {
1010 $data = [ $generator ];
1011 if ( $wgShowHostnames ) {
1012 $data[] = wfHostname();
1014 $data[] = wfTimestamp( TS_DB
);
1016 return "<!-- diff generator: " .
1017 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1022 * Replace line numbers with the text in the user's language
1024 * @param string $text
1028 public function localiseLineNumbers( $text ) {
1029 return preg_replace_callback(
1030 '/<!--LINE (\d+)-->/',
1031 [ $this, 'localiseLineNumbersCb' ],
1036 public function localiseLineNumbersCb( $matches ) {
1037 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1041 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1045 * If there are revisions between the ones being compared, return a note saying so.
1049 public function getMultiNotice() {
1050 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
1052 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
1053 // Comparing two different pages? Count would be meaningless.
1057 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1058 $oldRev = $this->mNewRev
; // flip
1059 $newRev = $this->mOldRev
; // flip
1060 } else { // normal case
1061 $oldRev = $this->mOldRev
;
1062 $newRev = $this->mNewRev
;
1065 // Sanity: don't show the notice if too many rows must be scanned
1066 // @todo show some special message for that case
1067 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1068 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1069 $limit = 100; // use diff-multi-manyusers if too many users
1070 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1071 $numUsers = count( $users );
1073 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1074 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1077 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1080 return ''; // nothing
1084 * Get a notice about how many intermediate edits and users there are
1086 * @param int $numEdits
1087 * @param int $numUsers
1092 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1093 if ( $numUsers === 0 ) {
1094 $msg = 'diff-multi-sameuser';
1095 } elseif ( $numUsers > $limit ) {
1096 $msg = 'diff-multi-manyusers';
1099 $msg = 'diff-multi-otherusers';
1102 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1106 * Get a header for a specified revision.
1108 * @param Revision $rev
1109 * @param string $complete 'complete' to get the header wrapped depending
1110 * the visibility of the revision and a link to edit the page.
1112 * @return string HTML fragment
1114 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1115 $lang = $this->getLanguage();
1116 $user = $this->getUser();
1117 $revtimestamp = $rev->getTimestamp();
1118 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1119 $dateofrev = $lang->userDate( $revtimestamp, $user );
1120 $timeofrev = $lang->userTime( $revtimestamp, $user );
1122 $header = $this->msg(
1123 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1129 if ( $complete !== 'complete' ) {
1133 $title = $rev->getTitle();
1135 $header = Linker
::linkKnown( $title, $header, [],
1136 [ 'oldid' => $rev->getId() ] );
1138 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1139 $editQuery = [ 'action' => 'edit' ];
1140 if ( !$rev->isCurrent() ) {
1141 $editQuery['oldid'] = $rev->getId();
1144 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1145 $msg = $this->msg( $key )->escaped();
1146 $editLink = $this->msg( 'parentheses' )->rawParams(
1147 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1148 $header .= ' ' . Html
::rawElement(
1150 [ 'class' => 'mw-diff-edit' ],
1153 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1154 $header = Html
::rawElement(
1156 [ 'class' => 'history-deleted' ],
1161 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1168 * Add the header to a diff body
1170 * @param string $diff Diff body
1171 * @param string $otitle Old revision header
1172 * @param string $ntitle New revision header
1173 * @param string $multi Notice telling user that there are intermediate
1174 * revisions between the ones being compared
1175 * @param string $notice Other notices, e.g. that user is viewing deleted content
1179 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1180 // shared.css sets diff in interface language/dir, but the actual content
1181 // is often in a different language, mostly the page content language/dir
1182 $header = Html
::openElement( 'table', [
1183 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1184 'data-mw' => 'interface',
1186 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1188 if ( !$diff && !$otitle ) {
1190 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1191 <td class=\"diff-ntitle\">{$ntitle}</td>
1195 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1197 <col class=\"diff-marker\" />
1198 <col class=\"diff-content\" />
1199 <col class=\"diff-marker\" />
1200 <col class=\"diff-content\" />";
1207 if ( $otitle ||
$ntitle ) {
1209 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1210 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1211 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1216 if ( $multi != '' ) {
1217 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1218 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1220 if ( $notice != '' ) {
1221 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1222 "lang=\"{$userLang}\">{$notice}</td></tr>";
1225 return $header . $diff . "</table>";
1229 * Use specified text instead of loading from the database
1230 * @param Content $oldContent
1231 * @param Content $newContent
1234 public function setContent( Content
$oldContent, Content
$newContent ) {
1235 $this->mOldContent
= $oldContent;
1236 $this->mNewContent
= $newContent;
1238 $this->mTextLoaded
= 2;
1239 $this->mRevisionsLoaded
= true;
1243 * Set the language in which the diff text is written
1244 * (Defaults to page content language).
1245 * @param Language|string $lang
1248 public function setTextLanguage( $lang ) {
1249 $this->mDiffLang
= wfGetLangObj( $lang );
1253 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1254 * to a pair of actual integers representing revision ids.
1256 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1257 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1259 * @return int[] List of two revision ids, older first, later second.
1260 * Zero signifies invalid argument passed.
1261 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1263 public function mapDiffPrevNext( $old, $new ) {
1264 if ( $new === 'prev' ) {
1265 // Show diff between revision $old and the previous one. Get previous one from DB.
1266 $newid = intval( $old );
1267 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1268 } elseif ( $new === 'next' ) {
1269 // Show diff between revision $old and the next one. Get next one from DB.
1270 $oldid = intval( $old );
1271 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1273 $oldid = intval( $old );
1274 $newid = intval( $new );
1277 return [ $oldid, $newid ];
1283 private function loadRevisionIds() {
1284 if ( $this->mRevisionsIdsLoaded
) {
1288 $this->mRevisionsIdsLoaded
= true;
1290 $old = $this->mOldid
;
1291 $new = $this->mNewid
;
1293 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1294 if ( $new === 'next' && $this->mNewid
=== false ) {
1295 # if no result, NewId points to the newest old revision. The only newer
1296 # revision is cur, which is "0".
1301 'NewDifferenceEngine',
1302 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1307 * Load revision metadata for the specified articles. If newid is 0, then compare
1308 * the old article in oldid to the current article; if oldid is 0, then
1309 * compare the current article to the immediately previous one (ignoring the
1312 * If oldid is false, leave the corresponding revision object set
1313 * to false. This is impossible via ordinary user input, and is provided for
1318 public function loadRevisionData() {
1319 if ( $this->mRevisionsLoaded
) {
1323 // Whether it succeeds or fails, we don't want to try again
1324 $this->mRevisionsLoaded
= true;
1326 $this->loadRevisionIds();
1328 // Load the new revision object
1329 if ( $this->mNewid
) {
1330 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1332 $this->mNewRev
= Revision
::newFromTitle(
1335 Revision
::READ_NORMAL
1339 if ( !$this->mNewRev
instanceof Revision
) {
1343 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1344 $this->mNewid
= $this->mNewRev
->getId();
1345 $this->mNewPage
= $this->mNewRev
->getTitle();
1347 // Load the old revision object
1348 $this->mOldRev
= false;
1349 if ( $this->mOldid
) {
1350 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1351 } elseif ( $this->mOldid
=== 0 ) {
1352 $rev = $this->mNewRev
->getPrevious();
1354 $this->mOldid
= $rev->getId();
1355 $this->mOldRev
= $rev;
1357 // No previous revision; mark to show as first-version only.
1358 $this->mOldid
= false;
1359 $this->mOldRev
= false;
1361 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1363 if ( is_null( $this->mOldRev
) ) {
1367 if ( $this->mOldRev
) {
1368 $this->mOldPage
= $this->mOldRev
->getTitle();
1371 // Load tags information for both revisions
1372 $dbr = wfGetDB( DB_REPLICA
);
1373 if ( $this->mOldid
!== false ) {
1374 $this->mOldTags
= $dbr->selectField(
1377 [ 'ts_rev_id' => $this->mOldid
],
1381 $this->mOldTags
= false;
1383 $this->mNewTags
= $dbr->selectField(
1386 [ 'ts_rev_id' => $this->mNewid
],
1394 * Load the text of the revisions, as well as revision data.
1398 public function loadText() {
1399 if ( $this->mTextLoaded
== 2 ) {
1403 // Whether it succeeds or fails, we don't want to try again
1404 $this->mTextLoaded
= 2;
1406 if ( !$this->loadRevisionData() ) {
1410 if ( $this->mOldRev
) {
1411 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1412 if ( $this->mOldContent
=== null ) {
1417 if ( $this->mNewRev
) {
1418 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1419 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1420 if ( $this->mNewContent
=== null ) {
1429 * Load the text of the new revision, not the old one
1433 public function loadNewText() {
1434 if ( $this->mTextLoaded
>= 1 ) {
1438 $this->mTextLoaded
= 1;
1440 if ( !$this->loadRevisionData() ) {
1444 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1446 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );