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 use DeprecationHelper
;
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
= '1.12';
42 /** @var int Revision ID or 0 for current */
45 /** @var int|string Revision ID or null for current or an alias such as 'next' */
51 /** @var Content|null */
52 protected $mOldContent;
54 /** @var Content|null */
55 protected $mNewContent;
66 /** @var Revision|null */
69 /** @var Revision|null */
72 /** @var bool Have the revisions IDs been loaded */
73 private $mRevisionsIdsLoaded = false;
75 /** @var bool Have the revisions been loaded */
76 protected $mRevisionsLoaded = false;
78 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
79 protected $mTextLoaded = 0;
82 * Was the content overridden via setContent()?
83 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored.
86 protected $isContentOverridden = false;
88 /** @var bool Was the diff fetched from cache? */
89 protected $mCacheHit = false;
92 * Set this to true to add debug info to the HTML output.
93 * Warning: this may cause RSS readers to spuriously mark articles as "new"
96 public $enableDebugComment = false;
98 /** @var bool If true, line X is not displayed when X is 1, for example
99 * to increase readability and conserve space with many small diffs.
101 protected $mReducedLineNumbers = false;
103 /** @var string Link to action=markpatrolled */
104 protected $mMarkPatrolledLink = null;
106 /** @var bool Show rev_deleted content if allowed */
107 protected $unhide = false;
109 /** @var bool Refresh the diff cache */
110 protected $mRefreshCache = false;
115 * @param IContextSource|null $context Context to use, anything else will be ignored
116 * @param int $old Old ID we want to show and diff with.
117 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
118 * @param int $rcid Deprecated, no longer used!
119 * @param bool $refreshCache If set, refreshes the diff cache
120 * @param bool $unhide If set, allow viewing deleted revs
122 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
123 $refreshCache = false, $unhide = false
125 $this->deprecatePublicProperty( 'mOldid', '1.32', __CLASS__
);
126 $this->deprecatePublicProperty( 'mNewid', '1.32', __CLASS__
);
127 $this->deprecatePublicProperty( 'mOldPage', '1.32', __CLASS__
);
128 $this->deprecatePublicProperty( 'mNewPage', '1.32', __CLASS__
);
129 $this->deprecatePublicProperty( 'mOldContent', '1.32', __CLASS__
);
130 $this->deprecatePublicProperty( 'mNewContent', '1.32', __CLASS__
);
131 $this->deprecatePublicProperty( 'mRevisionsLoaded', '1.32', __CLASS__
);
132 $this->deprecatePublicProperty( 'mTextLoaded', '1.32', __CLASS__
);
133 $this->deprecatePublicProperty( 'mCacheHit', '1.32', __CLASS__
);
135 if ( $context instanceof IContextSource
) {
136 $this->setContext( $context );
139 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
141 $this->mOldid
= $old;
142 $this->mNewid
= $new;
143 $this->mRefreshCache
= $refreshCache;
144 $this->unhide
= $unhide;
150 public function setReducedLineNumbers( $value = true ) {
151 $this->mReducedLineNumbers
= $value;
155 * Get the language of the difference engine, defaults to page content language
159 public function getDiffLang() {
160 if ( $this->mDiffLang
=== null ) {
161 # Default language in which the diff text is written.
162 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
165 return $this->mDiffLang
;
171 public function wasCacheHit() {
172 return $this->mCacheHit
;
178 public function getOldid() {
179 $this->loadRevisionIds();
181 return $this->mOldid
;
187 public function getNewid() {
188 $this->loadRevisionIds();
190 return $this->mNewid
;
194 * Look up a special:Undelete link to the given deleted revision id,
195 * as a workaround for being unable to load deleted diffs in currently.
197 * @param int $id Revision ID
199 * @return string|bool Link HTML or false
201 public function deletedLink( $id ) {
202 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
203 $dbr = wfGetDB( DB_REPLICA
);
204 $arQuery = Revision
::getArchiveQueryInfo();
205 $row = $dbr->selectRow(
207 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
208 [ 'ar_rev_id' => $id ],
214 $rev = Revision
::newFromArchiveRow( $row );
215 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
217 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
218 'target' => $title->getPrefixedText(),
219 'timestamp' => $rev->getTimestamp()
228 * Build a wikitext link toward a deleted revision, if viewable.
230 * @param int $id Revision ID
232 * @return string Wikitext fragment
234 public function deletedIdMarker( $id ) {
235 $link = $this->deletedLink( $id );
237 return "[$link $id]";
243 private function showMissingRevision() {
244 $out = $this->getOutput();
247 if ( $this->mOldRev
=== null ||
248 ( $this->mOldRev
&& $this->mOldContent
=== null )
250 $missing[] = $this->deletedIdMarker( $this->mOldid
);
252 if ( $this->mNewRev
=== null ||
253 ( $this->mNewRev
&& $this->mNewContent
=== null )
255 $missing[] = $this->deletedIdMarker( $this->mNewid
);
258 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
259 $msg = $this->msg( 'difference-missing-revision' )
260 ->params( $this->getLanguage()->listToText( $missing ) )
261 ->numParams( count( $missing ) )
263 $out->addHTML( $msg );
266 public function showDiffPage( $diffOnly = false ) {
267 # Allow frames except in certain special cases
268 $out = $this->getOutput();
269 $out->allowClickjacking();
270 $out->setRobotPolicy( 'noindex,nofollow' );
272 // Allow extensions to add any extra output here
273 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
275 if ( !$this->loadRevisionData() ) {
276 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
277 $this->showMissingRevision();
282 $user = $this->getUser();
283 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
284 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
285 $permErrors = wfMergeErrorArrays( $permErrors,
286 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
288 if ( count( $permErrors ) ) {
289 throw new PermissionsError( 'read', $permErrors );
295 # Carry over 'diffonly' param via navigation links
296 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
297 $query['diffonly'] = $diffOnly;
299 # Cascade unhide param in links for easy deletion browsing
300 if ( $this->unhide
) {
301 $query['unhide'] = 1;
304 # Check if one of the revisions is deleted/suppressed
305 $deleted = $suppressed = false;
306 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
310 # mOldRev is false if the difference engine is called with a "vague" query for
311 # a diff between a version V and its previous version V' AND the version V
312 # is the first version of that article. In that case, V' does not exist.
313 if ( $this->mOldRev
=== false ) {
314 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
317 // Allow extensions to change the $oldHeader variable
318 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
320 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
322 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
323 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
326 $out->setPageTitle( $this->msg( 'difference-title-multipage',
327 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
328 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
332 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
333 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
334 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
335 if ( $rollbackLink ) {
336 $out->preventClickjacking();
337 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
341 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
342 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
344 $undoLink = Html
::element( 'a', [
345 'href' => $this->mNewPage
->getLocalURL( [
347 'undoafter' => $this->mOldid
,
348 'undo' => $this->mNewid
350 'title' => Linker
::titleAttrib( 'undo' ),
352 $this->msg( 'editundo' )->text()
354 $revisionTools['mw-diff-undo'] = $undoLink;
358 # Make "previous revision link"
359 if ( $samePage && $this->mOldRev
->getPrevious() ) {
360 $prevlink = Linker
::linkKnown(
362 $this->msg( 'previousdiff' )->escaped(),
363 [ 'id' => 'differences-prevlink' ],
364 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
367 $prevlink = "\u{00A0}";
370 if ( $this->mOldRev
->isMinor() ) {
371 $oldminor = ChangesList
::flag( 'minor' );
376 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
377 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
378 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
380 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
381 '<div id="mw-diff-otitle2">' .
382 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
383 '<div id="mw-diff-otitle3">' . $oldminor .
384 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
385 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
386 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
388 // Allow extensions to change the $oldHeader variable
389 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
390 $diffOnly, $ldel, $this->unhide
] );
392 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
393 $deleted = true; // old revisions text is hidden
394 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
395 $suppressed = true; // also suppressed
399 # Check if this user can see the revisions
400 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
405 $out->addJsConfigVars( [
406 'wgDiffOldId' => $this->mOldid
,
407 'wgDiffNewId' => $this->mNewid
,
410 # Make "next revision link"
411 # Skip next link on the top revision
412 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
413 $nextlink = Linker
::linkKnown(
415 $this->msg( 'nextdiff' )->escaped(),
416 [ 'id' => 'differences-nextlink' ],
417 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
420 $nextlink = "\u{00A0}";
423 if ( $this->mNewRev
->isMinor() ) {
424 $newminor = ChangesList
::flag( 'minor' );
429 # Handle RevisionDelete links...
430 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
432 # Allow extensions to define their own revision tools
433 Hooks
::run( 'DiffRevisionTools',
434 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
435 $formattedRevisionTools = [];
436 // Put each one in parentheses (poor man's button)
437 foreach ( $revisionTools as $key => $tool ) {
438 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
439 $element = Html
::rawElement(
441 [ 'class' => $toolClass ],
442 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
444 $formattedRevisionTools[] = $element;
446 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
447 ' ' . implode( ' ', $formattedRevisionTools );
448 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
450 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
451 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
453 '<div id="mw-diff-ntitle3">' . $newminor .
454 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
455 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
456 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
458 // Allow extensions to change the $newHeader variable
459 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
460 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
462 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
463 $deleted = true; // new revisions text is hidden
464 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
465 $suppressed = true; // also suppressed
469 # If the diff cannot be shown due to a deleted revision, then output
470 # the diff header and links to unhide (if available)...
471 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
472 $this->showDiffStyle();
473 $multi = $this->getMultiNotice();
474 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
476 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
477 # Give explanation for why revision is not visible
478 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
481 # Give explanation and add a link to view the diff...
482 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
483 $link = $this->getTitle()->getFullURL( $query );
484 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
486 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
490 # Otherwise, output a regular diff...
492 # Add deletion notice if the user is viewing deleted content
495 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
496 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
497 $this->msg( $msg )->parse() .
500 $this->showDiff( $oldHeader, $newHeader, $notice );
502 $this->renderNewRevision();
508 * Build a link to mark a change as patrolled.
510 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
511 * Side effect: When the patrol link is build, this method will call
512 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
514 * @return string HTML or empty string
516 public function markPatrolledLink() {
517 if ( $this->mMarkPatrolledLink
=== null ) {
518 $linkInfo = $this->getMarkPatrolledLinkInfo();
519 // If false, there is no patrol link needed/allowed
521 $this->mMarkPatrolledLink
= '';
523 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
526 $this->msg( 'markaspatrolleddiff' )->escaped(),
529 'action' => 'markpatrolled',
530 'rcid' => $linkInfo['rcid'],
533 // Allow extensions to change the markpatrolled link
534 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
535 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
538 return $this->mMarkPatrolledLink
;
542 * Returns an array of meta data needed to build a "mark as patrolled" link and
543 * adds the mediawiki.page.patrol.ajax to the output.
545 * @return array|false An array of meta data for a patrol link (rcid only)
546 * or false if no link is needed
548 protected function getMarkPatrolledLinkInfo() {
549 global $wgUseRCPatrol;
551 $user = $this->getUser();
553 // Prepare a change patrol link, if applicable
555 // Is patrolling enabled and the user allowed to?
556 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
557 // Only do this if the revision isn't more than 6 hours older
558 // than the Max RC age (6h because the RC might not be cleaned out regularly)
559 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
561 // Look for an unpatrolled change corresponding to this diff
562 $db = wfGetDB( DB_REPLICA
);
563 $change = RecentChange
::newFromConds(
565 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
566 'rc_this_oldid' => $this->mNewid
,
567 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
572 if ( $change && !$change->getPerformer()->equals( $user ) ) {
573 $rcid = $change->getAttribute( 'rc_id' );
575 // None found or the page has been created by the current user.
576 // If the user could patrol this it already would be patrolled
580 // Allow extensions to possibly change the rcid here
581 // For example the rcid might be set to zero due to the user
582 // being the same as the performer of the change but an extension
583 // might still want to show it under certain conditions
584 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
588 $this->getOutput()->preventClickjacking();
589 if ( $user->isAllowed( 'writeapi' ) ) {
590 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
599 // No mark as patrolled link applicable
604 * @param Revision $rev
608 protected function revisionDeleteLink( $rev ) {
609 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
610 if ( $link !== '' ) {
611 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
618 * Show the new revision of the page.
620 public function renderNewRevision() {
621 $out = $this->getOutput();
622 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
623 # Add "current version as of X" title
624 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
625 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
626 # Page content may be handled by a hooked call instead...
627 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
628 $this->loadNewText();
629 $out->setRevisionId( $this->mNewid
);
630 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
631 $out->setArticleFlag( true );
633 if ( !Hooks
::run( 'ArticleContentViewCustom',
634 [ $this->mNewContent
, $this->mNewPage
, $out ] )
636 // Handled by extension
639 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
640 // If the Title stored in the context is the same as the one
641 // of the new revision, we can use its associated WikiPage
643 $wikiPage = $this->getWikiPage();
645 // Otherwise we need to create our own WikiPage object
646 $wikiPage = WikiPage
::factory( $this->mNewPage
);
649 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
651 # WikiPage::getParserOutput() should not return false, but just in case
652 if ( $parserOutput ) {
653 // Allow extensions to change parser output here
654 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
655 [ $this, $out, $parserOutput, $wikiPage ] )
657 $out->addParserOutput( $parserOutput, [
658 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
659 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
666 // Allow extensions to optionally not show the final patrolled link
667 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
668 # Add redundant patrol link on bottom...
669 $out->addHTML( $this->markPatrolledLink() );
674 * @param WikiPage $page
675 * @param Revision $rev
677 * @return ParserOutput|bool False if the revision was not found
679 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
680 $parserOptions = $page->makeParserOptions( $this->getContext() );
681 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
683 return $parserOutput;
687 * Get the diff text, send it to the OutputPage object
688 * Returns false if the diff could not be generated, otherwise returns true
690 * @param string|bool $otitle Header for old text or false
691 * @param string|bool $ntitle Header for new text or false
692 * @param string $notice HTML between diff header and body
696 public function showDiff( $otitle, $ntitle, $notice = '' ) {
697 // Allow extensions to affect the output here
698 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
700 $diff = $this->getDiff( $otitle, $ntitle, $notice );
701 if ( $diff === false ) {
702 $this->showMissingRevision();
706 $this->showDiffStyle();
707 $this->getOutput()->addHTML( $diff );
714 * Add style sheets for diff display.
716 public function showDiffStyle() {
717 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
721 * Get complete diff table, including header
723 * @param string|bool $otitle Header for old text or false
724 * @param string|bool $ntitle Header for new text or false
725 * @param string $notice HTML between diff header and body
729 public function getDiff( $otitle, $ntitle, $notice = '' ) {
730 $body = $this->getDiffBody();
731 if ( $body === false ) {
735 $multi = $this->getMultiNotice();
736 // Display a message when the diff is empty
737 if ( $body === '' ) {
738 $notice .= '<div class="mw-diff-empty">' .
739 $this->msg( 'diff-empty' )->parse() .
743 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
747 * Get the diff table body, without header
749 * @return mixed (string/false)
751 public function getDiffBody() {
752 $this->mCacheHit
= true;
753 // Check if the diff should be hidden from this user
754 if ( !$this->loadRevisionData() ) {
756 } elseif ( $this->mOldRev
&&
757 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
760 } elseif ( $this->mNewRev
&&
761 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
766 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
767 && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
769 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
775 $cache = ObjectCache
::getMainWANInstance();
776 if ( $this->mOldid
&& $this->mNewid
) {
777 // Check if subclass is still using the old way
778 // for backwards-compatibility
779 $key = $this->getDiffBodyCacheKey();
780 if ( $key === null ) {
781 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
785 if ( !$this->mRefreshCache
) {
786 $difftext = $cache->get( $key );
788 wfIncrStats( 'diff_cache.hit' );
789 $difftext = $this->localiseDiff( $difftext );
790 $difftext .= "\n<!-- diff cache key $key -->\n";
794 } // don't try to load but save the result
796 $this->mCacheHit
= false;
798 // Loadtext is permission safe, this just clears out the diff
799 if ( !$this->loadText() ) {
803 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
805 // Avoid PHP 7.1 warning from passing $this by reference
808 // Save to cache for 7 days
809 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
810 wfIncrStats( 'diff_cache.uncacheable' );
811 } elseif ( $key !== false && $difftext !== false ) {
812 wfIncrStats( 'diff_cache.miss' );
813 $cache->set( $key, $difftext, 7 * 86400 );
815 wfIncrStats( 'diff_cache.uncacheable' );
817 // localise line numbers and title attribute text
818 if ( $difftext !== false ) {
819 $difftext = $this->localiseDiff( $difftext );
826 * Returns the cache key for diff body text or content.
828 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
831 * @throws MWException
832 * @return string|null
834 protected function getDiffBodyCacheKey() {
839 * Get the cache key parameters
841 * Subclasses can replace the first element in the array to something
842 * more specific to the type of diff (e.g. "inline-diff"), or append
843 * if the cache should vary on more things. Overriding entirely should
849 * @throws MWException
851 protected function getDiffBodyCacheKeyParams() {
852 if ( !$this->mOldid ||
!$this->mNewid
) {
853 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
856 $engine = $this->getEngine();
861 "old-{$this->mOldid}",
862 "rev-{$this->mNewid}"
865 if ( $engine === 'wikidiff2' ) {
866 $params[] = phpversion( 'wikidiff2' );
867 $params[] = $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' );
874 * Generate a diff, no caching.
876 * This implementation uses generateTextDiffBody() to generate a diff based on the default
877 * serialization of the given Content objects. This will fail if $old or $new are not
878 * instances of TextContent.
880 * Subclasses may override this to provide a different rendering for the diff,
881 * perhaps taking advantage of the content's native form. This is required for all content
882 * models that are not text based.
886 * @param Content $old Old content
887 * @param Content $new New content
889 * @throws MWException If old or new content is not an instance of TextContent.
890 * @return bool|string
892 public function generateContentDiffBody( Content
$old, Content
$new ) {
893 if ( !( $old instanceof TextContent
) ) {
894 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
895 "override generateContentDiffBody to fix this." );
898 if ( !( $new instanceof TextContent
) ) {
899 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
900 . "override generateContentDiffBody to fix this." );
903 $otext = $old->serialize();
904 $ntext = $new->serialize();
906 return $this->generateTextDiffBody( $otext, $ntext );
910 * Generate a diff, no caching
912 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
914 * @param string $otext Old text, must be already segmented
915 * @param string $ntext New text, must be already segmented
917 * @return bool|string
919 public function generateTextDiffBody( $otext, $ntext ) {
920 $diff = function () use ( $otext, $ntext ) {
921 $time = microtime( true );
923 $result = $this->textDiff( $otext, $ntext );
925 $time = intval( ( microtime( true ) - $time ) * 1000 );
926 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
927 // Log requests slower than 99th percentile
928 if ( $time > 100 && $this->mOldPage
&& $this->mNewPage
) {
930 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
937 * @param Status $status
940 $error = function ( $status ) {
941 throw new FatalError( $status->getWikiText() );
944 // Use PoolCounter if the diff looks like it can be expensive
945 if ( strlen( $otext ) +
strlen( $ntext ) > 20000 ) {
946 $work = new PoolCounterWorkViaCallback( 'diff',
947 md5( $otext ) . md5( $ntext ),
948 [ 'doWork' => $diff, 'error' => $error ]
950 return $work->execute();
957 * Process $wgExternalDiffEngine and get a sane, usable engine
959 * @return bool|string 'wikidiff2', path to an executable, or false
961 private function getEngine() {
962 global $wgExternalDiffEngine;
963 // We use the global here instead of Config because we write to the value,
964 // and Config is not mutable.
965 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
966 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
967 $wgExternalDiffEngine = false;
968 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
969 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
970 $wgExternalDiffEngine = false;
971 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
972 // And prevent people from shooting themselves in the foot...
973 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
974 $wgExternalDiffEngine = false;
977 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
978 return $wgExternalDiffEngine;
979 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
988 * Generates diff, to be wrapped internally in a logging/instrumentation
990 * @param string $otext Old text, must be already segmented
991 * @param string $ntext New text, must be already segmented
992 * @return bool|string
994 protected function textDiff( $otext, $ntext ) {
995 $otext = str_replace( "\r\n", "\n", $otext );
996 $ntext = str_replace( "\r\n", "\n", $ntext );
998 $engine = $this->getEngine();
1000 // Better external diff engine, the 2 may some day be dropped
1001 // This one does the escaping and segmenting itself
1002 if ( $engine === 'wikidiff2' ) {
1003 $wikidiff2Version = phpversion( 'wikidiff2' );
1005 $wikidiff2Version !== false &&
1006 version_compare( $wikidiff2Version, '1.5.0', '>=' )
1008 $text = wikidiff2_do_diff(
1012 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
1015 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
1016 $text = wikidiff2_do_diff(
1022 // Log a warning in case the configuration value is set to not silently ignore it
1023 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
1024 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
1025 effect since the used version of WikiDiff2 does not support it.' );
1029 $text .= $this->debug( 'wikidiff2' );
1032 } elseif ( $engine !== false ) {
1033 # Diff via the shell
1034 $tmpDir = wfTempDir();
1035 $tempName1 = tempnam( $tmpDir, 'diff_' );
1036 $tempName2 = tempnam( $tmpDir, 'diff_' );
1038 $tempFile1 = fopen( $tempName1, "w" );
1039 if ( !$tempFile1 ) {
1042 $tempFile2 = fopen( $tempName2, "w" );
1043 if ( !$tempFile2 ) {
1046 fwrite( $tempFile1, $otext );
1047 fwrite( $tempFile2, $ntext );
1048 fclose( $tempFile1 );
1049 fclose( $tempFile2 );
1050 $cmd = [ $engine, $tempName1, $tempName2 ];
1051 $result = Shell
::command( $cmd )
1053 $exitCode = $result->getExitCode();
1054 if ( $exitCode !== 0 ) {
1055 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
1056 . wfEscapeWikiText( $result->getStderr() )
1059 $difftext = $result->getStdout();
1060 $difftext .= $this->debug( "external $engine" );
1061 unlink( $tempName1 );
1062 unlink( $tempName2 );
1068 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1069 $ota = explode( "\n", $contLang->segmentForDiff( $otext ) );
1070 $nta = explode( "\n", $contLang->segmentForDiff( $ntext ) );
1071 $diffs = new Diff( $ota, $nta );
1072 $formatter = new TableDiffFormatter();
1073 $difftext = $contLang->unsegmentForDiff( $formatter->format( $diffs ) );
1074 $difftext .= $this->debug( 'native PHP' );
1080 * Generate a debug comment indicating diff generating time,
1081 * server node, and generator backend.
1083 * @param string $generator : What diff engine was used
1087 protected function debug( $generator = "internal" ) {
1088 global $wgShowHostnames;
1089 if ( !$this->enableDebugComment
) {
1092 $data = [ $generator ];
1093 if ( $wgShowHostnames ) {
1094 $data[] = wfHostname();
1096 $data[] = wfTimestamp( TS_DB
);
1098 return "<!-- diff generator: " .
1099 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1104 * Localise diff output
1106 * @param string $text
1109 private function localiseDiff( $text ) {
1110 $text = $this->localiseLineNumbers( $text );
1111 if ( $this->getEngine() === 'wikidiff2' &&
1112 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1114 $text = $this->addLocalisedTitleTooltips( $text );
1120 * Replace line numbers with the text in the user's language
1122 * @param string $text
1126 public function localiseLineNumbers( $text ) {
1127 return preg_replace_callback(
1128 '/<!--LINE (\d+)-->/',
1129 [ $this, 'localiseLineNumbersCb' ],
1134 public function localiseLineNumbersCb( $matches ) {
1135 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1139 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1143 * Add title attributes for tooltips on moved paragraph indicators
1145 * @param string $text
1148 private function addLocalisedTitleTooltips( $text ) {
1149 return preg_replace_callback(
1150 '/class="mw-diff-movedpara-(left|right)"/',
1151 [ $this, 'addLocalisedTitleTooltipsCb' ],
1157 * @param array $matches
1160 private function addLocalisedTitleTooltipsCb( array $matches ) {
1161 $key = $matches[1] === 'right' ?
1162 'diff-paragraph-moved-toold' :
1163 'diff-paragraph-moved-tonew';
1164 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1168 * If there are revisions between the ones being compared, return a note saying so.
1172 public function getMultiNotice() {
1173 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
1175 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
1176 // Comparing two different pages? Count would be meaningless.
1180 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1181 $oldRev = $this->mNewRev
; // flip
1182 $newRev = $this->mOldRev
; // flip
1183 } else { // normal case
1184 $oldRev = $this->mOldRev
;
1185 $newRev = $this->mNewRev
;
1188 // Sanity: don't show the notice if too many rows must be scanned
1189 // @todo show some special message for that case
1190 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1191 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1192 $limit = 100; // use diff-multi-manyusers if too many users
1193 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1194 $numUsers = count( $users );
1196 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1197 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1200 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1203 return ''; // nothing
1207 * Get a notice about how many intermediate edits and users there are
1209 * @param int $numEdits
1210 * @param int $numUsers
1215 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1216 if ( $numUsers === 0 ) {
1217 $msg = 'diff-multi-sameuser';
1218 } elseif ( $numUsers > $limit ) {
1219 $msg = 'diff-multi-manyusers';
1222 $msg = 'diff-multi-otherusers';
1225 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1229 * Get a header for a specified revision.
1231 * @param Revision $rev
1232 * @param string $complete 'complete' to get the header wrapped depending
1233 * the visibility of the revision and a link to edit the page.
1235 * @return string HTML fragment
1237 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1238 $lang = $this->getLanguage();
1239 $user = $this->getUser();
1240 $revtimestamp = $rev->getTimestamp();
1241 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1242 $dateofrev = $lang->userDate( $revtimestamp, $user );
1243 $timeofrev = $lang->userTime( $revtimestamp, $user );
1245 $header = $this->msg(
1246 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1252 if ( $complete !== 'complete' ) {
1256 $title = $rev->getTitle();
1258 $header = Linker
::linkKnown( $title, $header, [],
1259 [ 'oldid' => $rev->getId() ] );
1261 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1262 $editQuery = [ 'action' => 'edit' ];
1263 if ( !$rev->isCurrent() ) {
1264 $editQuery['oldid'] = $rev->getId();
1267 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1268 $msg = $this->msg( $key )->escaped();
1269 $editLink = $this->msg( 'parentheses' )->rawParams(
1270 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1271 $header .= ' ' . Html
::rawElement(
1273 [ 'class' => 'mw-diff-edit' ],
1276 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1277 $header = Html
::rawElement(
1279 [ 'class' => 'history-deleted' ],
1284 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1291 * Add the header to a diff body
1293 * @param string $diff Diff body
1294 * @param string $otitle Old revision header
1295 * @param string $ntitle New revision header
1296 * @param string $multi Notice telling user that there are intermediate
1297 * revisions between the ones being compared
1298 * @param string $notice Other notices, e.g. that user is viewing deleted content
1302 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1303 // shared.css sets diff in interface language/dir, but the actual content
1304 // is often in a different language, mostly the page content language/dir
1305 $header = Html
::openElement( 'table', [
1306 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1307 'data-mw' => 'interface',
1309 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1311 if ( !$diff && !$otitle ) {
1313 <tr class=\"diff-title\" lang=\"{$userLang}\">
1314 <td class=\"diff-ntitle\">{$ntitle}</td>
1318 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1320 <col class=\"diff-marker\" />
1321 <col class=\"diff-content\" />
1322 <col class=\"diff-marker\" />
1323 <col class=\"diff-content\" />";
1330 if ( $otitle ||
$ntitle ) {
1332 <tr class=\"diff-title\" lang=\"{$userLang}\">
1333 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1334 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1339 if ( $multi != '' ) {
1340 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1341 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1343 if ( $notice != '' ) {
1344 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1345 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1348 return $header . $diff . "</table>";
1352 * Use specified text instead of loading from the database
1353 * @param Content $oldContent
1354 * @param Content $newContent
1357 public function setContent( Content
$oldContent, Content
$newContent ) {
1358 $this->mOldContent
= $oldContent;
1359 $this->mNewContent
= $newContent;
1361 $this->mTextLoaded
= 2;
1362 $this->mRevisionsLoaded
= true;
1363 $this->isContentOverridden
= true;
1367 * Set the language in which the diff text is written
1369 * @param Language $lang
1372 public function setTextLanguage( $lang ) {
1373 if ( !$lang instanceof Language
) {
1374 wfDeprecated( __METHOD__
. ' with other type than Language for $lang', '1.32' );
1376 $this->mDiffLang
= wfGetLangObj( $lang );
1380 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1381 * to a pair of actual integers representing revision ids.
1383 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1384 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1386 * @return int[] List of two revision ids, older first, later second.
1387 * Zero signifies invalid argument passed.
1388 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1390 public function mapDiffPrevNext( $old, $new ) {
1391 if ( $new === 'prev' ) {
1392 // Show diff between revision $old and the previous one. Get previous one from DB.
1393 $newid = intval( $old );
1394 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1395 } elseif ( $new === 'next' ) {
1396 // Show diff between revision $old and the next one. Get next one from DB.
1397 $oldid = intval( $old );
1398 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1400 $oldid = intval( $old );
1401 $newid = intval( $new );
1404 return [ $oldid, $newid ];
1410 private function loadRevisionIds() {
1411 if ( $this->mRevisionsIdsLoaded
) {
1415 $this->mRevisionsIdsLoaded
= true;
1417 $old = $this->mOldid
;
1418 $new = $this->mNewid
;
1420 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1421 if ( $new === 'next' && $this->mNewid
=== false ) {
1422 # if no result, NewId points to the newest old revision. The only newer
1423 # revision is cur, which is "0".
1428 'NewDifferenceEngine',
1429 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1434 * Load revision metadata for the specified articles. If newid is 0, then compare
1435 * the old article in oldid to the current article; if oldid is 0, then
1436 * compare the current article to the immediately previous one (ignoring the
1439 * If oldid is false, leave the corresponding revision object set
1440 * to false. This is impossible via ordinary user input, and is provided for
1443 * @return bool Whether both revisions were loaded successfully.
1445 public function loadRevisionData() {
1446 if ( $this->mRevisionsLoaded
) {
1447 return $this->isContentOverridden ||
$this->mNewRev
&& $this->mOldRev
;
1450 // Whether it succeeds or fails, we don't want to try again
1451 $this->mRevisionsLoaded
= true;
1453 $this->loadRevisionIds();
1455 // Load the new revision object
1456 if ( $this->mNewid
) {
1457 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1459 $this->mNewRev
= Revision
::newFromTitle(
1462 Revision
::READ_NORMAL
1466 if ( !$this->mNewRev
instanceof Revision
) {
1470 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1471 $this->mNewid
= $this->mNewRev
->getId();
1472 $this->mNewPage
= $this->mNewRev
->getTitle();
1474 // Load the old revision object
1475 $this->mOldRev
= false;
1476 if ( $this->mOldid
) {
1477 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1478 } elseif ( $this->mOldid
=== 0 ) {
1479 $rev = $this->mNewRev
->getPrevious();
1481 $this->mOldid
= $rev->getId();
1482 $this->mOldRev
= $rev;
1484 // No previous revision; mark to show as first-version only.
1485 $this->mOldid
= false;
1486 $this->mOldRev
= false;
1488 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1490 if ( is_null( $this->mOldRev
) ) {
1494 if ( $this->mOldRev
) {
1495 $this->mOldPage
= $this->mOldRev
->getTitle();
1498 // Load tags information for both revisions
1499 $dbr = wfGetDB( DB_REPLICA
);
1500 if ( $this->mOldid
!== false ) {
1501 $this->mOldTags
= $dbr->selectField(
1504 [ 'ts_rev_id' => $this->mOldid
],
1508 $this->mOldTags
= false;
1510 $this->mNewTags
= $dbr->selectField(
1513 [ 'ts_rev_id' => $this->mNewid
],
1521 * Load the text of the revisions, as well as revision data.
1523 * @return bool Whether the content of both revisions could be loaded successfully.
1525 public function loadText() {
1526 if ( $this->mTextLoaded
== 2 ) {
1527 return $this->loadRevisionData() && $this->mOldContent
&& $this->mNewContent
;
1530 // Whether it succeeds or fails, we don't want to try again
1531 $this->mTextLoaded
= 2;
1533 if ( !$this->loadRevisionData() ) {
1537 if ( $this->mOldRev
) {
1538 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1539 if ( $this->mOldContent
=== null ) {
1544 if ( $this->mNewRev
) {
1545 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1546 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1547 if ( $this->mNewContent
=== null ) {
1556 * Load the text of the new revision, not the old one
1558 * @return bool Whether the content of the new revision could be loaded successfully.
1560 public function loadNewText() {
1561 if ( $this->mTextLoaded
>= 1 ) {
1562 return $this->loadRevisionData();
1565 $this->mTextLoaded
= 1;
1567 if ( !$this->loadRevisionData() ) {
1571 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1573 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );