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 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
609 $this->loadNewText();
610 $out->setRevisionId( $this->mNewid
);
611 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
612 $out->setArticleFlag( true );
614 if ( !Hooks
::run( 'ArticleContentViewCustom',
615 [ $this->mNewContent
, $this->mNewPage
, $out ] )
617 // Handled by extension
620 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
621 // If the Title stored in the context is the same as the one
622 // of the new revision, we can use its associated WikiPage
624 $wikiPage = $this->getWikiPage();
626 // Otherwise we need to create our own WikiPage object
627 $wikiPage = WikiPage
::factory( $this->mNewPage
);
630 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
632 # WikiPage::getParserOutput() should not return false, but just in case
633 if ( $parserOutput ) {
634 // Allow extensions to change parser output here
635 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
636 [ $this, $out, $parserOutput, $wikiPage ] )
638 $out->addParserOutput( $parserOutput );
644 // Allow extensions to optionally not show the final patrolled link
645 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
646 # Add redundant patrol link on bottom...
647 $out->addHTML( $this->markPatrolledLink() );
651 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
652 $parserOptions = $page->makeParserOptions( $this->getContext() );
654 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( 'edit', $this->getUser() ) ) {
655 $parserOptions->setEditSection( false );
658 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
660 return $parserOutput;
664 * Get the diff text, send it to the OutputPage object
665 * Returns false if the diff could not be generated, otherwise returns true
667 * @param string|bool $otitle Header for old text or false
668 * @param string|bool $ntitle Header for new text or false
669 * @param string $notice HTML between diff header and body
673 public function showDiff( $otitle, $ntitle, $notice = '' ) {
674 // Allow extensions to affect the output here
675 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
677 $diff = $this->getDiff( $otitle, $ntitle, $notice );
678 if ( $diff === false ) {
679 $this->showMissingRevision();
683 $this->showDiffStyle();
684 $this->getOutput()->addHTML( $diff );
691 * Add style sheets for diff display.
693 public function showDiffStyle() {
694 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
698 * Get complete diff table, including header
700 * @param string|bool $otitle Header for old text or false
701 * @param string|bool $ntitle Header for new text or false
702 * @param string $notice HTML between diff header and body
706 public function getDiff( $otitle, $ntitle, $notice = '' ) {
707 $body = $this->getDiffBody();
708 if ( $body === false ) {
712 $multi = $this->getMultiNotice();
713 // Display a message when the diff is empty
714 if ( $body === '' ) {
715 $notice .= '<div class="mw-diff-empty">' .
716 $this->msg( 'diff-empty' )->parse() .
720 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
724 * Get the diff table body, without header
726 * @return mixed (string/false)
728 public function getDiffBody() {
729 $this->mCacheHit
= true;
730 // Check if the diff should be hidden from this user
731 if ( !$this->loadRevisionData() ) {
733 } elseif ( $this->mOldRev
&&
734 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
737 } elseif ( $this->mNewRev
&&
738 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
743 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
744 && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
746 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
752 $cache = ObjectCache
::getMainWANInstance();
753 if ( $this->mOldid
&& $this->mNewid
) {
754 $key = $this->getDiffBodyCacheKey();
757 if ( !$this->mRefreshCache
) {
758 $difftext = $cache->get( $key );
760 wfIncrStats( 'diff_cache.hit' );
761 $difftext = $this->localiseLineNumbers( $difftext );
762 $difftext .= "\n<!-- diff cache key $key -->\n";
766 } // don't try to load but save the result
768 $this->mCacheHit
= false;
770 // Loadtext is permission safe, this just clears out the diff
771 if ( !$this->loadText() ) {
775 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
777 // Avoid PHP 7.1 warning from passing $this by reference
780 // Save to cache for 7 days
781 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
782 wfIncrStats( 'diff_cache.uncacheable' );
783 } elseif ( $key !== false && $difftext !== false ) {
784 wfIncrStats( 'diff_cache.miss' );
785 $cache->set( $key, $difftext, 7 * 86400 );
787 wfIncrStats( 'diff_cache.uncacheable' );
789 // Replace line numbers with the text in the user's language
790 if ( $difftext !== false ) {
791 $difftext = $this->localiseLineNumbers( $difftext );
798 * Returns the cache key for diff body text or content.
802 * @throws MWException
805 protected function getDiffBodyCacheKey() {
806 if ( !$this->mOldid ||
!$this->mNewid
) {
807 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
810 return wfMemcKey( 'diff', 'version', self
::DIFF_VERSION
,
811 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
815 * Generate a diff, no caching.
817 * This implementation uses generateTextDiffBody() to generate a diff based on the default
818 * serialization of the given Content objects. This will fail if $old or $new are not
819 * instances of TextContent.
821 * Subclasses may override this to provide a different rendering for the diff,
822 * perhaps taking advantage of the content's native form. This is required for all content
823 * models that are not text based.
827 * @param Content $old Old content
828 * @param Content $new New content
830 * @throws MWException If old or new content is not an instance of TextContent.
831 * @return bool|string
833 public function generateContentDiffBody( Content
$old, Content
$new ) {
834 if ( !( $old instanceof TextContent
) ) {
835 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
836 "override generateContentDiffBody to fix this." );
839 if ( !( $new instanceof TextContent
) ) {
840 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
841 . "override generateContentDiffBody to fix this." );
844 $otext = $old->serialize();
845 $ntext = $new->serialize();
847 return $this->generateTextDiffBody( $otext, $ntext );
851 * Generate a diff, no caching
853 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
855 * @param string $otext Old text, must be already segmented
856 * @param string $ntext New text, must be already segmented
858 * @return bool|string
860 public function generateTextDiffBody( $otext, $ntext ) {
861 $diff = function () use ( $otext, $ntext ) {
862 $time = microtime( true );
864 $result = $this->textDiff( $otext, $ntext );
866 $time = intval( ( microtime( true ) - $time ) * 1000 );
867 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
868 // Log requests slower than 99th percentile
869 if ( $time > 100 && $this->mOldPage
&& $this->mNewPage
) {
871 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
878 * @param Status $status
881 $error = function ( $status ) {
882 throw new FatalError( $status->getWikiText() );
885 // Use PoolCounter if the diff looks like it can be expensive
886 if ( strlen( $otext ) +
strlen( $ntext ) > 20000 ) {
887 $work = new PoolCounterWorkViaCallback( 'diff',
888 md5( $otext ) . md5( $ntext ),
889 [ 'doWork' => $diff, 'error' => $error ]
891 return $work->execute();
898 * Generates diff, to be wrapped internally in a logging/instrumentation
900 * @param string $otext Old text, must be already segmented
901 * @param string $ntext New text, must be already segmented
902 * @return bool|string
904 protected function textDiff( $otext, $ntext ) {
905 global $wgExternalDiffEngine, $wgContLang;
907 $otext = str_replace( "\r\n", "\n", $otext );
908 $ntext = str_replace( "\r\n", "\n", $ntext );
910 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
911 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
912 $wgExternalDiffEngine = false;
913 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
914 // Same as above, but with no deprecation warnings
915 $wgExternalDiffEngine = false;
916 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
917 // And prevent people from shooting themselves in the foot...
918 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
919 $wgExternalDiffEngine = false;
922 // Better external diff engine, the 2 may some day be dropped
923 // This one does the escaping and segmenting itself
924 if ( function_exists( 'wikidiff2_do_diff' ) && $wgExternalDiffEngine === false ) {
925 $wikidiff2Version = phpversion( 'wikidiff2' );
927 $wikidiff2Version !== false &&
928 version_compare( $wikidiff2Version, '0.3', '>=' )
930 $text = wikidiff2_do_diff(
934 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
937 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
938 $text = wikidiff2_do_diff(
944 // Log a warning in case the configuration value is set to not silently ignore it
945 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
946 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
947 effect since the used version of WikiDiff2 does not support it.' );
951 $text .= $this->debug( 'wikidiff2' );
954 } elseif ( $wgExternalDiffEngine !== false && is_executable( $wgExternalDiffEngine ) ) {
956 $tmpDir = wfTempDir();
957 $tempName1 = tempnam( $tmpDir, 'diff_' );
958 $tempName2 = tempnam( $tmpDir, 'diff_' );
960 $tempFile1 = fopen( $tempName1, "w" );
964 $tempFile2 = fopen( $tempName2, "w" );
968 fwrite( $tempFile1, $otext );
969 fwrite( $tempFile2, $ntext );
970 fclose( $tempFile1 );
971 fclose( $tempFile2 );
972 $cmd = [ $wgExternalDiffEngine, $tempName1, $tempName2 ];
973 $result = Shell
::command( $cmd )
975 $exitCode = $result->getExitCode();
976 if ( $exitCode !== 0 ) {
977 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
978 . wfEscapeWikiText( $result->getStderr() )
981 $difftext = $result->getStdout();
982 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
983 unlink( $tempName1 );
984 unlink( $tempName2 );
990 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
991 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
992 $diffs = new Diff( $ota, $nta );
993 $formatter = new TableDiffFormatter();
994 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
1000 * Generate a debug comment indicating diff generating time,
1001 * server node, and generator backend.
1003 * @param string $generator : What diff engine was used
1007 protected function debug( $generator = "internal" ) {
1008 global $wgShowHostnames;
1009 if ( !$this->enableDebugComment
) {
1012 $data = [ $generator ];
1013 if ( $wgShowHostnames ) {
1014 $data[] = wfHostname();
1016 $data[] = wfTimestamp( TS_DB
);
1018 return "<!-- diff generator: " .
1019 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1024 * Replace line numbers with the text in the user's language
1026 * @param string $text
1030 public function localiseLineNumbers( $text ) {
1031 return preg_replace_callback(
1032 '/<!--LINE (\d+)-->/',
1033 [ $this, 'localiseLineNumbersCb' ],
1038 public function localiseLineNumbersCb( $matches ) {
1039 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1043 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1047 * If there are revisions between the ones being compared, return a note saying so.
1051 public function getMultiNotice() {
1052 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
1054 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
1055 // Comparing two different pages? Count would be meaningless.
1059 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1060 $oldRev = $this->mNewRev
; // flip
1061 $newRev = $this->mOldRev
; // flip
1062 } else { // normal case
1063 $oldRev = $this->mOldRev
;
1064 $newRev = $this->mNewRev
;
1067 // Sanity: don't show the notice if too many rows must be scanned
1068 // @todo show some special message for that case
1069 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1070 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1071 $limit = 100; // use diff-multi-manyusers if too many users
1072 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1073 $numUsers = count( $users );
1075 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1076 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1079 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1082 return ''; // nothing
1086 * Get a notice about how many intermediate edits and users there are
1088 * @param int $numEdits
1089 * @param int $numUsers
1094 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1095 if ( $numUsers === 0 ) {
1096 $msg = 'diff-multi-sameuser';
1097 } elseif ( $numUsers > $limit ) {
1098 $msg = 'diff-multi-manyusers';
1101 $msg = 'diff-multi-otherusers';
1104 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1108 * Get a header for a specified revision.
1110 * @param Revision $rev
1111 * @param string $complete 'complete' to get the header wrapped depending
1112 * the visibility of the revision and a link to edit the page.
1114 * @return string HTML fragment
1116 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1117 $lang = $this->getLanguage();
1118 $user = $this->getUser();
1119 $revtimestamp = $rev->getTimestamp();
1120 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1121 $dateofrev = $lang->userDate( $revtimestamp, $user );
1122 $timeofrev = $lang->userTime( $revtimestamp, $user );
1124 $header = $this->msg(
1125 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1131 if ( $complete !== 'complete' ) {
1135 $title = $rev->getTitle();
1137 $header = Linker
::linkKnown( $title, $header, [],
1138 [ 'oldid' => $rev->getId() ] );
1140 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1141 $editQuery = [ 'action' => 'edit' ];
1142 if ( !$rev->isCurrent() ) {
1143 $editQuery['oldid'] = $rev->getId();
1146 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1147 $msg = $this->msg( $key )->escaped();
1148 $editLink = $this->msg( 'parentheses' )->rawParams(
1149 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1150 $header .= ' ' . Html
::rawElement(
1152 [ 'class' => 'mw-diff-edit' ],
1155 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1156 $header = Html
::rawElement(
1158 [ 'class' => 'history-deleted' ],
1163 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1170 * Add the header to a diff body
1172 * @param string $diff Diff body
1173 * @param string $otitle Old revision header
1174 * @param string $ntitle New revision header
1175 * @param string $multi Notice telling user that there are intermediate
1176 * revisions between the ones being compared
1177 * @param string $notice Other notices, e.g. that user is viewing deleted content
1181 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1182 // shared.css sets diff in interface language/dir, but the actual content
1183 // is often in a different language, mostly the page content language/dir
1184 $header = Html
::openElement( 'table', [
1185 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1186 'data-mw' => 'interface',
1188 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1190 if ( !$diff && !$otitle ) {
1192 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1193 <td class=\"diff-ntitle\">{$ntitle}</td>
1197 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1199 <col class=\"diff-marker\" />
1200 <col class=\"diff-content\" />
1201 <col class=\"diff-marker\" />
1202 <col class=\"diff-content\" />";
1209 if ( $otitle ||
$ntitle ) {
1211 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1212 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1213 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1218 if ( $multi != '' ) {
1219 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1220 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1222 if ( $notice != '' ) {
1223 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1224 "lang=\"{$userLang}\">{$notice}</td></tr>";
1227 return $header . $diff . "</table>";
1231 * Use specified text instead of loading from the database
1232 * @param Content $oldContent
1233 * @param Content $newContent
1236 public function setContent( Content
$oldContent, Content
$newContent ) {
1237 $this->mOldContent
= $oldContent;
1238 $this->mNewContent
= $newContent;
1240 $this->mTextLoaded
= 2;
1241 $this->mRevisionsLoaded
= true;
1245 * Set the language in which the diff text is written
1246 * (Defaults to page content language).
1247 * @param Language|string $lang
1250 public function setTextLanguage( $lang ) {
1251 $this->mDiffLang
= wfGetLangObj( $lang );
1255 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1256 * to a pair of actual integers representing revision ids.
1258 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1259 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1261 * @return int[] List of two revision ids, older first, later second.
1262 * Zero signifies invalid argument passed.
1263 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1265 public function mapDiffPrevNext( $old, $new ) {
1266 if ( $new === 'prev' ) {
1267 // Show diff between revision $old and the previous one. Get previous one from DB.
1268 $newid = intval( $old );
1269 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1270 } elseif ( $new === 'next' ) {
1271 // Show diff between revision $old and the next one. Get next one from DB.
1272 $oldid = intval( $old );
1273 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1275 $oldid = intval( $old );
1276 $newid = intval( $new );
1279 return [ $oldid, $newid ];
1285 private function loadRevisionIds() {
1286 if ( $this->mRevisionsIdsLoaded
) {
1290 $this->mRevisionsIdsLoaded
= true;
1292 $old = $this->mOldid
;
1293 $new = $this->mNewid
;
1295 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1296 if ( $new === 'next' && $this->mNewid
=== false ) {
1297 # if no result, NewId points to the newest old revision. The only newer
1298 # revision is cur, which is "0".
1303 'NewDifferenceEngine',
1304 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1309 * Load revision metadata for the specified articles. If newid is 0, then compare
1310 * the old article in oldid to the current article; if oldid is 0, then
1311 * compare the current article to the immediately previous one (ignoring the
1314 * If oldid is false, leave the corresponding revision object set
1315 * to false. This is impossible via ordinary user input, and is provided for
1320 public function loadRevisionData() {
1321 if ( $this->mRevisionsLoaded
) {
1325 // Whether it succeeds or fails, we don't want to try again
1326 $this->mRevisionsLoaded
= true;
1328 $this->loadRevisionIds();
1330 // Load the new revision object
1331 if ( $this->mNewid
) {
1332 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1334 $this->mNewRev
= Revision
::newFromTitle(
1337 Revision
::READ_NORMAL
1341 if ( !$this->mNewRev
instanceof Revision
) {
1345 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1346 $this->mNewid
= $this->mNewRev
->getId();
1347 $this->mNewPage
= $this->mNewRev
->getTitle();
1349 // Load the old revision object
1350 $this->mOldRev
= false;
1351 if ( $this->mOldid
) {
1352 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1353 } elseif ( $this->mOldid
=== 0 ) {
1354 $rev = $this->mNewRev
->getPrevious();
1356 $this->mOldid
= $rev->getId();
1357 $this->mOldRev
= $rev;
1359 // No previous revision; mark to show as first-version only.
1360 $this->mOldid
= false;
1361 $this->mOldRev
= false;
1363 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1365 if ( is_null( $this->mOldRev
) ) {
1369 if ( $this->mOldRev
) {
1370 $this->mOldPage
= $this->mOldRev
->getTitle();
1373 // Load tags information for both revisions
1374 $dbr = wfGetDB( DB_REPLICA
);
1375 if ( $this->mOldid
!== false ) {
1376 $this->mOldTags
= $dbr->selectField(
1379 [ 'ts_rev_id' => $this->mOldid
],
1383 $this->mOldTags
= false;
1385 $this->mNewTags
= $dbr->selectField(
1388 [ 'ts_rev_id' => $this->mNewid
],
1396 * Load the text of the revisions, as well as revision data.
1400 public function loadText() {
1401 if ( $this->mTextLoaded
== 2 ) {
1405 // Whether it succeeds or fails, we don't want to try again
1406 $this->mTextLoaded
= 2;
1408 if ( !$this->loadRevisionData() ) {
1412 if ( $this->mOldRev
) {
1413 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1414 if ( $this->mOldContent
=== null ) {
1419 if ( $this->mNewRev
) {
1420 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1421 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1422 if ( $this->mNewContent
=== null ) {
1431 * Load the text of the new revision, not the old one
1435 public function loadNewText() {
1436 if ( $this->mTextLoaded
>= 1 ) {
1440 $this->mTextLoaded
= 1;
1442 if ( !$this->loadRevisionData() ) {
1446 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1448 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );