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 [ 'ar_rev_id' => $id ],
188 $rev = Revision
::newFromArchiveRow( $row );
189 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
191 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
192 'target' => $title->getPrefixedText(),
193 'timestamp' => $rev->getTimestamp()
202 * Build a wikitext link toward a deleted revision, if viewable.
204 * @param int $id Revision ID
206 * @return string Wikitext fragment
208 public function deletedIdMarker( $id ) {
209 $link = $this->deletedLink( $id );
211 return "[$link $id]";
217 private function showMissingRevision() {
218 $out = $this->getOutput();
221 if ( $this->mOldRev
=== null ||
222 ( $this->mOldRev
&& $this->mOldContent
=== null )
224 $missing[] = $this->deletedIdMarker( $this->mOldid
);
226 if ( $this->mNewRev
=== null ||
227 ( $this->mNewRev
&& $this->mNewContent
=== null )
229 $missing[] = $this->deletedIdMarker( $this->mNewid
);
232 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
233 $msg = $this->msg( 'difference-missing-revision' )
234 ->params( $this->getLanguage()->listToText( $missing ) )
235 ->numParams( count( $missing ) )
237 $out->addHTML( $msg );
240 public function showDiffPage( $diffOnly = false ) {
241 # Allow frames except in certain special cases
242 $out = $this->getOutput();
243 $out->allowClickjacking();
244 $out->setRobotPolicy( 'noindex,nofollow' );
246 // Allow extensions to add any extra output here
247 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
249 if ( !$this->loadRevisionData() ) {
250 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
251 $this->showMissingRevision();
256 $user = $this->getUser();
257 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
258 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
259 $permErrors = wfMergeErrorArrays( $permErrors,
260 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
262 if ( count( $permErrors ) ) {
263 throw new PermissionsError( 'read', $permErrors );
269 # Carry over 'diffonly' param via navigation links
270 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
271 $query['diffonly'] = $diffOnly;
273 # Cascade unhide param in links for easy deletion browsing
274 if ( $this->unhide
) {
275 $query['unhide'] = 1;
278 # Check if one of the revisions is deleted/suppressed
279 $deleted = $suppressed = false;
280 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
284 # mOldRev is false if the difference engine is called with a "vague" query for
285 # a diff between a version V and its previous version V' AND the version V
286 # is the first version of that article. In that case, V' does not exist.
287 if ( $this->mOldRev
=== false ) {
288 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
291 // Allow extensions to change the $oldHeader variable
292 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
294 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
296 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
297 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
300 $out->setPageTitle( $this->msg( 'difference-title-multipage',
301 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
302 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
306 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
307 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
308 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
309 if ( $rollbackLink ) {
310 $out->preventClickjacking();
311 $rollback = '   ' . $rollbackLink;
315 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
316 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
318 $undoLink = Html
::element( 'a', [
319 'href' => $this->mNewPage
->getLocalURL( [
321 'undoafter' => $this->mOldid
,
322 'undo' => $this->mNewid
324 'title' => Linker
::titleAttrib( 'undo' ),
326 $this->msg( 'editundo' )->text()
328 $revisionTools['mw-diff-undo'] = $undoLink;
332 # Make "previous revision link"
333 if ( $samePage && $this->mOldRev
->getPrevious() ) {
334 $prevlink = Linker
::linkKnown(
336 $this->msg( 'previousdiff' )->escaped(),
337 [ 'id' => 'differences-prevlink' ],
338 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
341 $prevlink = ' ';
344 if ( $this->mOldRev
->isMinor() ) {
345 $oldminor = ChangesList
::flag( 'minor' );
350 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
351 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
352 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
354 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
355 '<div id="mw-diff-otitle2">' .
356 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
357 '<div id="mw-diff-otitle3">' . $oldminor .
358 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
359 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
360 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
362 // Allow extensions to change the $oldHeader variable
363 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
364 $diffOnly, $ldel, $this->unhide
] );
366 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
367 $deleted = true; // old revisions text is hidden
368 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
369 $suppressed = true; // also suppressed
373 # Check if this user can see the revisions
374 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
379 $out->addJsConfigVars( [
380 'wgDiffOldId' => $this->mOldid
,
381 'wgDiffNewId' => $this->mNewid
,
384 # Make "next revision link"
385 # Skip next link on the top revision
386 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
387 $nextlink = Linker
::linkKnown(
389 $this->msg( 'nextdiff' )->escaped(),
390 [ 'id' => 'differences-nextlink' ],
391 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
394 $nextlink = ' ';
397 if ( $this->mNewRev
->isMinor() ) {
398 $newminor = ChangesList
::flag( 'minor' );
403 # Handle RevisionDelete links...
404 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
406 # Allow extensions to define their own revision tools
407 Hooks
::run( 'DiffRevisionTools',
408 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
409 $formattedRevisionTools = [];
410 // Put each one in parentheses (poor man's button)
411 foreach ( $revisionTools as $key => $tool ) {
412 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
413 $element = Html
::rawElement(
415 [ 'class' => $toolClass ],
416 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
418 $formattedRevisionTools[] = $element;
420 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
421 ' ' . implode( ' ', $formattedRevisionTools );
422 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
424 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
425 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
427 '<div id="mw-diff-ntitle3">' . $newminor .
428 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
429 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
430 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
432 // Allow extensions to change the $newHeader variable
433 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
434 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
436 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
437 $deleted = true; // new revisions text is hidden
438 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
439 $suppressed = true; // also suppressed
443 # If the diff cannot be shown due to a deleted revision, then output
444 # the diff header and links to unhide (if available)...
445 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
446 $this->showDiffStyle();
447 $multi = $this->getMultiNotice();
448 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
450 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
451 # Give explanation for why revision is not visible
452 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
455 # Give explanation and add a link to view the diff...
456 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
457 $link = $this->getTitle()->getFullURL( $query );
458 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
460 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
464 # Otherwise, output a regular diff...
466 # Add deletion notice if the user is viewing deleted content
469 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
470 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
471 $this->msg( $msg )->parse() .
474 $this->showDiff( $oldHeader, $newHeader, $notice );
476 $this->renderNewRevision();
482 * Build a link to mark a change as patrolled.
484 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
485 * Side effect: When the patrol link is build, this method will call
486 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
488 * @return string HTML or empty string
490 public function markPatrolledLink() {
491 if ( $this->mMarkPatrolledLink
=== null ) {
492 $linkInfo = $this->getMarkPatrolledLinkInfo();
493 // If false, there is no patrol link needed/allowed
495 $this->mMarkPatrolledLink
= '';
497 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
500 $this->msg( 'markaspatrolleddiff' )->escaped(),
503 'action' => 'markpatrolled',
504 'rcid' => $linkInfo['rcid'],
507 // Allow extensions to change the markpatrolled link
508 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
509 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
512 return $this->mMarkPatrolledLink
;
516 * Returns an array of meta data needed to build a "mark as patrolled" link and
517 * adds the mediawiki.page.patrol.ajax to the output.
519 * @return array|false An array of meta data for a patrol link (rcid only)
520 * or false if no link is needed
522 protected function getMarkPatrolledLinkInfo() {
523 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
525 $user = $this->getUser();
527 // Prepare a change patrol link, if applicable
529 // Is patrolling enabled and the user allowed to?
530 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
531 // Only do this if the revision isn't more than 6 hours older
532 // than the Max RC age (6h because the RC might not be cleaned out regularly)
533 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
535 // Look for an unpatrolled change corresponding to this diff
536 $db = wfGetDB( DB_REPLICA
);
537 $change = RecentChange
::newFromConds(
539 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
540 'rc_this_oldid' => $this->mNewid
,
546 if ( $change && !$change->getPerformer()->equals( $user ) ) {
547 $rcid = $change->getAttribute( 'rc_id' );
549 // None found or the page has been created by the current user.
550 // If the user could patrol this it already would be patrolled
554 // Allow extensions to possibly change the rcid here
555 // For example the rcid might be set to zero due to the user
556 // being the same as the performer of the change but an extension
557 // might still want to show it under certain conditions
558 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
562 $this->getOutput()->preventClickjacking();
563 if ( $wgEnableAPI && $wgEnableWriteAPI
564 && $user->isAllowed( 'writeapi' )
566 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
575 // No mark as patrolled link applicable
580 * @param Revision $rev
584 protected function revisionDeleteLink( $rev ) {
585 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
586 if ( $link !== '' ) {
587 $link = '   ' . $link . ' ';
594 * Show the new revision of the page.
596 public function renderNewRevision() {
597 $out = $this->getOutput();
598 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
599 # Add "current version as of X" title
600 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
601 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
602 # Page content may be handled by a hooked call instead...
603 # @codingStandardsIgnoreStart Ignoring long lines.
604 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
605 $this->loadNewText();
606 $out->setRevisionId( $this->mNewid
);
607 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
608 $out->setArticleFlag( true );
610 if ( !Hooks
::run( 'ArticleContentViewCustom', [ $this->mNewContent
, $this->mNewPage
, $out ] ) ) {
611 // Handled by extension
614 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
615 // If the Title stored in the context is the same as the one
616 // of the new revision, we can use its associated WikiPage
618 $wikiPage = $this->getWikiPage();
620 // Otherwise we need to create our own WikiPage object
621 $wikiPage = WikiPage
::factory( $this->mNewPage
);
624 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
626 # WikiPage::getParserOutput() should not return false, but just in case
627 if ( $parserOutput ) {
628 // Allow extensions to change parser output here
629 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput', [ $this, $out, $parserOutput, $wikiPage ] ) ) {
630 $out->addParserOutput( $parserOutput );
635 # @codingStandardsIgnoreEnd
637 // Allow extensions to optionally not show the final patrolled link
638 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
639 # Add redundant patrol link on bottom...
640 $out->addHTML( $this->markPatrolledLink() );
644 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
645 $parserOptions = $page->makeParserOptions( $this->getContext() );
647 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( 'edit', $this->getUser() ) ) {
648 $parserOptions->setEditSection( false );
651 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
653 return $parserOutput;
657 * Get the diff text, send it to the OutputPage object
658 * Returns false if the diff could not be generated, otherwise returns true
660 * @param string|bool $otitle Header for old text or false
661 * @param string|bool $ntitle Header for new text or false
662 * @param string $notice HTML between diff header and body
666 public function showDiff( $otitle, $ntitle, $notice = '' ) {
667 // Allow extensions to affect the output here
668 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
670 $diff = $this->getDiff( $otitle, $ntitle, $notice );
671 if ( $diff === false ) {
672 $this->showMissingRevision();
676 $this->showDiffStyle();
677 $this->getOutput()->addHTML( $diff );
684 * Add style sheets for diff display.
686 public function showDiffStyle() {
687 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
691 * Get complete diff table, including header
693 * @param string|bool $otitle Header for old text or false
694 * @param string|bool $ntitle Header for new text or false
695 * @param string $notice HTML between diff header and body
699 public function getDiff( $otitle, $ntitle, $notice = '' ) {
700 $body = $this->getDiffBody();
701 if ( $body === false ) {
705 $multi = $this->getMultiNotice();
706 // Display a message when the diff is empty
707 if ( $body === '' ) {
708 $notice .= '<div class="mw-diff-empty">' .
709 $this->msg( 'diff-empty' )->parse() .
713 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
717 * Get the diff table body, without header
719 * @return mixed (string/false)
721 public function getDiffBody() {
722 $this->mCacheHit
= true;
723 // Check if the diff should be hidden from this user
724 if ( !$this->loadRevisionData() ) {
726 } elseif ( $this->mOldRev
&&
727 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
730 } elseif ( $this->mNewRev
&&
731 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
736 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
737 && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
739 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
745 $cache = ObjectCache
::getMainWANInstance();
746 if ( $this->mOldid
&& $this->mNewid
) {
747 $key = $this->getDiffBodyCacheKey();
750 if ( !$this->mRefreshCache
) {
751 $difftext = $cache->get( $key );
753 wfIncrStats( 'diff_cache.hit' );
754 $difftext = $this->localiseLineNumbers( $difftext );
755 $difftext .= "\n<!-- diff cache key $key -->\n";
759 } // don't try to load but save the result
761 $this->mCacheHit
= false;
763 // Loadtext is permission safe, this just clears out the diff
764 if ( !$this->loadText() ) {
768 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
770 // Avoid PHP 7.1 warning from passing $this by reference
773 // Save to cache for 7 days
774 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
775 wfIncrStats( 'diff_cache.uncacheable' );
776 } elseif ( $key !== false && $difftext !== false ) {
777 wfIncrStats( 'diff_cache.miss' );
778 $cache->set( $key, $difftext, 7 * 86400 );
780 wfIncrStats( 'diff_cache.uncacheable' );
782 // Replace line numbers with the text in the user's language
783 if ( $difftext !== false ) {
784 $difftext = $this->localiseLineNumbers( $difftext );
791 * Returns the cache key for diff body text or content.
795 * @throws MWException
798 protected function getDiffBodyCacheKey() {
799 if ( !$this->mOldid ||
!$this->mNewid
) {
800 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
803 return wfMemcKey( 'diff', 'version', self
::DIFF_VERSION
,
804 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
808 * Generate a diff, no caching.
810 * This implementation uses generateTextDiffBody() to generate a diff based on the default
811 * serialization of the given Content objects. This will fail if $old or $new are not
812 * instances of TextContent.
814 * Subclasses may override this to provide a different rendering for the diff,
815 * perhaps taking advantage of the content's native form. This is required for all content
816 * models that are not text based.
820 * @param Content $old Old content
821 * @param Content $new New content
823 * @throws MWException If old or new content is not an instance of TextContent.
824 * @return bool|string
826 public function generateContentDiffBody( Content
$old, Content
$new ) {
827 if ( !( $old instanceof TextContent
) ) {
828 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
829 "override generateContentDiffBody to fix this." );
832 if ( !( $new instanceof TextContent
) ) {
833 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
834 . "override generateContentDiffBody to fix this." );
837 $otext = $old->serialize();
838 $ntext = $new->serialize();
840 return $this->generateTextDiffBody( $otext, $ntext );
844 * Generate a diff, no caching
846 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
848 * @param string $otext Old text, must be already segmented
849 * @param string $ntext New text, must be already segmented
851 * @return bool|string
853 public function generateTextDiffBody( $otext, $ntext ) {
854 $diff = function () use ( $otext, $ntext ) {
855 $time = microtime( true );
857 $result = $this->textDiff( $otext, $ntext );
859 $time = intval( ( microtime( true ) - $time ) * 1000 );
860 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
861 // Log requests slower than 99th percentile
862 if ( $time > 100 && $this->mOldPage
&& $this->mNewPage
) {
864 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
871 * @param Status $status
874 $error = function ( $status ) {
875 throw new FatalError( $status->getWikiText() );
878 // Use PoolCounter if the diff looks like it can be expensive
879 if ( strlen( $otext ) +
strlen( $ntext ) > 20000 ) {
880 $work = new PoolCounterWorkViaCallback( 'diff',
881 md5( $otext ) . md5( $ntext ),
882 [ 'doWork' => $diff, 'error' => $error ]
884 return $work->execute();
891 * Generates diff, to be wrapped internally in a logging/instrumentation
893 * @param string $otext Old text, must be already segmented
894 * @param string $ntext New text, must be already segmented
895 * @return bool|string
897 protected function textDiff( $otext, $ntext ) {
898 global $wgExternalDiffEngine, $wgContLang;
900 $otext = str_replace( "\r\n", "\n", $otext );
901 $ntext = str_replace( "\r\n", "\n", $ntext );
903 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
904 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
905 $wgExternalDiffEngine = false;
906 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
907 // Same as above, but with no deprecation warnings
908 $wgExternalDiffEngine = false;
909 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
910 // And prevent people from shooting themselves in the foot...
911 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
912 $wgExternalDiffEngine = false;
915 // Better external diff engine, the 2 may some day be dropped
916 // This one does the escaping and segmenting itself
917 if ( function_exists( 'wikidiff2_do_diff' ) && $wgExternalDiffEngine === false ) {
918 $wikidiff2Version = phpversion( 'wikidiff2' );
920 $wikidiff2Version !== false &&
921 version_compare( $wikidiff2Version, '0.3.0', '>=' )
923 $text = wikidiff2_do_diff(
927 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
930 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
931 $text = wikidiff2_do_diff(
937 // Log a warning in case the configuration value is set to not silently ignore it
938 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
939 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
940 effect since the used version of WikiDiff2 does not support it.' );
944 $text .= $this->debug( 'wikidiff2' );
947 } elseif ( $wgExternalDiffEngine !== false && is_executable( $wgExternalDiffEngine ) ) {
949 $tmpDir = wfTempDir();
950 $tempName1 = tempnam( $tmpDir, 'diff_' );
951 $tempName2 = tempnam( $tmpDir, 'diff_' );
953 $tempFile1 = fopen( $tempName1, "w" );
957 $tempFile2 = fopen( $tempName2, "w" );
961 fwrite( $tempFile1, $otext );
962 fwrite( $tempFile2, $ntext );
963 fclose( $tempFile1 );
964 fclose( $tempFile2 );
965 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
966 $difftext = wfShellExec( $cmd );
967 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
968 unlink( $tempName1 );
969 unlink( $tempName2 );
975 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
976 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
977 $diffs = new Diff( $ota, $nta );
978 $formatter = new TableDiffFormatter();
979 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
985 * Generate a debug comment indicating diff generating time,
986 * server node, and generator backend.
988 * @param string $generator : What diff engine was used
992 protected function debug( $generator = "internal" ) {
993 global $wgShowHostnames;
994 if ( !$this->enableDebugComment
) {
997 $data = [ $generator ];
998 if ( $wgShowHostnames ) {
999 $data[] = wfHostname();
1001 $data[] = wfTimestamp( TS_DB
);
1003 return "<!-- diff generator: " .
1004 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1009 * Replace line numbers with the text in the user's language
1011 * @param string $text
1015 public function localiseLineNumbers( $text ) {
1016 return preg_replace_callback(
1017 '/<!--LINE (\d+)-->/',
1018 [ $this, 'localiseLineNumbersCb' ],
1023 public function localiseLineNumbersCb( $matches ) {
1024 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1028 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1032 * If there are revisions between the ones being compared, return a note saying so.
1036 public function getMultiNotice() {
1037 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
1039 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
1040 // Comparing two different pages? Count would be meaningless.
1044 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1045 $oldRev = $this->mNewRev
; // flip
1046 $newRev = $this->mOldRev
; // flip
1047 } else { // normal case
1048 $oldRev = $this->mOldRev
;
1049 $newRev = $this->mNewRev
;
1052 // Sanity: don't show the notice if too many rows must be scanned
1053 // @todo show some special message for that case
1054 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1055 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1056 $limit = 100; // use diff-multi-manyusers if too many users
1057 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1058 $numUsers = count( $users );
1060 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1061 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1064 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1067 return ''; // nothing
1071 * Get a notice about how many intermediate edits and users there are
1073 * @param int $numEdits
1074 * @param int $numUsers
1079 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1080 if ( $numUsers === 0 ) {
1081 $msg = 'diff-multi-sameuser';
1082 } elseif ( $numUsers > $limit ) {
1083 $msg = 'diff-multi-manyusers';
1086 $msg = 'diff-multi-otherusers';
1089 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1093 * Get a header for a specified revision.
1095 * @param Revision $rev
1096 * @param string $complete 'complete' to get the header wrapped depending
1097 * the visibility of the revision and a link to edit the page.
1099 * @return string HTML fragment
1101 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1102 $lang = $this->getLanguage();
1103 $user = $this->getUser();
1104 $revtimestamp = $rev->getTimestamp();
1105 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1106 $dateofrev = $lang->userDate( $revtimestamp, $user );
1107 $timeofrev = $lang->userTime( $revtimestamp, $user );
1109 $header = $this->msg(
1110 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1116 if ( $complete !== 'complete' ) {
1120 $title = $rev->getTitle();
1122 $header = Linker
::linkKnown( $title, $header, [],
1123 [ 'oldid' => $rev->getId() ] );
1125 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1126 $editQuery = [ 'action' => 'edit' ];
1127 if ( !$rev->isCurrent() ) {
1128 $editQuery['oldid'] = $rev->getId();
1131 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1132 $msg = $this->msg( $key )->escaped();
1133 $editLink = $this->msg( 'parentheses' )->rawParams(
1134 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1135 $header .= ' ' . Html
::rawElement(
1137 [ 'class' => 'mw-diff-edit' ],
1140 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1141 $header = Html
::rawElement(
1143 [ 'class' => 'history-deleted' ],
1148 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1155 * Add the header to a diff body
1157 * @param string $diff Diff body
1158 * @param string $otitle Old revision header
1159 * @param string $ntitle New revision header
1160 * @param string $multi Notice telling user that there are intermediate
1161 * revisions between the ones being compared
1162 * @param string $notice Other notices, e.g. that user is viewing deleted content
1166 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1167 // shared.css sets diff in interface language/dir, but the actual content
1168 // is often in a different language, mostly the page content language/dir
1169 $header = Html
::openElement( 'table', [
1170 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1171 'data-mw' => 'interface',
1173 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1175 if ( !$diff && !$otitle ) {
1177 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1178 <td class=\"diff-ntitle\">{$ntitle}</td>
1182 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1184 <col class=\"diff-marker\" />
1185 <col class=\"diff-content\" />
1186 <col class=\"diff-marker\" />
1187 <col class=\"diff-content\" />";
1194 if ( $otitle ||
$ntitle ) {
1196 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1197 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1198 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1203 if ( $multi != '' ) {
1204 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1205 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1207 if ( $notice != '' ) {
1208 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1209 "lang=\"{$userLang}\">{$notice}</td></tr>";
1212 return $header . $diff . "</table>";
1216 * Use specified text instead of loading from the database
1217 * @param Content $oldContent
1218 * @param Content $newContent
1221 public function setContent( Content
$oldContent, Content
$newContent ) {
1222 $this->mOldContent
= $oldContent;
1223 $this->mNewContent
= $newContent;
1225 $this->mTextLoaded
= 2;
1226 $this->mRevisionsLoaded
= true;
1230 * Set the language in which the diff text is written
1231 * (Defaults to page content language).
1232 * @param Language|string $lang
1235 public function setTextLanguage( $lang ) {
1236 $this->mDiffLang
= wfGetLangObj( $lang );
1240 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1241 * to a pair of actual integers representing revision ids.
1243 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1244 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1246 * @return int[] List of two revision ids, older first, later second.
1247 * Zero signifies invalid argument passed.
1248 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1250 public function mapDiffPrevNext( $old, $new ) {
1251 if ( $new === 'prev' ) {
1252 // Show diff between revision $old and the previous one. Get previous one from DB.
1253 $newid = intval( $old );
1254 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1255 } elseif ( $new === 'next' ) {
1256 // Show diff between revision $old and the next one. Get next one from DB.
1257 $oldid = intval( $old );
1258 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1260 $oldid = intval( $old );
1261 $newid = intval( $new );
1264 return [ $oldid, $newid ];
1270 private function loadRevisionIds() {
1271 if ( $this->mRevisionsIdsLoaded
) {
1275 $this->mRevisionsIdsLoaded
= true;
1277 $old = $this->mOldid
;
1278 $new = $this->mNewid
;
1280 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1281 if ( $new === 'next' && $this->mNewid
=== false ) {
1282 # if no result, NewId points to the newest old revision. The only newer
1283 # revision is cur, which is "0".
1288 'NewDifferenceEngine',
1289 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1294 * Load revision metadata for the specified articles. If newid is 0, then compare
1295 * the old article in oldid to the current article; if oldid is 0, then
1296 * compare the current article to the immediately previous one (ignoring the
1299 * If oldid is false, leave the corresponding revision object set
1300 * to false. This is impossible via ordinary user input, and is provided for
1305 public function loadRevisionData() {
1306 if ( $this->mRevisionsLoaded
) {
1310 // Whether it succeeds or fails, we don't want to try again
1311 $this->mRevisionsLoaded
= true;
1313 $this->loadRevisionIds();
1315 // Load the new revision object
1316 if ( $this->mNewid
) {
1317 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1319 $this->mNewRev
= Revision
::newFromTitle(
1322 Revision
::READ_NORMAL
1326 if ( !$this->mNewRev
instanceof Revision
) {
1330 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1331 $this->mNewid
= $this->mNewRev
->getId();
1332 $this->mNewPage
= $this->mNewRev
->getTitle();
1334 // Load the old revision object
1335 $this->mOldRev
= false;
1336 if ( $this->mOldid
) {
1337 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1338 } elseif ( $this->mOldid
=== 0 ) {
1339 $rev = $this->mNewRev
->getPrevious();
1341 $this->mOldid
= $rev->getId();
1342 $this->mOldRev
= $rev;
1344 // No previous revision; mark to show as first-version only.
1345 $this->mOldid
= false;
1346 $this->mOldRev
= false;
1348 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1350 if ( is_null( $this->mOldRev
) ) {
1354 if ( $this->mOldRev
) {
1355 $this->mOldPage
= $this->mOldRev
->getTitle();
1358 // Load tags information for both revisions
1359 $dbr = wfGetDB( DB_REPLICA
);
1360 if ( $this->mOldid
!== false ) {
1361 $this->mOldTags
= $dbr->selectField(
1364 [ 'ts_rev_id' => $this->mOldid
],
1368 $this->mOldTags
= false;
1370 $this->mNewTags
= $dbr->selectField(
1373 [ 'ts_rev_id' => $this->mNewid
],
1381 * Load the text of the revisions, as well as revision data.
1385 public function loadText() {
1386 if ( $this->mTextLoaded
== 2 ) {
1390 // Whether it succeeds or fails, we don't want to try again
1391 $this->mTextLoaded
= 2;
1393 if ( !$this->loadRevisionData() ) {
1397 if ( $this->mOldRev
) {
1398 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1399 if ( $this->mOldContent
=== null ) {
1404 if ( $this->mNewRev
) {
1405 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1406 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1407 if ( $this->mNewContent
=== null ) {
1416 * Load the text of the new revision, not the old one
1420 public function loadNewText() {
1421 if ( $this->mTextLoaded
>= 1 ) {
1425 $this->mTextLoaded
= 1;
1427 if ( !$this->loadRevisionData() ) {
1431 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1433 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );