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
;
28 * @ingroup DifferenceEngine
30 class DifferenceEngine
extends ContextSource
{
32 * Constant to indicate diff cache compatibility.
33 * Bump this when changing the diff formatting in a way that
34 * fixes important bugs or such to force cached diff views to
37 const DIFF_VERSION
= '1.12';
39 /** @var int Revision ID or 0 for current */
42 /** @var int|string Revision ID or null for current or an alias such as 'next' */
48 /** @var Content|null */
51 /** @var Content|null */
63 /** @var Revision|null */
66 /** @var Revision|null */
69 /** @var bool Have the revisions IDs been loaded */
70 private $mRevisionsIdsLoaded = false;
72 /** @var bool Have the revisions been loaded */
73 public $mRevisionsLoaded = false;
75 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
76 public $mTextLoaded = 0;
79 * Was the content overridden via setContent()?
80 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored.
83 protected $isContentOverridden = false;
85 /** @var bool Was the diff fetched from cache? */
86 public $mCacheHit = false;
89 * Set this to true to add debug info to the HTML output.
90 * Warning: this may cause RSS readers to spuriously mark articles as "new"
93 public $enableDebugComment = false;
95 /** @var bool If true, line X is not displayed when X is 1, for example
96 * to increase readability and conserve space with many small diffs.
98 protected $mReducedLineNumbers = false;
100 /** @var string Link to action=markpatrolled */
101 protected $mMarkPatrolledLink = null;
103 /** @var bool Show rev_deleted content if allowed */
104 protected $unhide = false;
106 /** @var bool Refresh the diff cache */
107 protected $mRefreshCache = false;
112 * @param IContextSource|null $context Context to use, anything else will be ignored
113 * @param int $old Old ID we want to show and diff with.
114 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
115 * @param int $rcid Deprecated, no longer used!
116 * @param bool $refreshCache If set, refreshes the diff cache
117 * @param bool $unhide If set, allow viewing deleted revs
119 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
120 $refreshCache = false, $unhide = false
122 if ( $context instanceof IContextSource
) {
123 $this->setContext( $context );
126 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
128 $this->mOldid
= $old;
129 $this->mNewid
= $new;
130 $this->mRefreshCache
= $refreshCache;
131 $this->unhide
= $unhide;
137 public function setReducedLineNumbers( $value = true ) {
138 $this->mReducedLineNumbers
= $value;
142 * Get the language of the difference engine, defaults to page content language
146 public function getDiffLang() {
147 if ( $this->mDiffLang
=== null ) {
148 # Default language in which the diff text is written.
149 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
152 return $this->mDiffLang
;
158 public function wasCacheHit() {
159 return $this->mCacheHit
;
165 public function getOldid() {
166 $this->loadRevisionIds();
168 return $this->mOldid
;
174 public function getNewid() {
175 $this->loadRevisionIds();
177 return $this->mNewid
;
181 * Look up a special:Undelete link to the given deleted revision id,
182 * as a workaround for being unable to load deleted diffs in currently.
184 * @param int $id Revision ID
186 * @return string|bool Link HTML or false
188 public function deletedLink( $id ) {
189 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
190 $dbr = wfGetDB( DB_REPLICA
);
191 $arQuery = Revision
::getArchiveQueryInfo();
192 $row = $dbr->selectRow(
194 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
195 [ 'ar_rev_id' => $id ],
201 $rev = Revision
::newFromArchiveRow( $row );
202 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
204 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
205 'target' => $title->getPrefixedText(),
206 'timestamp' => $rev->getTimestamp()
215 * Build a wikitext link toward a deleted revision, if viewable.
217 * @param int $id Revision ID
219 * @return string Wikitext fragment
221 public function deletedIdMarker( $id ) {
222 $link = $this->deletedLink( $id );
224 return "[$link $id]";
230 private function showMissingRevision() {
231 $out = $this->getOutput();
234 if ( $this->mOldRev
=== null ||
235 ( $this->mOldRev
&& $this->mOldContent
=== null )
237 $missing[] = $this->deletedIdMarker( $this->mOldid
);
239 if ( $this->mNewRev
=== null ||
240 ( $this->mNewRev
&& $this->mNewContent
=== null )
242 $missing[] = $this->deletedIdMarker( $this->mNewid
);
245 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
246 $msg = $this->msg( 'difference-missing-revision' )
247 ->params( $this->getLanguage()->listToText( $missing ) )
248 ->numParams( count( $missing ) )
250 $out->addHTML( $msg );
253 public function showDiffPage( $diffOnly = false ) {
254 # Allow frames except in certain special cases
255 $out = $this->getOutput();
256 $out->allowClickjacking();
257 $out->setRobotPolicy( 'noindex,nofollow' );
259 // Allow extensions to add any extra output here
260 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
262 if ( !$this->loadRevisionData() ) {
263 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
264 $this->showMissingRevision();
269 $user = $this->getUser();
270 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
271 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
272 $permErrors = wfMergeErrorArrays( $permErrors,
273 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
275 if ( count( $permErrors ) ) {
276 throw new PermissionsError( 'read', $permErrors );
282 # Carry over 'diffonly' param via navigation links
283 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
284 $query['diffonly'] = $diffOnly;
286 # Cascade unhide param in links for easy deletion browsing
287 if ( $this->unhide
) {
288 $query['unhide'] = 1;
291 # Check if one of the revisions is deleted/suppressed
292 $deleted = $suppressed = false;
293 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
297 # mOldRev is false if the difference engine is called with a "vague" query for
298 # a diff between a version V and its previous version V' AND the version V
299 # is the first version of that article. In that case, V' does not exist.
300 if ( $this->mOldRev
=== false ) {
301 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
304 // Allow extensions to change the $oldHeader variable
305 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
307 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
309 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
310 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
313 $out->setPageTitle( $this->msg( 'difference-title-multipage',
314 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
315 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
319 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
320 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
321 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
322 if ( $rollbackLink ) {
323 $out->preventClickjacking();
324 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
328 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
329 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
331 $undoLink = Html
::element( 'a', [
332 'href' => $this->mNewPage
->getLocalURL( [
334 'undoafter' => $this->mOldid
,
335 'undo' => $this->mNewid
337 'title' => Linker
::titleAttrib( 'undo' ),
339 $this->msg( 'editundo' )->text()
341 $revisionTools['mw-diff-undo'] = $undoLink;
345 # Make "previous revision link"
346 if ( $samePage && $this->mOldRev
->getPrevious() ) {
347 $prevlink = Linker
::linkKnown(
349 $this->msg( 'previousdiff' )->escaped(),
350 [ 'id' => 'differences-prevlink' ],
351 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
354 $prevlink = "\u{00A0}";
357 if ( $this->mOldRev
->isMinor() ) {
358 $oldminor = ChangesList
::flag( 'minor' );
363 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
364 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
365 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
367 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
368 '<div id="mw-diff-otitle2">' .
369 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
370 '<div id="mw-diff-otitle3">' . $oldminor .
371 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
372 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
373 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
375 // Allow extensions to change the $oldHeader variable
376 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
377 $diffOnly, $ldel, $this->unhide
] );
379 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
380 $deleted = true; // old revisions text is hidden
381 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
382 $suppressed = true; // also suppressed
386 # Check if this user can see the revisions
387 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
392 $out->addJsConfigVars( [
393 'wgDiffOldId' => $this->mOldid
,
394 'wgDiffNewId' => $this->mNewid
,
397 # Make "next revision link"
398 # Skip next link on the top revision
399 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
400 $nextlink = Linker
::linkKnown(
402 $this->msg( 'nextdiff' )->escaped(),
403 [ 'id' => 'differences-nextlink' ],
404 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
407 $nextlink = "\u{00A0}";
410 if ( $this->mNewRev
->isMinor() ) {
411 $newminor = ChangesList
::flag( 'minor' );
416 # Handle RevisionDelete links...
417 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
419 # Allow extensions to define their own revision tools
420 Hooks
::run( 'DiffRevisionTools',
421 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
422 $formattedRevisionTools = [];
423 // Put each one in parentheses (poor man's button)
424 foreach ( $revisionTools as $key => $tool ) {
425 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
426 $element = Html
::rawElement(
428 [ 'class' => $toolClass ],
429 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
431 $formattedRevisionTools[] = $element;
433 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
434 ' ' . implode( ' ', $formattedRevisionTools );
435 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
437 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
438 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
440 '<div id="mw-diff-ntitle3">' . $newminor .
441 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
442 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
443 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
445 // Allow extensions to change the $newHeader variable
446 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
447 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
449 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
450 $deleted = true; // new revisions text is hidden
451 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
452 $suppressed = true; // also suppressed
456 # If the diff cannot be shown due to a deleted revision, then output
457 # the diff header and links to unhide (if available)...
458 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
459 $this->showDiffStyle();
460 $multi = $this->getMultiNotice();
461 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
463 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
464 # Give explanation for why revision is not visible
465 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
468 # Give explanation and add a link to view the diff...
469 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
470 $link = $this->getTitle()->getFullURL( $query );
471 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
473 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
477 # Otherwise, output a regular diff...
479 # Add deletion notice if the user is viewing deleted content
482 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
483 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
484 $this->msg( $msg )->parse() .
487 $this->showDiff( $oldHeader, $newHeader, $notice );
489 $this->renderNewRevision();
495 * Build a link to mark a change as patrolled.
497 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
498 * Side effect: When the patrol link is build, this method will call
499 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
501 * @return string HTML or empty string
503 public function markPatrolledLink() {
504 if ( $this->mMarkPatrolledLink
=== null ) {
505 $linkInfo = $this->getMarkPatrolledLinkInfo();
506 // If false, there is no patrol link needed/allowed
508 $this->mMarkPatrolledLink
= '';
510 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
513 $this->msg( 'markaspatrolleddiff' )->escaped(),
516 'action' => 'markpatrolled',
517 'rcid' => $linkInfo['rcid'],
520 // Allow extensions to change the markpatrolled link
521 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
522 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
525 return $this->mMarkPatrolledLink
;
529 * Returns an array of meta data needed to build a "mark as patrolled" link and
530 * adds the mediawiki.page.patrol.ajax to the output.
532 * @return array|false An array of meta data for a patrol link (rcid only)
533 * or false if no link is needed
535 protected function getMarkPatrolledLinkInfo() {
536 global $wgUseRCPatrol;
538 $user = $this->getUser();
540 // Prepare a change patrol link, if applicable
542 // Is patrolling enabled and the user allowed to?
543 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
544 // Only do this if the revision isn't more than 6 hours older
545 // than the Max RC age (6h because the RC might not be cleaned out regularly)
546 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
548 // Look for an unpatrolled change corresponding to this diff
549 $db = wfGetDB( DB_REPLICA
);
550 $change = RecentChange
::newFromConds(
552 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
553 'rc_this_oldid' => $this->mNewid
,
554 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
559 if ( $change && !$change->getPerformer()->equals( $user ) ) {
560 $rcid = $change->getAttribute( 'rc_id' );
562 // None found or the page has been created by the current user.
563 // If the user could patrol this it already would be patrolled
567 // Allow extensions to possibly change the rcid here
568 // For example the rcid might be set to zero due to the user
569 // being the same as the performer of the change but an extension
570 // might still want to show it under certain conditions
571 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
575 $this->getOutput()->preventClickjacking();
576 if ( $user->isAllowed( 'writeapi' ) ) {
577 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
586 // No mark as patrolled link applicable
591 * @param Revision $rev
595 protected function revisionDeleteLink( $rev ) {
596 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
597 if ( $link !== '' ) {
598 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
605 * Show the new revision of the page.
607 public function renderNewRevision() {
608 $out = $this->getOutput();
609 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
610 # Add "current version as of X" title
611 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
612 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
613 # Page content may be handled by a hooked call instead...
614 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
615 $this->loadNewText();
616 $out->setRevisionId( $this->mNewid
);
617 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
618 $out->setArticleFlag( true );
620 if ( !Hooks
::run( 'ArticleContentViewCustom',
621 [ $this->mNewContent
, $this->mNewPage
, $out ] )
623 // Handled by extension
626 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
627 // If the Title stored in the context is the same as the one
628 // of the new revision, we can use its associated WikiPage
630 $wikiPage = $this->getWikiPage();
632 // Otherwise we need to create our own WikiPage object
633 $wikiPage = WikiPage
::factory( $this->mNewPage
);
636 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
638 # WikiPage::getParserOutput() should not return false, but just in case
639 if ( $parserOutput ) {
640 // Allow extensions to change parser output here
641 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
642 [ $this, $out, $parserOutput, $wikiPage ] )
644 $out->addParserOutput( $parserOutput, [
645 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
646 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
653 // Allow extensions to optionally not show the final patrolled link
654 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
655 # Add redundant patrol link on bottom...
656 $out->addHTML( $this->markPatrolledLink() );
661 * @param WikiPage $page
662 * @param Revision $rev
664 * @return ParserOutput|bool False if the revision was not found
666 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
667 $parserOptions = $page->makeParserOptions( $this->getContext() );
668 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
670 return $parserOutput;
674 * Get the diff text, send it to the OutputPage object
675 * Returns false if the diff could not be generated, otherwise returns true
677 * @param string|bool $otitle Header for old text or false
678 * @param string|bool $ntitle Header for new text or false
679 * @param string $notice HTML between diff header and body
683 public function showDiff( $otitle, $ntitle, $notice = '' ) {
684 // Allow extensions to affect the output here
685 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
687 $diff = $this->getDiff( $otitle, $ntitle, $notice );
688 if ( $diff === false ) {
689 $this->showMissingRevision();
693 $this->showDiffStyle();
694 $this->getOutput()->addHTML( $diff );
701 * Add style sheets for diff display.
703 public function showDiffStyle() {
704 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
708 * Get complete diff table, including header
710 * @param string|bool $otitle Header for old text or false
711 * @param string|bool $ntitle Header for new text or false
712 * @param string $notice HTML between diff header and body
716 public function getDiff( $otitle, $ntitle, $notice = '' ) {
717 $body = $this->getDiffBody();
718 if ( $body === false ) {
722 $multi = $this->getMultiNotice();
723 // Display a message when the diff is empty
724 if ( $body === '' ) {
725 $notice .= '<div class="mw-diff-empty">' .
726 $this->msg( 'diff-empty' )->parse() .
730 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
734 * Get the diff table body, without header
736 * @return mixed (string/false)
738 public function getDiffBody() {
739 $this->mCacheHit
= true;
740 // Check if the diff should be hidden from this user
741 if ( !$this->loadRevisionData() ) {
743 } elseif ( $this->mOldRev
&&
744 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
747 } elseif ( $this->mNewRev
&&
748 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
753 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
754 && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
756 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
762 $cache = ObjectCache
::getMainWANInstance();
763 if ( $this->mOldid
&& $this->mNewid
) {
764 // Check if subclass is still using the old way
765 // for backwards-compatibility
766 $key = $this->getDiffBodyCacheKey();
767 if ( $key === null ) {
768 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
772 if ( !$this->mRefreshCache
) {
773 $difftext = $cache->get( $key );
775 wfIncrStats( 'diff_cache.hit' );
776 $difftext = $this->localiseDiff( $difftext );
777 $difftext .= "\n<!-- diff cache key $key -->\n";
781 } // don't try to load but save the result
783 $this->mCacheHit
= false;
785 // Loadtext is permission safe, this just clears out the diff
786 if ( !$this->loadText() ) {
790 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
792 // Avoid PHP 7.1 warning from passing $this by reference
795 // Save to cache for 7 days
796 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
797 wfIncrStats( 'diff_cache.uncacheable' );
798 } elseif ( $key !== false && $difftext !== false ) {
799 wfIncrStats( 'diff_cache.miss' );
800 $cache->set( $key, $difftext, 7 * 86400 );
802 wfIncrStats( 'diff_cache.uncacheable' );
804 // localise line numbers and title attribute text
805 if ( $difftext !== false ) {
806 $difftext = $this->localiseDiff( $difftext );
813 * Returns the cache key for diff body text or content.
815 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
818 * @throws MWException
819 * @return string|null
821 protected function getDiffBodyCacheKey() {
826 * Get the cache key parameters
828 * Subclasses can replace the first element in the array to something
829 * more specific to the type of diff (e.g. "inline-diff"), or append
830 * if the cache should vary on more things. Overriding entirely should
836 * @throws MWException
838 protected function getDiffBodyCacheKeyParams() {
839 if ( !$this->mOldid ||
!$this->mNewid
) {
840 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
843 $engine = $this->getEngine();
848 "old-{$this->mOldid}",
849 "rev-{$this->mNewid}"
852 if ( $engine === 'wikidiff2' ) {
853 $params[] = phpversion( 'wikidiff2' );
854 $params[] = $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' );
861 * Generate a diff, no caching.
863 * This implementation uses generateTextDiffBody() to generate a diff based on the default
864 * serialization of the given Content objects. This will fail if $old or $new are not
865 * instances of TextContent.
867 * Subclasses may override this to provide a different rendering for the diff,
868 * perhaps taking advantage of the content's native form. This is required for all content
869 * models that are not text based.
873 * @param Content $old Old content
874 * @param Content $new New content
876 * @throws MWException If old or new content is not an instance of TextContent.
877 * @return bool|string
879 public function generateContentDiffBody( Content
$old, Content
$new ) {
880 if ( !( $old instanceof TextContent
) ) {
881 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
882 "override generateContentDiffBody to fix this." );
885 if ( !( $new instanceof TextContent
) ) {
886 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
887 . "override generateContentDiffBody to fix this." );
890 $otext = $old->serialize();
891 $ntext = $new->serialize();
893 return $this->generateTextDiffBody( $otext, $ntext );
897 * Generate a diff, no caching
899 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
901 * @param string $otext Old text, must be already segmented
902 * @param string $ntext New text, must be already segmented
904 * @return bool|string
906 public function generateTextDiffBody( $otext, $ntext ) {
907 $diff = function () use ( $otext, $ntext ) {
908 $time = microtime( true );
910 $result = $this->textDiff( $otext, $ntext );
912 $time = intval( ( microtime( true ) - $time ) * 1000 );
913 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
914 // Log requests slower than 99th percentile
915 if ( $time > 100 && $this->mOldPage
&& $this->mNewPage
) {
917 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
924 * @param Status $status
927 $error = function ( $status ) {
928 throw new FatalError( $status->getWikiText() );
931 // Use PoolCounter if the diff looks like it can be expensive
932 if ( strlen( $otext ) +
strlen( $ntext ) > 20000 ) {
933 $work = new PoolCounterWorkViaCallback( 'diff',
934 md5( $otext ) . md5( $ntext ),
935 [ 'doWork' => $diff, 'error' => $error ]
937 return $work->execute();
944 * Process $wgExternalDiffEngine and get a sane, usable engine
946 * @return bool|string 'wikidiff2', path to an executable, or false
948 private function getEngine() {
949 global $wgExternalDiffEngine;
950 // We use the global here instead of Config because we write to the value,
951 // and Config is not mutable.
952 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
953 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
954 $wgExternalDiffEngine = false;
955 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
956 // Same as above, but with no deprecation warnings
957 $wgExternalDiffEngine = false;
958 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
959 // And prevent people from shooting themselves in the foot...
960 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
961 $wgExternalDiffEngine = false;
964 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
965 return $wgExternalDiffEngine;
966 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
975 * Generates diff, to be wrapped internally in a logging/instrumentation
977 * @param string $otext Old text, must be already segmented
978 * @param string $ntext New text, must be already segmented
979 * @return bool|string
981 protected function textDiff( $otext, $ntext ) {
984 $otext = str_replace( "\r\n", "\n", $otext );
985 $ntext = str_replace( "\r\n", "\n", $ntext );
987 $engine = $this->getEngine();
989 // Better external diff engine, the 2 may some day be dropped
990 // This one does the escaping and segmenting itself
991 if ( $engine === 'wikidiff2' ) {
992 $wikidiff2Version = phpversion( 'wikidiff2' );
994 $wikidiff2Version !== false &&
995 version_compare( $wikidiff2Version, '1.5.0', '>=' )
997 $text = wikidiff2_do_diff(
1001 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
1004 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
1005 $text = wikidiff2_do_diff(
1011 // Log a warning in case the configuration value is set to not silently ignore it
1012 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
1013 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
1014 effect since the used version of WikiDiff2 does not support it.' );
1018 $text .= $this->debug( 'wikidiff2' );
1021 } elseif ( $engine !== false ) {
1022 # Diff via the shell
1023 $tmpDir = wfTempDir();
1024 $tempName1 = tempnam( $tmpDir, 'diff_' );
1025 $tempName2 = tempnam( $tmpDir, 'diff_' );
1027 $tempFile1 = fopen( $tempName1, "w" );
1028 if ( !$tempFile1 ) {
1031 $tempFile2 = fopen( $tempName2, "w" );
1032 if ( !$tempFile2 ) {
1035 fwrite( $tempFile1, $otext );
1036 fwrite( $tempFile2, $ntext );
1037 fclose( $tempFile1 );
1038 fclose( $tempFile2 );
1039 $cmd = [ $engine, $tempName1, $tempName2 ];
1040 $result = Shell
::command( $cmd )
1042 $exitCode = $result->getExitCode();
1043 if ( $exitCode !== 0 ) {
1044 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
1045 . wfEscapeWikiText( $result->getStderr() )
1048 $difftext = $result->getStdout();
1049 $difftext .= $this->debug( "external $engine" );
1050 unlink( $tempName1 );
1051 unlink( $tempName2 );
1057 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
1058 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
1059 $diffs = new Diff( $ota, $nta );
1060 $formatter = new TableDiffFormatter();
1061 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
1062 $difftext .= $this->debug( 'native PHP' );
1068 * Generate a debug comment indicating diff generating time,
1069 * server node, and generator backend.
1071 * @param string $generator : What diff engine was used
1075 protected function debug( $generator = "internal" ) {
1076 global $wgShowHostnames;
1077 if ( !$this->enableDebugComment
) {
1080 $data = [ $generator ];
1081 if ( $wgShowHostnames ) {
1082 $data[] = wfHostname();
1084 $data[] = wfTimestamp( TS_DB
);
1086 return "<!-- diff generator: " .
1087 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1092 * Localise diff output
1094 * @param string $text
1097 private function localiseDiff( $text ) {
1098 $text = $this->localiseLineNumbers( $text );
1099 if ( $this->getEngine() === 'wikidiff2' &&
1100 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1102 $text = $this->addLocalisedTitleTooltips( $text );
1108 * Replace line numbers with the text in the user's language
1110 * @param string $text
1114 public function localiseLineNumbers( $text ) {
1115 return preg_replace_callback(
1116 '/<!--LINE (\d+)-->/',
1117 [ $this, 'localiseLineNumbersCb' ],
1122 public function localiseLineNumbersCb( $matches ) {
1123 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1127 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1131 * Add title attributes for tooltips on moved paragraph indicators
1133 * @param string $text
1136 private function addLocalisedTitleTooltips( $text ) {
1137 return preg_replace_callback(
1138 '/class="mw-diff-movedpara-(left|right)"/',
1139 [ $this, 'addLocalisedTitleTooltipsCb' ],
1145 * @param array $matches
1148 private function addLocalisedTitleTooltipsCb( array $matches ) {
1149 $key = $matches[1] === 'right' ?
1150 'diff-paragraph-moved-toold' :
1151 'diff-paragraph-moved-tonew';
1152 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1156 * If there are revisions between the ones being compared, return a note saying so.
1160 public function getMultiNotice() {
1161 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
1163 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
1164 // Comparing two different pages? Count would be meaningless.
1168 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1169 $oldRev = $this->mNewRev
; // flip
1170 $newRev = $this->mOldRev
; // flip
1171 } else { // normal case
1172 $oldRev = $this->mOldRev
;
1173 $newRev = $this->mNewRev
;
1176 // Sanity: don't show the notice if too many rows must be scanned
1177 // @todo show some special message for that case
1178 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1179 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1180 $limit = 100; // use diff-multi-manyusers if too many users
1181 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1182 $numUsers = count( $users );
1184 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1185 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1188 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1191 return ''; // nothing
1195 * Get a notice about how many intermediate edits and users there are
1197 * @param int $numEdits
1198 * @param int $numUsers
1203 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1204 if ( $numUsers === 0 ) {
1205 $msg = 'diff-multi-sameuser';
1206 } elseif ( $numUsers > $limit ) {
1207 $msg = 'diff-multi-manyusers';
1210 $msg = 'diff-multi-otherusers';
1213 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1217 * Get a header for a specified revision.
1219 * @param Revision $rev
1220 * @param string $complete 'complete' to get the header wrapped depending
1221 * the visibility of the revision and a link to edit the page.
1223 * @return string HTML fragment
1225 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1226 $lang = $this->getLanguage();
1227 $user = $this->getUser();
1228 $revtimestamp = $rev->getTimestamp();
1229 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1230 $dateofrev = $lang->userDate( $revtimestamp, $user );
1231 $timeofrev = $lang->userTime( $revtimestamp, $user );
1233 $header = $this->msg(
1234 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1240 if ( $complete !== 'complete' ) {
1244 $title = $rev->getTitle();
1246 $header = Linker
::linkKnown( $title, $header, [],
1247 [ 'oldid' => $rev->getId() ] );
1249 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1250 $editQuery = [ 'action' => 'edit' ];
1251 if ( !$rev->isCurrent() ) {
1252 $editQuery['oldid'] = $rev->getId();
1255 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1256 $msg = $this->msg( $key )->escaped();
1257 $editLink = $this->msg( 'parentheses' )->rawParams(
1258 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1259 $header .= ' ' . Html
::rawElement(
1261 [ 'class' => 'mw-diff-edit' ],
1264 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1265 $header = Html
::rawElement(
1267 [ 'class' => 'history-deleted' ],
1272 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1279 * Add the header to a diff body
1281 * @param string $diff Diff body
1282 * @param string $otitle Old revision header
1283 * @param string $ntitle New revision header
1284 * @param string $multi Notice telling user that there are intermediate
1285 * revisions between the ones being compared
1286 * @param string $notice Other notices, e.g. that user is viewing deleted content
1290 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1291 // shared.css sets diff in interface language/dir, but the actual content
1292 // is often in a different language, mostly the page content language/dir
1293 $header = Html
::openElement( 'table', [
1294 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1295 'data-mw' => 'interface',
1297 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1299 if ( !$diff && !$otitle ) {
1301 <tr class=\"diff-title\" lang=\"{$userLang}\">
1302 <td class=\"diff-ntitle\">{$ntitle}</td>
1306 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1308 <col class=\"diff-marker\" />
1309 <col class=\"diff-content\" />
1310 <col class=\"diff-marker\" />
1311 <col class=\"diff-content\" />";
1318 if ( $otitle ||
$ntitle ) {
1320 <tr class=\"diff-title\" lang=\"{$userLang}\">
1321 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1322 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1327 if ( $multi != '' ) {
1328 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1329 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1331 if ( $notice != '' ) {
1332 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1333 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1336 return $header . $diff . "</table>";
1340 * Use specified text instead of loading from the database
1341 * @param Content $oldContent
1342 * @param Content $newContent
1345 public function setContent( Content
$oldContent, Content
$newContent ) {
1346 $this->mOldContent
= $oldContent;
1347 $this->mNewContent
= $newContent;
1349 $this->mTextLoaded
= 2;
1350 $this->mRevisionsLoaded
= true;
1351 $this->isContentOverridden
= true;
1355 * Set the language in which the diff text is written
1357 * @param Language $lang
1360 public function setTextLanguage( $lang ) {
1361 if ( !$lang instanceof Language
) {
1362 wfDeprecated( __METHOD__
. ' with other type than Language for $lang', '1.32' );
1364 $this->mDiffLang
= wfGetLangObj( $lang );
1368 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1369 * to a pair of actual integers representing revision ids.
1371 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1372 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1374 * @return int[] List of two revision ids, older first, later second.
1375 * Zero signifies invalid argument passed.
1376 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1378 public function mapDiffPrevNext( $old, $new ) {
1379 if ( $new === 'prev' ) {
1380 // Show diff between revision $old and the previous one. Get previous one from DB.
1381 $newid = intval( $old );
1382 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1383 } elseif ( $new === 'next' ) {
1384 // Show diff between revision $old and the next one. Get next one from DB.
1385 $oldid = intval( $old );
1386 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1388 $oldid = intval( $old );
1389 $newid = intval( $new );
1392 return [ $oldid, $newid ];
1398 private function loadRevisionIds() {
1399 if ( $this->mRevisionsIdsLoaded
) {
1403 $this->mRevisionsIdsLoaded
= true;
1405 $old = $this->mOldid
;
1406 $new = $this->mNewid
;
1408 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1409 if ( $new === 'next' && $this->mNewid
=== false ) {
1410 # if no result, NewId points to the newest old revision. The only newer
1411 # revision is cur, which is "0".
1416 'NewDifferenceEngine',
1417 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1422 * Load revision metadata for the specified articles. If newid is 0, then compare
1423 * the old article in oldid to the current article; if oldid is 0, then
1424 * compare the current article to the immediately previous one (ignoring the
1427 * If oldid is false, leave the corresponding revision object set
1428 * to false. This is impossible via ordinary user input, and is provided for
1431 * @return bool Whether both revisions were loaded successfully.
1433 public function loadRevisionData() {
1434 if ( $this->mRevisionsLoaded
) {
1435 return $this->isContentOverridden ||
$this->mNewRev
&& $this->mOldRev
;
1438 // Whether it succeeds or fails, we don't want to try again
1439 $this->mRevisionsLoaded
= true;
1441 $this->loadRevisionIds();
1443 // Load the new revision object
1444 if ( $this->mNewid
) {
1445 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1447 $this->mNewRev
= Revision
::newFromTitle(
1450 Revision
::READ_NORMAL
1454 if ( !$this->mNewRev
instanceof Revision
) {
1458 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1459 $this->mNewid
= $this->mNewRev
->getId();
1460 $this->mNewPage
= $this->mNewRev
->getTitle();
1462 // Load the old revision object
1463 $this->mOldRev
= false;
1464 if ( $this->mOldid
) {
1465 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1466 } elseif ( $this->mOldid
=== 0 ) {
1467 $rev = $this->mNewRev
->getPrevious();
1469 $this->mOldid
= $rev->getId();
1470 $this->mOldRev
= $rev;
1472 // No previous revision; mark to show as first-version only.
1473 $this->mOldid
= false;
1474 $this->mOldRev
= false;
1476 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1478 if ( is_null( $this->mOldRev
) ) {
1482 if ( $this->mOldRev
) {
1483 $this->mOldPage
= $this->mOldRev
->getTitle();
1486 // Load tags information for both revisions
1487 $dbr = wfGetDB( DB_REPLICA
);
1488 if ( $this->mOldid
!== false ) {
1489 $this->mOldTags
= $dbr->selectField(
1492 [ 'ts_rev_id' => $this->mOldid
],
1496 $this->mOldTags
= false;
1498 $this->mNewTags
= $dbr->selectField(
1501 [ 'ts_rev_id' => $this->mNewid
],
1509 * Load the text of the revisions, as well as revision data.
1511 * @return bool Whether the content of both revisions could be loaded successfully.
1513 public function loadText() {
1514 if ( $this->mTextLoaded
== 2 ) {
1515 return $this->loadRevisionData() && $this->mOldContent
&& $this->mNewContent
;
1518 // Whether it succeeds or fails, we don't want to try again
1519 $this->mTextLoaded
= 2;
1521 if ( !$this->loadRevisionData() ) {
1525 if ( $this->mOldRev
) {
1526 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1527 if ( $this->mOldContent
=== null ) {
1532 if ( $this->mNewRev
) {
1533 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1534 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1535 if ( $this->mNewContent
=== null ) {
1544 * Load the text of the new revision, not the old one
1546 * @return bool Whether the content of the new revision could be loaded successfully.
1548 public function loadNewText() {
1549 if ( $this->mTextLoaded
>= 1 ) {
1550 return $this->loadRevisionData();
1553 $this->mTextLoaded
= 1;
1555 if ( !$this->loadRevisionData() ) {
1559 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1561 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );