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
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Revision\RevisionRecord
;
26 use MediaWiki\Revision\SlotRecord
;
27 use MediaWiki\Storage\NameTableAccessException
;
30 * DifferenceEngine is responsible for rendering the difference between two revisions as HTML.
31 * This includes interpreting URL parameters, retrieving revision data, checking access permissions,
32 * selecting and invoking the diff generator class for the individual slots, doing post-processing
33 * on the generated diff, adding the rest of the HTML (such as headers) and writing the whole thing
36 * DifferenceEngine can be subclassed by extensions, by customizing
37 * ContentHandler::createDifferenceEngine; the content handler will be selected based on the
38 * content model of the main slot (of the new revision, when the two are different).
39 * That might change after PageTypeHandler gets introduced.
41 * In the past, the class was also used for slot-level diff generation, and extensions might still
42 * subclass it and add such functionality. When that is the case (sepcifically, when a
43 * ContentHandler returns a standard SlotDiffRenderer but a nonstandard DifferenceEngine)
44 * DifferenceEngineSlotDiffRenderer will be used to convert the old behavior into the new one.
46 * @ingroup DifferenceEngine
48 * @todo This class is huge and poorly defined. It should be split into a controller responsible
49 * for interpreting query parameters, retrieving data and checking permissions; and a HTML renderer.
51 class DifferenceEngine
extends ContextSource
{
53 use DeprecationHelper
;
56 * Constant to indicate diff cache compatibility.
57 * Bump this when changing the diff formatting in a way that
58 * fixes important bugs or such to force cached diff views to
61 const DIFF_VERSION
= '1.12';
64 * Revision ID for the old revision. 0 for the revision previous to $mNewid, false
65 * if the diff does not have an old revision (e.g. 'oldid=<first revision of page>&diff=prev'),
66 * or the revision does not exist, null if the revision is unsaved.
72 * Revision ID for the new revision. 0 for the last revision of the current page
73 * (as defined by the request context), false if the revision does not exist, null
74 * if it is unsaved, or an alias such as 'next'.
75 * @var int|string|false|null
80 * Old revision (left pane).
81 * Allowed to be an unsaved revision, unlikely that's ever needed though.
82 * False when the old revision does not exist; this can happen when using
83 * diff=prev on the first revision. Null when the revision should exist but
84 * doesn't (e.g. load failure); loadRevisionData() will return false in that
85 * case. Also null until lazy-loaded. Ignored completely when isContentOverridden
87 * Since 1.32 public access is deprecated.
88 * @var Revision|null|false
93 * New revision (right pane).
94 * Note that this might be an unsaved revision (e.g. for edit preview).
95 * Null in case of load failure; diff methods will just return an error message in that case,
96 * and loadRevisionData() will return false. Also null until lazy-loaded. Ignored completely
97 * when isContentOverridden is set.
98 * Since 1.32 public access is deprecated.
104 * Title of $mOldRev or null if the old revision does not exist or does not belong to a page.
105 * Since 1.32 public access is deprecated and the property can be null.
111 * Title of $mNewRev or null if the new revision does not exist or does not belong to a page.
112 * Since 1.32 public access is deprecated and the property can be null.
118 * Change tags of $mOldRev or null if it does not exist / is not saved.
124 * Change tags of $mNewRev or null if it does not exist / is not saved.
131 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
132 * This property is set to the content of the main slot, but not actually used for the main diff.
134 private $mOldContent;
138 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
139 * This property is set to the content of the main slot, but not actually used for the main diff.
141 private $mNewContent;
144 protected $mDiffLang;
146 /** @var bool Have the revisions IDs been loaded */
147 private $mRevisionsIdsLoaded = false;
149 /** @var bool Have the revisions been loaded */
150 protected $mRevisionsLoaded = false;
152 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
153 protected $mTextLoaded = 0;
156 * Was the content overridden via setContent()?
157 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
158 * and only mOldContent and mNewContent is reliable.
159 * (Note that setRevisions() does not set this flag as in that case all properties are
160 * overriden and remain consistent with each other, so no special handling is needed.)
163 protected $isContentOverridden = false;
165 /** @var bool Was the diff fetched from cache? */
166 protected $mCacheHit = false;
169 * Set this to true to add debug info to the HTML output.
170 * Warning: this may cause RSS readers to spuriously mark articles as "new"
173 public $enableDebugComment = false;
175 /** @var bool If true, line X is not displayed when X is 1, for example
176 * to increase readability and conserve space with many small diffs.
178 protected $mReducedLineNumbers = false;
180 /** @var string Link to action=markpatrolled */
181 protected $mMarkPatrolledLink = null;
183 /** @var bool Show rev_deleted content if allowed */
184 protected $unhide = false;
186 /** @var bool Refresh the diff cache */
187 protected $mRefreshCache = false;
189 /** @var SlotDiffRenderer[] DifferenceEngine classes for the slots, keyed by role name. */
190 protected $slotDiffRenderers = null;
193 * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
194 * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
195 * $slotDiffRenderers should not be used.
198 protected $isSlotDiffRenderer = false;
203 * @param IContextSource|null $context Context to use, anything else will be ignored
204 * @param int $old Old ID we want to show and diff with.
205 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
206 * @param int $rcid Deprecated, no longer used!
207 * @param bool $refreshCache If set, refreshes the diff cache
208 * @param bool $unhide If set, allow viewing deleted revs
210 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
211 $refreshCache = false, $unhide = false
213 $this->deprecatePublicProperty( 'mOldid', '1.32', __CLASS__
);
214 $this->deprecatePublicProperty( 'mNewid', '1.32', __CLASS__
);
215 $this->deprecatePublicProperty( 'mOldRev', '1.32', __CLASS__
);
216 $this->deprecatePublicProperty( 'mNewRev', '1.32', __CLASS__
);
217 $this->deprecatePublicProperty( 'mOldPage', '1.32', __CLASS__
);
218 $this->deprecatePublicProperty( 'mNewPage', '1.32', __CLASS__
);
219 $this->deprecatePublicProperty( 'mOldContent', '1.32', __CLASS__
);
220 $this->deprecatePublicProperty( 'mNewContent', '1.32', __CLASS__
);
221 $this->deprecatePublicProperty( 'mRevisionsLoaded', '1.32', __CLASS__
);
222 $this->deprecatePublicProperty( 'mTextLoaded', '1.32', __CLASS__
);
223 $this->deprecatePublicProperty( 'mCacheHit', '1.32', __CLASS__
);
225 if ( $context instanceof IContextSource
) {
226 $this->setContext( $context );
229 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
231 $this->mOldid
= $old;
232 $this->mNewid
= $new;
233 $this->mRefreshCache
= $refreshCache;
234 $this->unhide
= $unhide;
238 * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
239 * Includes slots only present in one of the revisions.
241 protected function getSlotDiffRenderers() {
242 if ( $this->isSlotDiffRenderer
) {
243 throw new LogicException( __METHOD__
. ' called in slot diff renderer mode' );
246 if ( $this->slotDiffRenderers
=== null ) {
247 if ( !$this->loadRevisionData() ) {
251 $slotContents = $this->getSlotContents();
252 $this->slotDiffRenderers
= array_map( function ( $contents ) {
253 /** @var Content $content */
254 $content = $contents['new'] ?
: $contents['old'];
255 return $content->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
258 return $this->slotDiffRenderers
;
262 * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
263 * This is used in legacy mode when the DifferenceEngine is wrapped in a
264 * DifferenceEngineSlotDiffRenderer.
265 * @internal For use by DifferenceEngineSlotDiffRenderer only.
267 public function markAsSlotDiffRenderer() {
268 $this->isSlotDiffRenderer
= true;
272 * Get the old and new content objects for all slots.
273 * This method does not do any permission checks.
274 * @return array [ role => [ 'old' => SlotRecord|null, 'new' => SlotRecord|null ], ... ]
276 protected function getSlotContents() {
277 if ( $this->isContentOverridden
) {
279 SlotRecord
::MAIN
=> [
280 'old' => $this->mOldContent
,
281 'new' => $this->mNewContent
,
284 } elseif ( !$this->loadRevisionData() ) {
288 $newSlots = $this->mNewRev
->getRevisionRecord()->getSlots()->getSlots();
289 if ( $this->mOldRev
) {
290 $oldSlots = $this->mOldRev
->getRevisionRecord()->getSlots()->getSlots();
294 // The order here will determine the visual order of the diff. The current logic is
295 // slots of the new revision first in natural order, then deleted ones. This is ad hoc
296 // and should not be relied on - in the future we may want the ordering to depend
298 $roles = array_merge( array_keys( $newSlots ), array_keys( $oldSlots ) );
301 foreach ( $roles as $role ) {
303 'old' => isset( $oldSlots[$role] ) ?
$oldSlots[$role]->getContent() : null,
304 'new' => isset( $newSlots[$role] ) ?
$newSlots[$role]->getContent() : null,
307 // move main slot to front
308 if ( isset( $slots[SlotRecord
::MAIN
] ) ) {
309 $slots = [ SlotRecord
::MAIN
=> $slots[SlotRecord
::MAIN
] ] +
$slots;
314 public function getTitle() {
315 // T202454 avoid errors when there is no title
316 return parent
::getTitle() ?
: Title
::makeTitle( NS_SPECIAL
, 'BadTitle/DifferenceEngine' );
320 * Set reduced line numbers mode.
321 * When set, line X is not displayed when X is 1, for example to increase readability and
322 * conserve space with many small diffs.
325 public function setReducedLineNumbers( $value = true ) {
326 $this->mReducedLineNumbers
= $value;
330 * Get the language of the difference engine, defaults to page content language
334 public function getDiffLang() {
335 if ( $this->mDiffLang
=== null ) {
336 # Default language in which the diff text is written.
337 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
340 return $this->mDiffLang
;
346 public function wasCacheHit() {
347 return $this->mCacheHit
;
351 * Get the ID of old revision (left pane) of the diff. 0 for the revision
352 * previous to getNewid(), false if the old revision does not exist, null
354 * To get a real revision ID instead of 0, call loadRevisionData() first.
355 * @return int|false|null
357 public function getOldid() {
358 $this->loadRevisionIds();
360 return $this->mOldid
;
364 * Get the ID of new revision (right pane) of the diff. 0 for the current revision,
365 * false if the new revision does not exist, null if it's unsaved.
366 * To get a real revision ID instead of 0, call loadRevisionData() first.
367 * @return int|false|null
369 public function getNewid() {
370 $this->loadRevisionIds();
372 return $this->mNewid
;
376 * Get the left side of the diff.
377 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
379 * @return RevisionRecord|null
381 public function getOldRevision() {
382 return $this->mOldRev ?
$this->mOldRev
->getRevisionRecord() : null;
386 * Get the right side of the diff.
387 * Should not be null but can still happen in the case of load failure.
388 * @return RevisionRecord|null
390 public function getNewRevision() {
391 return $this->mNewRev ?
$this->mNewRev
->getRevisionRecord() : null;
395 * Look up a special:Undelete link to the given deleted revision id,
396 * as a workaround for being unable to load deleted diffs in currently.
398 * @param int $id Revision ID
400 * @return string|bool Link HTML or false
402 public function deletedLink( $id ) {
403 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
404 if ( $permissionManager->userHasRight( $this->getUser(), 'deletedhistory' ) ) {
405 $dbr = wfGetDB( DB_REPLICA
);
406 $arQuery = Revision
::getArchiveQueryInfo();
407 $row = $dbr->selectRow(
409 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
410 [ 'ar_rev_id' => $id ],
416 $rev = Revision
::newFromArchiveRow( $row );
417 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
419 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
420 'target' => $title->getPrefixedText(),
421 'timestamp' => $rev->getTimestamp()
430 * Build a wikitext link toward a deleted revision, if viewable.
432 * @param int $id Revision ID
434 * @return string Wikitext fragment
436 public function deletedIdMarker( $id ) {
437 $link = $this->deletedLink( $id );
439 return "[$link $id]";
445 private function showMissingRevision() {
446 $out = $this->getOutput();
449 if ( $this->mOldRev
=== null ||
450 ( $this->mOldRev
&& $this->mOldContent
=== null )
452 $missing[] = $this->deletedIdMarker( $this->mOldid
);
454 if ( $this->mNewRev
=== null ||
455 ( $this->mNewRev
&& $this->mNewContent
=== null )
457 $missing[] = $this->deletedIdMarker( $this->mNewid
);
460 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
461 $msg = $this->msg( 'difference-missing-revision' )
462 ->params( $this->getLanguage()->listToText( $missing ) )
463 ->numParams( count( $missing ) )
465 $out->addHTML( $msg );
468 public function showDiffPage( $diffOnly = false ) {
469 # Allow frames except in certain special cases
470 $out = $this->getOutput();
471 $out->allowClickjacking();
472 $out->setRobotPolicy( 'noindex,nofollow' );
474 // Allow extensions to add any extra output here
475 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
477 if ( !$this->loadRevisionData() ) {
478 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
479 $this->showMissingRevision();
484 $user = $this->getUser();
486 if ( $this->mNewPage
) {
487 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
489 if ( $this->mOldPage
) {
490 $permErrors = wfMergeErrorArrays( $permErrors,
491 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
493 if ( count( $permErrors ) ) {
494 throw new PermissionsError( 'read', $permErrors );
500 # Carry over 'diffonly' param via navigation links
501 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
502 $query['diffonly'] = $diffOnly;
504 # Cascade unhide param in links for easy deletion browsing
505 if ( $this->unhide
) {
506 $query['unhide'] = 1;
509 # Check if one of the revisions is deleted/suppressed
510 $deleted = $suppressed = false;
511 $allowed = $this->mNewRev
->userCan( RevisionRecord
::DELETED_TEXT
, $user );
515 # mOldRev is false if the difference engine is called with a "vague" query for
516 # a diff between a version V and its previous version V' AND the version V
517 # is the first version of that article. In that case, V' does not exist.
518 if ( $this->mOldRev
=== false ) {
519 if ( $this->mNewPage
) {
520 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
524 // Allow extensions to change the $oldHeader variable
525 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
527 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
529 if ( !$this->mOldPage ||
!$this->mNewPage
) {
530 // XXX say something to the user?
532 } elseif ( $this->mNewPage
->equals( $this->mOldPage
) ) {
533 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
536 $out->setPageTitle( $this->msg( 'difference-title-multipage',
537 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
538 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
542 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
544 if ( $samePage && $this->mNewPage
&& $permissionManager->quickUserCan(
545 'edit', $user, $this->mNewPage
547 if ( $this->mNewRev
->isCurrent() && $permissionManager->userCan(
548 'rollback', $user, $this->mNewPage
550 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext(),
552 if ( $rollbackLink ) {
553 $out->preventClickjacking();
554 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
558 if ( $this->userCanEdit( $this->mOldRev
) &&
559 $this->userCanEdit( $this->mNewRev
)
561 $undoLink = Html
::element( 'a', [
562 'href' => $this->mNewPage
->getLocalURL( [
564 'undoafter' => $this->mOldid
,
565 'undo' => $this->mNewid
567 'title' => Linker
::titleAttrib( 'undo' ),
569 $this->msg( 'editundo' )->text()
571 $revisionTools['mw-diff-undo'] = $undoLink;
575 # Make "previous revision link"
576 if ( $samePage && $this->mOldPage
&& $this->mOldRev
->getPrevious() ) {
577 $prevlink = Linker
::linkKnown(
579 $this->msg( 'previousdiff' )->escaped(),
580 [ 'id' => 'differences-prevlink' ],
581 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
584 $prevlink = "\u{00A0}";
587 if ( $this->mOldRev
->isMinor() ) {
588 $oldminor = ChangesList
::flag( 'minor' );
593 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
594 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
595 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
597 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
598 '<div id="mw-diff-otitle2">' .
599 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
600 '<div id="mw-diff-otitle3">' . $oldminor .
601 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
602 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
603 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
605 // Allow extensions to change the $oldHeader variable
606 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
607 $diffOnly, $ldel, $this->unhide
] );
609 if ( $this->mOldRev
->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
610 $deleted = true; // old revisions text is hidden
611 if ( $this->mOldRev
->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
612 $suppressed = true; // also suppressed
616 # Check if this user can see the revisions
617 if ( !$this->mOldRev
->userCan( RevisionRecord
::DELETED_TEXT
, $user ) ) {
622 $out->addJsConfigVars( [
623 'wgDiffOldId' => $this->mOldid
,
624 'wgDiffNewId' => $this->mNewid
,
627 # Make "next revision link"
628 # Skip next link on the top revision
629 if ( $samePage && $this->mNewPage
&& !$this->mNewRev
->isCurrent() ) {
630 $nextlink = Linker
::linkKnown(
632 $this->msg( 'nextdiff' )->escaped(),
633 [ 'id' => 'differences-nextlink' ],
634 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
637 $nextlink = "\u{00A0}";
640 if ( $this->mNewRev
->isMinor() ) {
641 $newminor = ChangesList
::flag( 'minor' );
646 # Handle RevisionDelete links...
647 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
649 # Allow extensions to define their own revision tools
650 Hooks
::run( 'DiffRevisionTools',
651 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
652 $formattedRevisionTools = [];
653 // Put each one in parentheses (poor man's button)
654 foreach ( $revisionTools as $key => $tool ) {
655 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
656 $element = Html
::rawElement(
658 [ 'class' => $toolClass ],
659 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
661 $formattedRevisionTools[] = $element;
663 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
664 ' ' . implode( ' ', $formattedRevisionTools );
665 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
667 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
668 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
670 '<div id="mw-diff-ntitle3">' . $newminor .
671 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
672 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
673 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
675 // Allow extensions to change the $newHeader variable
676 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
677 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
679 if ( $this->mNewRev
->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
680 $deleted = true; // new revisions text is hidden
681 if ( $this->mNewRev
->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
682 $suppressed = true; // also suppressed
686 # If the diff cannot be shown due to a deleted revision, then output
687 # the diff header and links to unhide (if available)...
688 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
689 $this->showDiffStyle();
690 $multi = $this->getMultiNotice();
691 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
693 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
694 # Give explanation for why revision is not visible
695 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
698 # Give explanation and add a link to view the diff...
699 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
700 $link = $this->getTitle()->getFullURL( $query );
701 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
703 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
707 # Otherwise, output a regular diff...
709 # Add deletion notice if the user is viewing deleted content
712 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
713 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
714 $this->msg( $msg )->parse() .
717 $this->showDiff( $oldHeader, $newHeader, $notice );
719 $this->renderNewRevision();
725 * Build a link to mark a change as patrolled.
727 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
728 * Side effect: When the patrol link is build, this method will call
729 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
731 * @return string HTML or empty string
733 public function markPatrolledLink() {
734 if ( $this->mMarkPatrolledLink
=== null ) {
735 $linkInfo = $this->getMarkPatrolledLinkInfo();
736 // If false, there is no patrol link needed/allowed
737 if ( !$linkInfo ||
!$this->mNewPage
) {
738 $this->mMarkPatrolledLink
= '';
740 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
743 $this->msg( 'markaspatrolleddiff' )->escaped(),
746 'action' => 'markpatrolled',
747 'rcid' => $linkInfo['rcid'],
750 // Allow extensions to change the markpatrolled link
751 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
752 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
755 return $this->mMarkPatrolledLink
;
759 * Returns an array of meta data needed to build a "mark as patrolled" link and
760 * adds the mediawiki.page.patrol.ajax to the output.
762 * @return array|false An array of meta data for a patrol link (rcid only)
763 * or false if no link is needed
765 protected function getMarkPatrolledLinkInfo() {
766 $user = $this->getUser();
767 $config = $this->getConfig();
768 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
770 // Prepare a change patrol link, if applicable
772 // Is patrolling enabled and the user allowed to?
773 $config->get( 'UseRCPatrol' ) &&
775 $permissionManager->quickUserCan( 'patrol', $user, $this->mNewPage
) &&
776 // Only do this if the revision isn't more than 6 hours older
777 // than the Max RC age (6h because the RC might not be cleaned out regularly)
778 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
780 // Look for an unpatrolled change corresponding to this diff
781 $db = wfGetDB( DB_REPLICA
);
782 $change = RecentChange
::newFromConds(
784 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
785 'rc_this_oldid' => $this->mNewid
,
786 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
791 if ( $change && !$change->getPerformer()->equals( $user ) ) {
792 $rcid = $change->getAttribute( 'rc_id' );
794 // None found or the page has been created by the current user.
795 // If the user could patrol this it already would be patrolled
799 // Allow extensions to possibly change the rcid here
800 // For example the rcid might be set to zero due to the user
801 // being the same as the performer of the change but an extension
802 // might still want to show it under certain conditions
803 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
807 $this->getOutput()->preventClickjacking();
808 if ( $permissionManager->userHasRight( $user, 'writeapi' ) ) {
809 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
818 // No mark as patrolled link applicable
823 * @param Revision $rev
827 protected function revisionDeleteLink( $rev ) {
828 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
829 if ( $link !== '' ) {
830 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
837 * Show the new revision of the page.
839 * @note Not supported after calling setContent().
841 public function renderNewRevision() {
842 if ( $this->isContentOverridden
) {
843 // The code below only works with a Revision object. We could construct a fake revision
844 // (here or in setContent), but since this does not seem needed at the moment,
845 // we'll just fail for now.
846 throw new LogicException(
848 . ' is not supported after calling setContent(). Use setRevisions() instead.'
852 $out = $this->getOutput();
853 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
854 # Add "current version as of X" title
855 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
856 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
857 # Page content may be handled by a hooked call instead...
858 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
859 $this->loadNewText();
860 if ( !$this->mNewPage
) {
861 // New revision is unsaved; bail out.
862 // TODO in theory rendering the new revision is a meaningful thing to do
863 // even if it's unsaved, but a lot of untangling is required to do it safely.
867 $out->setRevisionId( $this->mNewid
);
868 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
869 $out->setArticleFlag( true );
871 if ( !Hooks
::run( 'ArticleRevisionViewCustom',
872 [ $this->mNewRev
->getRevisionRecord(), $this->mNewPage
, $out ] )
874 // Handled by extension
875 // NOTE: sync with hooks called in Article::view()
876 } elseif ( !Hooks
::run( 'ArticleContentViewCustom',
877 [ $this->mNewContent
, $this->mNewPage
, $out ], '1.32' )
879 // Handled by extension
880 // NOTE: sync with hooks called in Article::view()
883 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
884 // If the Title stored in the context is the same as the one
885 // of the new revision, we can use its associated WikiPage
887 $wikiPage = $this->getWikiPage();
889 // Otherwise we need to create our own WikiPage object
890 $wikiPage = WikiPage
::factory( $this->mNewPage
);
893 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
895 # WikiPage::getParserOutput() should not return false, but just in case
896 if ( $parserOutput ) {
897 // Allow extensions to change parser output here
898 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
899 [ $this, $out, $parserOutput, $wikiPage ] )
901 $out->addParserOutput( $parserOutput, [
902 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
903 && MediaWikiServices
::getInstance()->getPermissionManager()->quickUserCan(
906 $this->mNewRev
->getTitle()
914 // Allow extensions to optionally not show the final patrolled link
915 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
916 # Add redundant patrol link on bottom...
917 $out->addHTML( $this->markPatrolledLink() );
922 * @param WikiPage $page
923 * @param Revision $rev
925 * @return ParserOutput|bool False if the revision was not found
927 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
928 if ( !$rev->getId() ) {
929 // WikiPage::getParserOutput wants a revision ID. Passing 0 will incorrectly show
930 // the current revision, so fail instead. If need be, WikiPage::getParserOutput
931 // could be made to accept a Revision or RevisionRecord instead of the id.
935 $parserOptions = $page->makeParserOptions( $this->getContext() );
936 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
938 return $parserOutput;
942 * Get the diff text, send it to the OutputPage object
943 * Returns false if the diff could not be generated, otherwise returns true
945 * @param string|bool $otitle Header for old text or false
946 * @param string|bool $ntitle Header for new text or false
947 * @param string $notice HTML between diff header and body
951 public function showDiff( $otitle, $ntitle, $notice = '' ) {
952 // Allow extensions to affect the output here
953 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
955 $diff = $this->getDiff( $otitle, $ntitle, $notice );
956 if ( $diff === false ) {
957 $this->showMissingRevision();
961 $this->showDiffStyle();
962 $this->getOutput()->addHTML( $diff );
969 * Add style sheets for diff display.
971 public function showDiffStyle() {
972 if ( !$this->isSlotDiffRenderer
) {
973 $this->getOutput()->addModuleStyles( [
974 'mediawiki.interface.helpers.styles',
975 'mediawiki.diff.styles'
977 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
978 $slotDiffRenderer->addModules( $this->getOutput() );
984 * Get complete diff table, including header
986 * @param string|bool $otitle Header for old text or false
987 * @param string|bool $ntitle Header for new text or false
988 * @param string $notice HTML between diff header and body
992 public function getDiff( $otitle, $ntitle, $notice = '' ) {
993 $body = $this->getDiffBody();
994 if ( $body === false ) {
998 $multi = $this->getMultiNotice();
999 // Display a message when the diff is empty
1000 if ( $body === '' ) {
1001 $notice .= '<div class="mw-diff-empty">' .
1002 $this->msg( 'diff-empty' )->parse() .
1006 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
1010 * Get the diff table body, without header
1012 * @return mixed (string/false)
1014 public function getDiffBody() {
1015 $this->mCacheHit
= true;
1016 // Check if the diff should be hidden from this user
1017 if ( !$this->isContentOverridden
) {
1018 if ( !$this->loadRevisionData() ) {
1020 } elseif ( $this->mOldRev
&&
1021 !$this->mOldRev
->userCan( RevisionRecord
::DELETED_TEXT
, $this->getUser() )
1024 } elseif ( $this->mNewRev
&&
1025 !$this->mNewRev
->userCan( RevisionRecord
::DELETED_TEXT
, $this->getUser() )
1030 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
&&
1031 $this->mOldRev
->getId() && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
1033 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
1041 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1042 if ( $this->mOldid
&& $this->mNewid
) {
1043 // Check if subclass is still using the old way
1044 // for backwards-compatibility
1045 $key = $this->getDiffBodyCacheKey();
1046 if ( $key === null ) {
1047 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
1051 if ( !$this->mRefreshCache
) {
1052 $difftext = $cache->get( $key );
1053 if ( is_string( $difftext ) ) {
1054 wfIncrStats( 'diff_cache.hit' );
1055 $difftext = $this->localiseDiff( $difftext );
1056 $difftext .= "\n<!-- diff cache key $key -->\n";
1060 } // don't try to load but save the result
1062 $this->mCacheHit
= false;
1064 // Loadtext is permission safe, this just clears out the diff
1065 if ( !$this->loadText() ) {
1070 // We've checked for revdelete at the beginning of this method; it's OK to ignore
1071 // read permissions here.
1072 $slotContents = $this->getSlotContents();
1073 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
1074 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
1075 $slotContents[$role]['new'] );
1076 if ( $slotDiff && $role !== SlotRecord
::MAIN
) {
1077 // FIXME: ask SlotRoleHandler::getSlotNameMessage
1079 $difftext .= $this->getSlotHeader( $slotTitle );
1081 $difftext .= $slotDiff;
1084 // Avoid PHP 7.1 warning from passing $this by reference
1085 $diffEngine = $this;
1087 // Save to cache for 7 days
1088 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1089 wfIncrStats( 'diff_cache.uncacheable' );
1090 } elseif ( $key !== false && $difftext !== false ) {
1091 wfIncrStats( 'diff_cache.miss' );
1092 $cache->set( $key, $difftext, 7 * 86400 );
1094 wfIncrStats( 'diff_cache.uncacheable' );
1096 // localise line numbers and title attribute text
1097 if ( $difftext !== false ) {
1098 $difftext = $this->localiseDiff( $difftext );
1105 * Get the diff table body for one slot, without header
1107 * @param string $role
1108 * @return string|false
1110 public function getDiffBodyForRole( $role ) {
1111 $diffRenderers = $this->getSlotDiffRenderers();
1112 if ( !isset( $diffRenderers[$role] ) ) {
1116 $slotContents = $this->getSlotContents();
1117 $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1118 $slotContents[$role]['new'] );
1123 if ( $role !== SlotRecord
::MAIN
) {
1124 // TODO use human-readable role name at least
1126 $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1129 return $this->localiseDiff( $slotDiff );
1133 * Get a slot header for inclusion in a diff body (as a table row).
1135 * @param string $headerText The text of the header
1139 protected function getSlotHeader( $headerText ) {
1140 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1141 $columnCount = $this->mOldRev ?
4 : 2;
1142 $userLang = $this->getLanguage()->getHtmlCode();
1143 return Html
::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1144 Html
::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1148 * Returns the cache key for diff body text or content.
1150 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1153 * @throws MWException
1154 * @return string|null
1156 protected function getDiffBodyCacheKey() {
1161 * Get the cache key parameters
1163 * Subclasses can replace the first element in the array to something
1164 * more specific to the type of diff (e.g. "inline-diff"), or append
1165 * if the cache should vary on more things. Overriding entirely should
1171 * @throws MWException
1173 protected function getDiffBodyCacheKeyParams() {
1174 if ( !$this->mOldid ||
!$this->mNewid
) {
1175 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1178 $engine = $this->getEngine();
1183 "old-{$this->mOldid}",
1184 "rev-{$this->mNewid}"
1187 if ( $engine === 'wikidiff2' ) {
1188 $params[] = phpversion( 'wikidiff2' );
1191 if ( !$this->isSlotDiffRenderer
) {
1192 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1193 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1201 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1202 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1204 * @internal for use by DifferenceEngineSlotDiffRenderer only
1207 public function getExtraCacheKeys() {
1208 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1209 // about special things, not the revision IDs, which are added to the cache key by the
1210 // page-level DifferenceEngine, and which might not have a valid value for this object.
1211 $this->mOldid
= 123456789;
1212 $this->mNewid
= 987654321;
1214 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1215 $cacheString = $this->getDiffBodyCacheKey();
1216 if ( $cacheString ) {
1217 return [ $cacheString ];
1220 $params = $this->getDiffBodyCacheKeyParams();
1222 // Try to get rid of the standard keys to keep the cache key human-readable:
1223 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1224 // the child class includes the same keys, drop them.
1225 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1226 // as long as we are already in a non-static method of the same class, and the call context
1227 // ($this) will be inherited.
1228 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1229 $standardParams = DifferenceEngine
::getDiffBodyCacheKeyParams();
1230 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1231 $params = array_slice( $params, count( $standardParams ) );
1238 * Generate a diff, no caching.
1242 * @param Content $old Old content
1243 * @param Content $new New content
1245 * @throws Exception If old or new content is not an instance of TextContent.
1246 * @return bool|string
1248 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1250 public function generateContentDiffBody( Content
$old, Content
$new ) {
1251 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1253 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1254 && $this->isSlotDiffRenderer
1256 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1257 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1258 // This will happen when a content model has no custom slot diff renderer, it does have
1259 // a custom difference engine, but that does not override this method.
1260 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1261 . 'Please use a SlotDiffRenderer.' );
1263 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1267 * Generate a diff, no caching
1269 * @param string $otext Old text, must be already segmented
1270 * @param string $ntext New text, must be already segmented
1272 * @throws Exception If content handling for text content is configured in a way
1273 * that makes maintaining B/C hard.
1274 * @return bool|string
1276 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1278 public function generateTextDiffBody( $otext, $ntext ) {
1279 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1280 ->getSlotDiffRenderer( $this->getContext() );
1281 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1282 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1283 // This is too unlikely to happen to bother handling properly.
1284 throw new Exception( 'The slot diff renderer for text content should be a '
1285 . 'TextSlotDiffRenderer subclass' );
1287 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1291 * Process $wgExternalDiffEngine and get a sane, usable engine
1293 * @return bool|string 'wikidiff2', path to an executable, or false
1294 * @internal For use by this class and TextSlotDiffRenderer only.
1296 public static function getEngine() {
1297 global $wgExternalDiffEngine;
1298 // We use the global here instead of Config because we write to the value,
1299 // and Config is not mutable.
1300 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
1301 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1302 $wgExternalDiffEngine = false;
1303 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1304 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1305 $wgExternalDiffEngine = false;
1306 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1307 // And prevent people from shooting themselves in the foot...
1308 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1309 $wgExternalDiffEngine = false;
1312 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1313 return $wgExternalDiffEngine;
1314 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1323 * Generates diff, to be wrapped internally in a logging/instrumentation
1325 * @param string $otext Old text, must be already segmented
1326 * @param string $ntext New text, must be already segmented
1328 * @throws Exception If content handling for text content is configured in a way
1329 * that makes maintaining B/C hard.
1330 * @return bool|string
1332 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1334 protected function textDiff( $otext, $ntext ) {
1335 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1336 ->getSlotDiffRenderer( $this->getContext() );
1337 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1338 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1339 // This is too unlikely to happen to bother handling properly.
1340 throw new Exception( 'The slot diff renderer for text content should be a '
1341 . 'TextSlotDiffRenderer subclass' );
1343 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1347 * Generate a debug comment indicating diff generating time,
1348 * server node, and generator backend.
1350 * @param string $generator : What diff engine was used
1354 protected function debug( $generator = "internal" ) {
1355 if ( !$this->enableDebugComment
) {
1358 $data = [ $generator ];
1359 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1360 $data[] = wfHostname();
1362 $data[] = wfTimestamp( TS_DB
);
1364 return "<!-- diff generator: " .
1365 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1369 private function getDebugString() {
1370 $engine = self
::getEngine();
1371 if ( $engine === 'wikidiff2' ) {
1372 return $this->debug( 'wikidiff2' );
1373 } elseif ( $engine === false ) {
1374 return $this->debug( 'native PHP' );
1376 return $this->debug( "external $engine" );
1381 * Localise diff output
1383 * @param string $text
1386 private function localiseDiff( $text ) {
1387 $text = $this->localiseLineNumbers( $text );
1388 if ( $this->getEngine() === 'wikidiff2' &&
1389 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1391 $text = $this->addLocalisedTitleTooltips( $text );
1397 * Replace line numbers with the text in the user's language
1399 * @param string $text
1403 public function localiseLineNumbers( $text ) {
1404 return preg_replace_callback(
1405 '/<!--LINE (\d+)-->/',
1406 [ $this, 'localiseLineNumbersCb' ],
1411 public function localiseLineNumbersCb( $matches ) {
1412 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1416 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1420 * Add title attributes for tooltips on moved paragraph indicators
1422 * @param string $text
1425 private function addLocalisedTitleTooltips( $text ) {
1426 return preg_replace_callback(
1427 '/class="mw-diff-movedpara-(left|right)"/',
1428 [ $this, 'addLocalisedTitleTooltipsCb' ],
1434 * @param array $matches
1437 private function addLocalisedTitleTooltipsCb( array $matches ) {
1438 $key = $matches[1] === 'right' ?
1439 'diff-paragraph-moved-toold' :
1440 'diff-paragraph-moved-tonew';
1441 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1445 * If there are revisions between the ones being compared, return a note saying so.
1449 public function getMultiNotice() {
1450 // The notice only make sense if we are diffing two saved revisions of the same page.
1452 !$this->mOldRev ||
!$this->mNewRev
1453 ||
!$this->mOldPage ||
!$this->mNewPage
1454 ||
!$this->mOldPage
->equals( $this->mNewPage
)
1459 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1460 $oldRev = $this->mNewRev
; // flip
1461 $newRev = $this->mOldRev
; // flip
1462 } else { // normal case
1463 $oldRev = $this->mOldRev
;
1464 $newRev = $this->mNewRev
;
1467 // Sanity: don't show the notice if too many rows must be scanned
1468 // @todo show some special message for that case
1469 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1470 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1471 $limit = 100; // use diff-multi-manyusers if too many users
1472 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1473 $numUsers = count( $users );
1475 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( RevisionRecord
::RAW
) ) {
1476 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1479 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1486 * Get a notice about how many intermediate edits and users there are
1488 * @param int $numEdits
1489 * @param int $numUsers
1494 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1495 if ( $numUsers === 0 ) {
1496 $msg = 'diff-multi-sameuser';
1497 } elseif ( $numUsers > $limit ) {
1498 $msg = 'diff-multi-manyusers';
1501 $msg = 'diff-multi-otherusers';
1504 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1508 * @param Revision $rev
1509 * @return bool whether the user can see and edit the revision.
1511 private function userCanEdit( Revision
$rev ) {
1512 $user = $this->getUser();
1514 if ( !$rev->userCan( RevisionRecord
::DELETED_TEXT
, $user ) ) {
1522 * Get a header for a specified revision.
1524 * @param Revision $rev
1525 * @param string $complete 'complete' to get the header wrapped depending
1526 * the visibility of the revision and a link to edit the page.
1528 * @return string HTML fragment
1530 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1531 $lang = $this->getLanguage();
1532 $user = $this->getUser();
1533 $revtimestamp = $rev->getTimestamp();
1534 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1535 $dateofrev = $lang->userDate( $revtimestamp, $user );
1536 $timeofrev = $lang->userTime( $revtimestamp, $user );
1538 $header = $this->msg(
1539 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1545 if ( $complete !== 'complete' ) {
1549 $title = $rev->getTitle();
1551 $header = Linker
::linkKnown( $title, $header, [],
1552 [ 'oldid' => $rev->getId() ] );
1554 if ( $this->userCanEdit( $rev ) ) {
1555 $editQuery = [ 'action' => 'edit' ];
1556 if ( !$rev->isCurrent() ) {
1557 $editQuery['oldid'] = $rev->getId();
1560 $key = MediaWikiServices
::getInstance()->getPermissionManager()
1561 ->quickUserCan( 'edit', $user, $title ) ?
'editold' : 'viewsourceold';
1562 $msg = $this->msg( $key )->escaped();
1563 $editLink = $this->msg( 'parentheses' )->rawParams(
1564 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1565 $header .= ' ' . Html
::rawElement(
1567 [ 'class' => 'mw-diff-edit' ],
1570 if ( $rev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
1571 $header = Html
::rawElement(
1573 [ 'class' => 'history-deleted' ],
1578 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1585 * Add the header to a diff body
1587 * @param string $diff Diff body
1588 * @param string $otitle Old revision header
1589 * @param string $ntitle New revision header
1590 * @param string $multi Notice telling user that there are intermediate
1591 * revisions between the ones being compared
1592 * @param string $notice Other notices, e.g. that user is viewing deleted content
1596 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1597 // shared.css sets diff in interface language/dir, but the actual content
1598 // is often in a different language, mostly the page content language/dir
1599 $header = Html
::openElement( 'table', [
1600 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1601 'data-mw' => 'interface',
1603 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1605 if ( !$diff && !$otitle ) {
1607 <tr class=\"diff-title\" lang=\"{$userLang}\">
1608 <td class=\"diff-ntitle\">{$ntitle}</td>
1612 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1614 <col class=\"diff-marker\" />
1615 <col class=\"diff-content\" />
1616 <col class=\"diff-marker\" />
1617 <col class=\"diff-content\" />";
1624 if ( $otitle ||
$ntitle ) {
1626 <tr class=\"diff-title\" lang=\"{$userLang}\">
1627 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1628 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1633 if ( $multi != '' ) {
1634 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1635 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1637 if ( $notice != '' ) {
1638 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1639 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1642 return $header . $diff . "</table>";
1646 * Use specified text instead of loading from the database
1647 * @param Content $oldContent
1648 * @param Content $newContent
1650 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1652 public function setContent( Content
$oldContent, Content
$newContent ) {
1653 $this->mOldContent
= $oldContent;
1654 $this->mNewContent
= $newContent;
1656 $this->mTextLoaded
= 2;
1657 $this->mRevisionsLoaded
= true;
1658 $this->isContentOverridden
= true;
1659 $this->slotDiffRenderers
= null;
1663 * Use specified text instead of loading from the database.
1664 * @param RevisionRecord|null $oldRevision
1665 * @param RevisionRecord $newRevision
1667 public function setRevisions(
1668 RevisionRecord
$oldRevision = null, RevisionRecord
$newRevision
1670 if ( $oldRevision ) {
1671 $this->mOldRev
= new Revision( $oldRevision );
1672 $this->mOldid
= $oldRevision->getId();
1673 $this->mOldPage
= Title
::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1674 // This method is meant for edit diffs and such so there is no reason to provide a
1675 // revision that's not readable to the user, but check it just in case.
1676 $this->mOldContent
= $oldRevision->getContent( SlotRecord
::MAIN
,
1677 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1679 $this->mOldPage
= null;
1680 $this->mOldRev
= $this->mOldid
= false;
1682 $this->mNewRev
= new Revision( $newRevision );
1683 $this->mNewid
= $newRevision->getId();
1684 $this->mNewPage
= Title
::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1685 $this->mNewContent
= $newRevision->getContent( SlotRecord
::MAIN
,
1686 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1688 $this->mRevisionsIdsLoaded
= $this->mRevisionsLoaded
= true;
1689 $this->mTextLoaded
= $oldRevision ?
2 : 1;
1690 $this->isContentOverridden
= false;
1691 $this->slotDiffRenderers
= null;
1695 * Set the language in which the diff text is written
1697 * @param Language $lang
1700 public function setTextLanguage( Language
$lang ) {
1701 $this->mDiffLang
= $lang;
1705 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1706 * to a pair of actual integers representing revision ids.
1708 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1709 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1711 * @return array List of two revision ids, older first, later second.
1712 * Zero signifies invalid argument passed.
1713 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1715 public function mapDiffPrevNext( $old, $new ) {
1716 if ( $new === 'prev' ) {
1717 // Show diff between revision $old and the previous one. Get previous one from DB.
1718 $newid = intval( $old );
1719 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1720 } elseif ( $new === 'next' ) {
1721 // Show diff between revision $old and the next one. Get next one from DB.
1722 $oldid = intval( $old );
1723 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1725 $oldid = intval( $old );
1726 $newid = intval( $new );
1729 return [ $oldid, $newid ];
1735 private function loadRevisionIds() {
1736 if ( $this->mRevisionsIdsLoaded
) {
1740 $this->mRevisionsIdsLoaded
= true;
1742 $old = $this->mOldid
;
1743 $new = $this->mNewid
;
1745 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1746 if ( $new === 'next' && $this->mNewid
=== false ) {
1747 # if no result, NewId points to the newest old revision. The only newer
1748 # revision is cur, which is "0".
1753 'NewDifferenceEngine',
1754 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1759 * Load revision metadata for the specified revisions. If newid is 0, then compare
1760 * the old revision in oldid to the current revision of the current page (as defined
1761 * by the request context); if oldid is 0, then compare the revision in newid to the
1762 * immediately previous one.
1764 * If oldid is false, leave the corresponding revision object set to false. This can
1765 * happen with 'diff=prev' pointing to a non-existent revision, and is also used directly
1768 * @return bool Whether both revisions were loaded successfully. Setting mOldRev
1769 * to false counts as successful loading.
1771 public function loadRevisionData() {
1772 if ( $this->mRevisionsLoaded
) {
1773 return $this->isContentOverridden ||
( $this->mOldRev
!== null && $this->mNewRev
!== null );
1776 // Whether it succeeds or fails, we don't want to try again
1777 $this->mRevisionsLoaded
= true;
1779 $this->loadRevisionIds();
1781 // Load the new revision object
1782 if ( $this->mNewid
) {
1783 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1785 $this->mNewRev
= Revision
::newFromTitle(
1788 Revision
::READ_NORMAL
1792 if ( !$this->mNewRev
instanceof Revision
) {
1796 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1797 $this->mNewid
= $this->mNewRev
->getId();
1798 if ( $this->mNewid
) {
1799 $this->mNewPage
= $this->mNewRev
->getTitle();
1801 $this->mNewPage
= null;
1804 // Load the old revision object
1805 $this->mOldRev
= false;
1806 if ( $this->mOldid
) {
1807 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1808 } elseif ( $this->mOldid
=== 0 ) {
1809 $rev = $this->mNewRev
->getPrevious();
1811 $this->mOldid
= $rev->getId();
1812 $this->mOldRev
= $rev;
1814 // No previous revision; mark to show as first-version only.
1815 $this->mOldid
= false;
1816 $this->mOldRev
= false;
1818 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1820 if ( is_null( $this->mOldRev
) ) {
1824 if ( $this->mOldRev
&& $this->mOldRev
->getId() ) {
1825 $this->mOldPage
= $this->mOldRev
->getTitle();
1827 $this->mOldPage
= null;
1830 // Load tags information for both revisions
1831 $dbr = wfGetDB( DB_REPLICA
);
1832 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
1833 if ( $this->mOldid
!== false ) {
1834 $tagIds = $dbr->selectFieldValues(
1837 [ 'ct_rev_id' => $this->mOldid
],
1841 foreach ( $tagIds as $tagId ) {
1843 $tags[] = $changeTagDefStore->getName( (int)$tagId );
1844 } catch ( NameTableAccessException
$exception ) {
1848 $this->mOldTags
= implode( ',', $tags );
1850 $this->mOldTags
= false;
1853 $tagIds = $dbr->selectFieldValues(
1856 [ 'ct_rev_id' => $this->mNewid
],
1860 foreach ( $tagIds as $tagId ) {
1862 $tags[] = $changeTagDefStore->getName( (int)$tagId );
1863 } catch ( NameTableAccessException
$exception ) {
1867 $this->mNewTags
= implode( ',', $tags );
1873 * Load the text of the revisions, as well as revision data.
1874 * When the old revision is missing (mOldRev is false), loading mOldContent is not attempted.
1876 * @return bool Whether the content of both revisions could be loaded successfully.
1877 * (When mOldRev is false, that still counts as a success.)
1880 public function loadText() {
1881 if ( $this->mTextLoaded
== 2 ) {
1882 return $this->loadRevisionData() && ( $this->mOldRev
=== false ||
$this->mOldContent
)
1883 && $this->mNewContent
;
1886 // Whether it succeeds or fails, we don't want to try again
1887 $this->mTextLoaded
= 2;
1889 if ( !$this->loadRevisionData() ) {
1893 if ( $this->mOldRev
) {
1894 $this->mOldContent
= $this->mOldRev
->getContent(
1895 RevisionRecord
::FOR_THIS_USER
, $this->getUser()
1897 if ( $this->mOldContent
=== null ) {
1902 $this->mNewContent
= $this->mNewRev
->getContent(
1903 RevisionRecord
::FOR_THIS_USER
, $this->getUser()
1905 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1906 if ( $this->mNewContent
=== null ) {
1914 * Load the text of the new revision, not the old one
1916 * @return bool Whether the content of the new revision could be loaded successfully.
1918 public function loadNewText() {
1919 if ( $this->mTextLoaded
>= 1 ) {
1920 return $this->loadRevisionData();
1923 $this->mTextLoaded
= 1;
1925 if ( !$this->loadRevisionData() ) {
1929 $this->mNewContent
= $this->mNewRev
->getContent(
1930 RevisionRecord
::FOR_THIS_USER
, $this->getUser()
1933 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );