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 // Same as above, but with no deprecation warnings
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 ) {
997 $otext = str_replace( "\r\n", "\n", $otext );
998 $ntext = str_replace( "\r\n", "\n", $ntext );
1000 $engine = $this->getEngine();
1002 // Better external diff engine, the 2 may some day be dropped
1003 // This one does the escaping and segmenting itself
1004 if ( $engine === 'wikidiff2' ) {
1005 $wikidiff2Version = phpversion( 'wikidiff2' );
1007 $wikidiff2Version !== false &&
1008 version_compare( $wikidiff2Version, '1.5.0', '>=' )
1010 $text = wikidiff2_do_diff(
1014 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
1017 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
1018 $text = wikidiff2_do_diff(
1024 // Log a warning in case the configuration value is set to not silently ignore it
1025 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
1026 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
1027 effect since the used version of WikiDiff2 does not support it.' );
1031 $text .= $this->debug( 'wikidiff2' );
1034 } elseif ( $engine !== false ) {
1035 # Diff via the shell
1036 $tmpDir = wfTempDir();
1037 $tempName1 = tempnam( $tmpDir, 'diff_' );
1038 $tempName2 = tempnam( $tmpDir, 'diff_' );
1040 $tempFile1 = fopen( $tempName1, "w" );
1041 if ( !$tempFile1 ) {
1044 $tempFile2 = fopen( $tempName2, "w" );
1045 if ( !$tempFile2 ) {
1048 fwrite( $tempFile1, $otext );
1049 fwrite( $tempFile2, $ntext );
1050 fclose( $tempFile1 );
1051 fclose( $tempFile2 );
1052 $cmd = [ $engine, $tempName1, $tempName2 ];
1053 $result = Shell
::command( $cmd )
1055 $exitCode = $result->getExitCode();
1056 if ( $exitCode !== 0 ) {
1057 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
1058 . wfEscapeWikiText( $result->getStderr() )
1061 $difftext = $result->getStdout();
1062 $difftext .= $this->debug( "external $engine" );
1063 unlink( $tempName1 );
1064 unlink( $tempName2 );
1070 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
1071 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
1072 $diffs = new Diff( $ota, $nta );
1073 $formatter = new TableDiffFormatter();
1074 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
1075 $difftext .= $this->debug( 'native PHP' );
1081 * Generate a debug comment indicating diff generating time,
1082 * server node, and generator backend.
1084 * @param string $generator : What diff engine was used
1088 protected function debug( $generator = "internal" ) {
1089 global $wgShowHostnames;
1090 if ( !$this->enableDebugComment
) {
1093 $data = [ $generator ];
1094 if ( $wgShowHostnames ) {
1095 $data[] = wfHostname();
1097 $data[] = wfTimestamp( TS_DB
);
1099 return "<!-- diff generator: " .
1100 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1105 * Localise diff output
1107 * @param string $text
1110 private function localiseDiff( $text ) {
1111 $text = $this->localiseLineNumbers( $text );
1112 if ( $this->getEngine() === 'wikidiff2' &&
1113 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1115 $text = $this->addLocalisedTitleTooltips( $text );
1121 * Replace line numbers with the text in the user's language
1123 * @param string $text
1127 public function localiseLineNumbers( $text ) {
1128 return preg_replace_callback(
1129 '/<!--LINE (\d+)-->/',
1130 [ $this, 'localiseLineNumbersCb' ],
1135 public function localiseLineNumbersCb( $matches ) {
1136 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1140 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1144 * Add title attributes for tooltips on moved paragraph indicators
1146 * @param string $text
1149 private function addLocalisedTitleTooltips( $text ) {
1150 return preg_replace_callback(
1151 '/class="mw-diff-movedpara-(left|right)"/',
1152 [ $this, 'addLocalisedTitleTooltipsCb' ],
1158 * @param array $matches
1161 private function addLocalisedTitleTooltipsCb( array $matches ) {
1162 $key = $matches[1] === 'right' ?
1163 'diff-paragraph-moved-toold' :
1164 'diff-paragraph-moved-tonew';
1165 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1169 * If there are revisions between the ones being compared, return a note saying so.
1173 public function getMultiNotice() {
1174 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
1176 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
1177 // Comparing two different pages? Count would be meaningless.
1181 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1182 $oldRev = $this->mNewRev
; // flip
1183 $newRev = $this->mOldRev
; // flip
1184 } else { // normal case
1185 $oldRev = $this->mOldRev
;
1186 $newRev = $this->mNewRev
;
1189 // Sanity: don't show the notice if too many rows must be scanned
1190 // @todo show some special message for that case
1191 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1192 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1193 $limit = 100; // use diff-multi-manyusers if too many users
1194 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1195 $numUsers = count( $users );
1197 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1198 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1201 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1204 return ''; // nothing
1208 * Get a notice about how many intermediate edits and users there are
1210 * @param int $numEdits
1211 * @param int $numUsers
1216 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1217 if ( $numUsers === 0 ) {
1218 $msg = 'diff-multi-sameuser';
1219 } elseif ( $numUsers > $limit ) {
1220 $msg = 'diff-multi-manyusers';
1223 $msg = 'diff-multi-otherusers';
1226 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1230 * Get a header for a specified revision.
1232 * @param Revision $rev
1233 * @param string $complete 'complete' to get the header wrapped depending
1234 * the visibility of the revision and a link to edit the page.
1236 * @return string HTML fragment
1238 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1239 $lang = $this->getLanguage();
1240 $user = $this->getUser();
1241 $revtimestamp = $rev->getTimestamp();
1242 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1243 $dateofrev = $lang->userDate( $revtimestamp, $user );
1244 $timeofrev = $lang->userTime( $revtimestamp, $user );
1246 $header = $this->msg(
1247 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1253 if ( $complete !== 'complete' ) {
1257 $title = $rev->getTitle();
1259 $header = Linker
::linkKnown( $title, $header, [],
1260 [ 'oldid' => $rev->getId() ] );
1262 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1263 $editQuery = [ 'action' => 'edit' ];
1264 if ( !$rev->isCurrent() ) {
1265 $editQuery['oldid'] = $rev->getId();
1268 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1269 $msg = $this->msg( $key )->escaped();
1270 $editLink = $this->msg( 'parentheses' )->rawParams(
1271 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1272 $header .= ' ' . Html
::rawElement(
1274 [ 'class' => 'mw-diff-edit' ],
1277 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1278 $header = Html
::rawElement(
1280 [ 'class' => 'history-deleted' ],
1285 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1292 * Add the header to a diff body
1294 * @param string $diff Diff body
1295 * @param string $otitle Old revision header
1296 * @param string $ntitle New revision header
1297 * @param string $multi Notice telling user that there are intermediate
1298 * revisions between the ones being compared
1299 * @param string $notice Other notices, e.g. that user is viewing deleted content
1303 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1304 // shared.css sets diff in interface language/dir, but the actual content
1305 // is often in a different language, mostly the page content language/dir
1306 $header = Html
::openElement( 'table', [
1307 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1308 'data-mw' => 'interface',
1310 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1312 if ( !$diff && !$otitle ) {
1314 <tr class=\"diff-title\" lang=\"{$userLang}\">
1315 <td class=\"diff-ntitle\">{$ntitle}</td>
1319 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1321 <col class=\"diff-marker\" />
1322 <col class=\"diff-content\" />
1323 <col class=\"diff-marker\" />
1324 <col class=\"diff-content\" />";
1331 if ( $otitle ||
$ntitle ) {
1333 <tr class=\"diff-title\" lang=\"{$userLang}\">
1334 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1335 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1340 if ( $multi != '' ) {
1341 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1342 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1344 if ( $notice != '' ) {
1345 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1346 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1349 return $header . $diff . "</table>";
1353 * Use specified text instead of loading from the database
1354 * @param Content $oldContent
1355 * @param Content $newContent
1358 public function setContent( Content
$oldContent, Content
$newContent ) {
1359 $this->mOldContent
= $oldContent;
1360 $this->mNewContent
= $newContent;
1362 $this->mTextLoaded
= 2;
1363 $this->mRevisionsLoaded
= true;
1364 $this->isContentOverridden
= true;
1368 * Set the language in which the diff text is written
1370 * @param Language $lang
1373 public function setTextLanguage( $lang ) {
1374 if ( !$lang instanceof Language
) {
1375 wfDeprecated( __METHOD__
. ' with other type than Language for $lang', '1.32' );
1377 $this->mDiffLang
= wfGetLangObj( $lang );
1381 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1382 * to a pair of actual integers representing revision ids.
1384 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1385 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1387 * @return int[] List of two revision ids, older first, later second.
1388 * Zero signifies invalid argument passed.
1389 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1391 public function mapDiffPrevNext( $old, $new ) {
1392 if ( $new === 'prev' ) {
1393 // Show diff between revision $old and the previous one. Get previous one from DB.
1394 $newid = intval( $old );
1395 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1396 } elseif ( $new === 'next' ) {
1397 // Show diff between revision $old and the next one. Get next one from DB.
1398 $oldid = intval( $old );
1399 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1401 $oldid = intval( $old );
1402 $newid = intval( $new );
1405 return [ $oldid, $newid ];
1411 private function loadRevisionIds() {
1412 if ( $this->mRevisionsIdsLoaded
) {
1416 $this->mRevisionsIdsLoaded
= true;
1418 $old = $this->mOldid
;
1419 $new = $this->mNewid
;
1421 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1422 if ( $new === 'next' && $this->mNewid
=== false ) {
1423 # if no result, NewId points to the newest old revision. The only newer
1424 # revision is cur, which is "0".
1429 'NewDifferenceEngine',
1430 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1435 * Load revision metadata for the specified articles. If newid is 0, then compare
1436 * the old article in oldid to the current article; if oldid is 0, then
1437 * compare the current article to the immediately previous one (ignoring the
1440 * If oldid is false, leave the corresponding revision object set
1441 * to false. This is impossible via ordinary user input, and is provided for
1444 * @return bool Whether both revisions were loaded successfully.
1446 public function loadRevisionData() {
1447 if ( $this->mRevisionsLoaded
) {
1448 return $this->isContentOverridden ||
$this->mNewRev
&& $this->mOldRev
;
1451 // Whether it succeeds or fails, we don't want to try again
1452 $this->mRevisionsLoaded
= true;
1454 $this->loadRevisionIds();
1456 // Load the new revision object
1457 if ( $this->mNewid
) {
1458 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1460 $this->mNewRev
= Revision
::newFromTitle(
1463 Revision
::READ_NORMAL
1467 if ( !$this->mNewRev
instanceof Revision
) {
1471 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1472 $this->mNewid
= $this->mNewRev
->getId();
1473 $this->mNewPage
= $this->mNewRev
->getTitle();
1475 // Load the old revision object
1476 $this->mOldRev
= false;
1477 if ( $this->mOldid
) {
1478 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1479 } elseif ( $this->mOldid
=== 0 ) {
1480 $rev = $this->mNewRev
->getPrevious();
1482 $this->mOldid
= $rev->getId();
1483 $this->mOldRev
= $rev;
1485 // No previous revision; mark to show as first-version only.
1486 $this->mOldid
= false;
1487 $this->mOldRev
= false;
1489 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1491 if ( is_null( $this->mOldRev
) ) {
1495 if ( $this->mOldRev
) {
1496 $this->mOldPage
= $this->mOldRev
->getTitle();
1499 // Load tags information for both revisions
1500 $dbr = wfGetDB( DB_REPLICA
);
1501 if ( $this->mOldid
!== false ) {
1502 $this->mOldTags
= $dbr->selectField(
1505 [ 'ts_rev_id' => $this->mOldid
],
1509 $this->mOldTags
= false;
1511 $this->mNewTags
= $dbr->selectField(
1514 [ 'ts_rev_id' => $this->mNewid
],
1522 * Load the text of the revisions, as well as revision data.
1524 * @return bool Whether the content of both revisions could be loaded successfully.
1526 public function loadText() {
1527 if ( $this->mTextLoaded
== 2 ) {
1528 return $this->loadRevisionData() && $this->mOldContent
&& $this->mNewContent
;
1531 // Whether it succeeds or fails, we don't want to try again
1532 $this->mTextLoaded
= 2;
1534 if ( !$this->loadRevisionData() ) {
1538 if ( $this->mOldRev
) {
1539 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1540 if ( $this->mOldContent
=== null ) {
1545 if ( $this->mNewRev
) {
1546 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1547 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1548 if ( $this->mNewContent
=== null ) {
1557 * Load the text of the new revision, not the old one
1559 * @return bool Whether the content of the new revision could be loaded successfully.
1561 public function loadNewText() {
1562 if ( $this->mTextLoaded
>= 1 ) {
1563 return $this->loadRevisionData();
1566 $this->mTextLoaded
= 1;
1568 if ( !$this->loadRevisionData() ) {
1572 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1574 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );