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\Permissions\PermissionManager
;
26 use MediaWiki\Revision\RevisionRecord
;
27 use MediaWiki\Revision\SlotRecord
;
28 use MediaWiki\Storage\NameTableAccessException
;
31 * DifferenceEngine is responsible for rendering the difference between two revisions as HTML.
32 * This includes interpreting URL parameters, retrieving revision data, checking access permissions,
33 * selecting and invoking the diff generator class for the individual slots, doing post-processing
34 * on the generated diff, adding the rest of the HTML (such as headers) and writing the whole thing
37 * DifferenceEngine can be subclassed by extensions, by customizing
38 * ContentHandler::createDifferenceEngine; the content handler will be selected based on the
39 * content model of the main slot (of the new revision, when the two are different).
40 * That might change after PageTypeHandler gets introduced.
42 * In the past, the class was also used for slot-level diff generation, and extensions might still
43 * subclass it and add such functionality. When that is the case (sepcifically, when a
44 * ContentHandler returns a standard SlotDiffRenderer but a nonstandard DifferenceEngine)
45 * DifferenceEngineSlotDiffRenderer will be used to convert the old behavior into the new one.
47 * @ingroup DifferenceEngine
49 * @todo This class is huge and poorly defined. It should be split into a controller responsible
50 * for interpreting query parameters, retrieving data and checking permissions; and a HTML renderer.
52 class DifferenceEngine
extends ContextSource
{
54 use DeprecationHelper
;
57 * Constant to indicate diff cache compatibility.
58 * Bump this when changing the diff formatting in a way that
59 * fixes important bugs or such to force cached diff views to
62 const DIFF_VERSION
= '1.12';
65 * Revision ID for the old revision. 0 for the revision previous to $mNewid, false
66 * if the diff does not have an old revision (e.g. 'oldid=<first revision of page>&diff=prev'),
67 * or the revision does not exist, null if the revision is unsaved.
73 * Revision ID for the new revision. 0 for the last revision of the current page
74 * (as defined by the request context), false if the revision does not exist, null
75 * if it is unsaved, or an alias such as 'next'.
76 * @var int|string|false|null
81 * Old revision (left pane).
82 * Allowed to be an unsaved revision, unlikely that's ever needed though.
83 * False when the old revision does not exist; this can happen when using
84 * diff=prev on the first revision. Null when the revision should exist but
85 * doesn't (e.g. load failure); loadRevisionData() will return false in that
86 * case. Also null until lazy-loaded. Ignored completely when isContentOverridden
88 * Since 1.32 public access is deprecated.
89 * @var Revision|null|false
94 * New revision (right pane).
95 * Note that this might be an unsaved revision (e.g. for edit preview).
96 * Null in case of load failure; diff methods will just return an error message in that case,
97 * and loadRevisionData() will return false. Also null until lazy-loaded. Ignored completely
98 * when isContentOverridden is set.
99 * Since 1.32 public access is deprecated.
105 * Title of $mOldRev or null if the old revision does not exist or does not belong to a page.
106 * Since 1.32 public access is deprecated and the property can be null.
112 * Title of $mNewRev or null if the new revision does not exist or does not belong to a page.
113 * Since 1.32 public access is deprecated and the property can be null.
119 * Change tags of $mOldRev or null if it does not exist / is not saved.
125 * Change tags of $mNewRev or null if it does not exist / is not saved.
132 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
133 * This property is set to the content of the main slot, but not actually used for the main diff.
135 private $mOldContent;
139 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
140 * This property is set to the content of the main slot, but not actually used for the main diff.
142 private $mNewContent;
145 protected $mDiffLang;
147 /** @var bool Have the revisions IDs been loaded */
148 private $mRevisionsIdsLoaded = false;
150 /** @var bool Have the revisions been loaded */
151 protected $mRevisionsLoaded = false;
153 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
154 protected $mTextLoaded = 0;
157 * Was the content overridden via setContent()?
158 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
159 * and only mOldContent and mNewContent is reliable.
160 * (Note that setRevisions() does not set this flag as in that case all properties are
161 * overriden and remain consistent with each other, so no special handling is needed.)
164 protected $isContentOverridden = false;
166 /** @var bool Was the diff fetched from cache? */
167 protected $mCacheHit = false;
170 * Set this to true to add debug info to the HTML output.
171 * Warning: this may cause RSS readers to spuriously mark articles as "new"
174 public $enableDebugComment = false;
176 /** @var bool If true, line X is not displayed when X is 1, for example
177 * to increase readability and conserve space with many small diffs.
179 protected $mReducedLineNumbers = false;
181 /** @var string Link to action=markpatrolled */
182 protected $mMarkPatrolledLink = null;
184 /** @var bool Show rev_deleted content if allowed */
185 protected $unhide = false;
187 /** @var bool Refresh the diff cache */
188 protected $mRefreshCache = false;
190 /** @var SlotDiffRenderer[] DifferenceEngine classes for the slots, keyed by role name. */
191 protected $slotDiffRenderers = null;
194 * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
195 * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
196 * $slotDiffRenderers should not be used.
199 protected $isSlotDiffRenderer = false;
204 * @param IContextSource|null $context Context to use, anything else will be ignored
205 * @param int $old Old ID we want to show and diff with.
206 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
207 * @param int $rcid Deprecated, no longer used!
208 * @param bool $refreshCache If set, refreshes the diff cache
209 * @param bool $unhide If set, allow viewing deleted revs
211 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
212 $refreshCache = false, $unhide = false
214 $this->deprecatePublicProperty( 'mOldid', '1.32', __CLASS__
);
215 $this->deprecatePublicProperty( 'mNewid', '1.32', __CLASS__
);
216 $this->deprecatePublicProperty( 'mOldRev', '1.32', __CLASS__
);
217 $this->deprecatePublicProperty( 'mNewRev', '1.32', __CLASS__
);
218 $this->deprecatePublicProperty( 'mOldPage', '1.32', __CLASS__
);
219 $this->deprecatePublicProperty( 'mNewPage', '1.32', __CLASS__
);
220 $this->deprecatePublicProperty( 'mOldContent', '1.32', __CLASS__
);
221 $this->deprecatePublicProperty( 'mNewContent', '1.32', __CLASS__
);
222 $this->deprecatePublicProperty( 'mRevisionsLoaded', '1.32', __CLASS__
);
223 $this->deprecatePublicProperty( 'mTextLoaded', '1.32', __CLASS__
);
224 $this->deprecatePublicProperty( 'mCacheHit', '1.32', __CLASS__
);
226 if ( $context instanceof IContextSource
) {
227 $this->setContext( $context );
230 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
232 $this->mOldid
= $old;
233 $this->mNewid
= $new;
234 $this->mRefreshCache
= $refreshCache;
235 $this->unhide
= $unhide;
239 * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
240 * Includes slots only present in one of the revisions.
242 protected function getSlotDiffRenderers() {
243 if ( $this->isSlotDiffRenderer
) {
244 throw new LogicException( __METHOD__
. ' called in slot diff renderer mode' );
247 if ( $this->slotDiffRenderers
=== null ) {
248 if ( !$this->loadRevisionData() ) {
252 $slotContents = $this->getSlotContents();
253 $this->slotDiffRenderers
= array_map( function ( $contents ) {
254 /** @var Content $content */
255 $content = $contents['new'] ?
: $contents['old'];
256 return $content->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
259 return $this->slotDiffRenderers
;
263 * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
264 * This is used in legacy mode when the DifferenceEngine is wrapped in a
265 * DifferenceEngineSlotDiffRenderer.
266 * @internal For use by DifferenceEngineSlotDiffRenderer only.
268 public function markAsSlotDiffRenderer() {
269 $this->isSlotDiffRenderer
= true;
273 * Get the old and new content objects for all slots.
274 * This method does not do any permission checks.
275 * @return array [ role => [ 'old' => SlotRecord|null, 'new' => SlotRecord|null ], ... ]
277 protected function getSlotContents() {
278 if ( $this->isContentOverridden
) {
280 SlotRecord
::MAIN
=> [
281 'old' => $this->mOldContent
,
282 'new' => $this->mNewContent
,
285 } elseif ( !$this->loadRevisionData() ) {
289 $newSlots = $this->mNewRev
->getRevisionRecord()->getSlots()->getSlots();
290 if ( $this->mOldRev
) {
291 $oldSlots = $this->mOldRev
->getRevisionRecord()->getSlots()->getSlots();
295 // The order here will determine the visual order of the diff. The current logic is
296 // slots of the new revision first in natural order, then deleted ones. This is ad hoc
297 // and should not be relied on - in the future we may want the ordering to depend
299 $roles = array_merge( array_keys( $newSlots ), array_keys( $oldSlots ) );
302 foreach ( $roles as $role ) {
304 'old' => isset( $oldSlots[$role] ) ?
$oldSlots[$role]->getContent() : null,
305 'new' => isset( $newSlots[$role] ) ?
$newSlots[$role]->getContent() : null,
308 // move main slot to front
309 if ( isset( $slots[SlotRecord
::MAIN
] ) ) {
310 $slots = [ SlotRecord
::MAIN
=> $slots[SlotRecord
::MAIN
] ] +
$slots;
315 public function getTitle() {
316 // T202454 avoid errors when there is no title
317 return parent
::getTitle() ?
: Title
::makeTitle( NS_SPECIAL
, 'BadTitle/DifferenceEngine' );
321 * Set reduced line numbers mode.
322 * When set, line X is not displayed when X is 1, for example to increase readability and
323 * conserve space with many small diffs.
326 public function setReducedLineNumbers( $value = true ) {
327 $this->mReducedLineNumbers
= $value;
331 * Get the language of the difference engine, defaults to page content language
335 public function getDiffLang() {
336 if ( $this->mDiffLang
=== null ) {
337 # Default language in which the diff text is written.
338 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
341 return $this->mDiffLang
;
347 public function wasCacheHit() {
348 return $this->mCacheHit
;
352 * Get the ID of old revision (left pane) of the diff. 0 for the revision
353 * previous to getNewid(), false if the old revision does not exist, null
355 * To get a real revision ID instead of 0, call loadRevisionData() first.
356 * @return int|false|null
358 public function getOldid() {
359 $this->loadRevisionIds();
361 return $this->mOldid
;
365 * Get the ID of new revision (right pane) of the diff. 0 for the current revision,
366 * false if the new revision does not exist, null if it's unsaved.
367 * To get a real revision ID instead of 0, call loadRevisionData() first.
368 * @return int|false|null
370 public function getNewid() {
371 $this->loadRevisionIds();
373 return $this->mNewid
;
377 * Get the left side of the diff.
378 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
380 * @return RevisionRecord|null
382 public function getOldRevision() {
383 return $this->mOldRev ?
$this->mOldRev
->getRevisionRecord() : null;
387 * Get the right side of the diff.
388 * Should not be null but can still happen in the case of load failure.
389 * @return RevisionRecord|null
391 public function getNewRevision() {
392 return $this->mNewRev ?
$this->mNewRev
->getRevisionRecord() : null;
396 * Look up a special:Undelete link to the given deleted revision id,
397 * as a workaround for being unable to load deleted diffs in currently.
399 * @param int $id Revision ID
401 * @return string|bool Link HTML or false
403 public function deletedLink( $id ) {
404 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
405 if ( $permissionManager->userHasRight( $this->getUser(), 'deletedhistory' ) ) {
406 $dbr = wfGetDB( DB_REPLICA
);
407 $arQuery = Revision
::getArchiveQueryInfo();
408 $row = $dbr->selectRow(
410 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
411 [ 'ar_rev_id' => $id ],
417 $rev = Revision
::newFromArchiveRow( $row );
418 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
420 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
421 'target' => $title->getPrefixedText(),
422 'timestamp' => $rev->getTimestamp()
431 * Build a wikitext link toward a deleted revision, if viewable.
433 * @param int $id Revision ID
435 * @return string Wikitext fragment
437 public function deletedIdMarker( $id ) {
438 $link = $this->deletedLink( $id );
440 return "[$link $id]";
446 private function showMissingRevision() {
447 $out = $this->getOutput();
450 if ( $this->mOldRev
=== null ||
451 ( $this->mOldRev
&& $this->mOldContent
=== null )
453 $missing[] = $this->deletedIdMarker( $this->mOldid
);
455 if ( $this->mNewRev
=== null ||
456 ( $this->mNewRev
&& $this->mNewContent
=== null )
458 $missing[] = $this->deletedIdMarker( $this->mNewid
);
461 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
462 $msg = $this->msg( 'difference-missing-revision' )
463 ->params( $this->getLanguage()->listToText( $missing ) )
464 ->numParams( count( $missing ) )
466 $out->addHTML( $msg );
469 public function showDiffPage( $diffOnly = false ) {
470 # Allow frames except in certain special cases
471 $out = $this->getOutput();
472 $out->allowClickjacking();
473 $out->setRobotPolicy( 'noindex,nofollow' );
475 // Allow extensions to add any extra output here
476 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
478 if ( !$this->loadRevisionData() ) {
479 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
480 $this->showMissingRevision();
485 $user = $this->getUser();
487 if ( $this->mNewPage
) {
488 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
490 if ( $this->mOldPage
) {
491 $permErrors = wfMergeErrorArrays( $permErrors,
492 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
494 if ( count( $permErrors ) ) {
495 throw new PermissionsError( 'read', $permErrors );
501 # Carry over 'diffonly' param via navigation links
502 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
503 $query['diffonly'] = $diffOnly;
505 # Cascade unhide param in links for easy deletion browsing
506 if ( $this->unhide
) {
507 $query['unhide'] = 1;
510 # Check if one of the revisions is deleted/suppressed
511 $deleted = $suppressed = false;
512 $allowed = $this->mNewRev
->userCan( RevisionRecord
::DELETED_TEXT
, $user );
516 # mOldRev is false if the difference engine is called with a "vague" query for
517 # a diff between a version V and its previous version V' AND the version V
518 # is the first version of that article. In that case, V' does not exist.
519 if ( $this->mOldRev
=== false ) {
520 if ( $this->mNewPage
) {
521 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
525 // Allow extensions to change the $oldHeader variable
526 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
528 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
530 if ( !$this->mOldPage ||
!$this->mNewPage
) {
531 // XXX say something to the user?
533 } elseif ( $this->mNewPage
->equals( $this->mOldPage
) ) {
534 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
537 $out->setPageTitle( $this->msg( 'difference-title-multipage',
538 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
539 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
543 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
545 if ( $samePage && $this->mNewPage
&& $permissionManager->userCan(
546 'edit', $user, $this->mNewPage
, PermissionManager
::RIGOR_QUICK
548 if ( $this->mNewRev
->isCurrent() && $permissionManager->userCan(
549 'rollback', $user, $this->mNewPage
551 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext(),
553 if ( $rollbackLink ) {
554 $out->preventClickjacking();
555 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
559 if ( $this->userCanEdit( $this->mOldRev
) &&
560 $this->userCanEdit( $this->mNewRev
)
562 $undoLink = Html
::element( 'a', [
563 'href' => $this->mNewPage
->getLocalURL( [
565 'undoafter' => $this->mOldid
,
566 'undo' => $this->mNewid
568 'title' => Linker
::titleAttrib( 'undo' ),
570 $this->msg( 'editundo' )->text()
572 $revisionTools['mw-diff-undo'] = $undoLink;
576 # Make "previous revision link"
577 if ( $samePage && $this->mOldPage
&& $this->mOldRev
->getPrevious() ) {
578 $prevlink = Linker
::linkKnown(
580 $this->msg( 'previousdiff' )->escaped(),
581 [ 'id' => 'differences-prevlink' ],
582 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
585 $prevlink = "\u{00A0}";
588 if ( $this->mOldRev
->isMinor() ) {
589 $oldminor = ChangesList
::flag( 'minor' );
594 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
595 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
596 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
598 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
599 '<div id="mw-diff-otitle2">' .
600 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
601 '<div id="mw-diff-otitle3">' . $oldminor .
602 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
603 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
604 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
606 // Allow extensions to change the $oldHeader variable
607 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
608 $diffOnly, $ldel, $this->unhide
] );
610 if ( $this->mOldRev
->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
611 $deleted = true; // old revisions text is hidden
612 if ( $this->mOldRev
->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
613 $suppressed = true; // also suppressed
617 # Check if this user can see the revisions
618 if ( !$this->mOldRev
->userCan( RevisionRecord
::DELETED_TEXT
, $user ) ) {
623 $out->addJsConfigVars( [
624 'wgDiffOldId' => $this->mOldid
,
625 'wgDiffNewId' => $this->mNewid
,
628 # Make "next revision link"
629 # Skip next link on the top revision
630 if ( $samePage && $this->mNewPage
&& !$this->mNewRev
->isCurrent() ) {
631 $nextlink = Linker
::linkKnown(
633 $this->msg( 'nextdiff' )->escaped(),
634 [ 'id' => 'differences-nextlink' ],
635 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
638 $nextlink = "\u{00A0}";
641 if ( $this->mNewRev
->isMinor() ) {
642 $newminor = ChangesList
::flag( 'minor' );
647 # Handle RevisionDelete links...
648 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
650 # Allow extensions to define their own revision tools
651 Hooks
::run( 'DiffRevisionTools',
652 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
653 $formattedRevisionTools = [];
654 // Put each one in parentheses (poor man's button)
655 foreach ( $revisionTools as $key => $tool ) {
656 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
657 $element = Html
::rawElement(
659 [ 'class' => $toolClass ],
660 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
662 $formattedRevisionTools[] = $element;
664 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
665 ' ' . implode( ' ', $formattedRevisionTools );
666 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
668 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
669 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
671 '<div id="mw-diff-ntitle3">' . $newminor .
672 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
673 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
674 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
676 // Allow extensions to change the $newHeader variable
677 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
678 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
680 if ( $this->mNewRev
->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
681 $deleted = true; // new revisions text is hidden
682 if ( $this->mNewRev
->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
683 $suppressed = true; // also suppressed
687 # If the diff cannot be shown due to a deleted revision, then output
688 # the diff header and links to unhide (if available)...
689 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
690 $this->showDiffStyle();
691 $multi = $this->getMultiNotice();
692 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
694 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
695 # Give explanation for why revision is not visible
696 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
699 # Give explanation and add a link to view the diff...
700 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
701 $link = $this->getTitle()->getFullURL( $query );
702 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
704 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
708 # Otherwise, output a regular diff...
710 # Add deletion notice if the user is viewing deleted content
713 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
714 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
715 $this->msg( $msg )->parse() .
718 $this->showDiff( $oldHeader, $newHeader, $notice );
720 $this->renderNewRevision();
726 * Build a link to mark a change as patrolled.
728 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
729 * Side effect: When the patrol link is build, this method will call
730 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
732 * @return string HTML or empty string
734 public function markPatrolledLink() {
735 if ( $this->mMarkPatrolledLink
=== null ) {
736 $linkInfo = $this->getMarkPatrolledLinkInfo();
737 // If false, there is no patrol link needed/allowed
738 if ( !$linkInfo ||
!$this->mNewPage
) {
739 $this->mMarkPatrolledLink
= '';
741 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
744 $this->msg( 'markaspatrolleddiff' )->escaped(),
747 'action' => 'markpatrolled',
748 'rcid' => $linkInfo['rcid'],
751 // Allow extensions to change the markpatrolled link
752 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
753 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
756 return $this->mMarkPatrolledLink
;
760 * Returns an array of meta data needed to build a "mark as patrolled" link and
761 * adds the mediawiki.page.patrol.ajax to the output.
763 * @return array|false An array of meta data for a patrol link (rcid only)
764 * or false if no link is needed
766 protected function getMarkPatrolledLinkInfo() {
767 $user = $this->getUser();
768 $config = $this->getConfig();
770 // Prepare a change patrol link, if applicable
772 // Is patrolling enabled and the user allowed to?
773 $config->get( 'UseRCPatrol' ) &&
774 $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
775 // Only do this if the revision isn't more than 6 hours older
776 // than the Max RC age (6h because the RC might not be cleaned out regularly)
777 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
779 // Look for an unpatrolled change corresponding to this diff
780 $db = wfGetDB( DB_REPLICA
);
781 $change = RecentChange
::newFromConds(
783 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
784 'rc_this_oldid' => $this->mNewid
,
785 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
790 if ( $change && !$change->getPerformer()->equals( $user ) ) {
791 $rcid = $change->getAttribute( 'rc_id' );
793 // None found or the page has been created by the current user.
794 // If the user could patrol this it already would be patrolled
798 // Allow extensions to possibly change the rcid here
799 // For example the rcid might be set to zero due to the user
800 // being the same as the performer of the change but an extension
801 // might still want to show it under certain conditions
802 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
806 $this->getOutput()->preventClickjacking();
807 if ( MediaWikiServices
::getInstance()->getPermissionManager()
808 ->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 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
910 // Allow extensions to optionally not show the final patrolled link
911 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
912 # Add redundant patrol link on bottom...
913 $out->addHTML( $this->markPatrolledLink() );
918 * @param WikiPage $page
919 * @param Revision $rev
921 * @return ParserOutput|bool False if the revision was not found
923 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
924 if ( !$rev->getId() ) {
925 // WikiPage::getParserOutput wants a revision ID. Passing 0 will incorrectly show
926 // the current revision, so fail instead. If need be, WikiPage::getParserOutput
927 // could be made to accept a Revision or RevisionRecord instead of the id.
931 $parserOptions = $page->makeParserOptions( $this->getContext() );
932 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
934 return $parserOutput;
938 * Get the diff text, send it to the OutputPage object
939 * Returns false if the diff could not be generated, otherwise returns true
941 * @param string|bool $otitle Header for old text or false
942 * @param string|bool $ntitle Header for new text or false
943 * @param string $notice HTML between diff header and body
947 public function showDiff( $otitle, $ntitle, $notice = '' ) {
948 // Allow extensions to affect the output here
949 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
951 $diff = $this->getDiff( $otitle, $ntitle, $notice );
952 if ( $diff === false ) {
953 $this->showMissingRevision();
957 $this->showDiffStyle();
958 $this->getOutput()->addHTML( $diff );
965 * Add style sheets for diff display.
967 public function showDiffStyle() {
968 if ( !$this->isSlotDiffRenderer
) {
969 $this->getOutput()->addModuleStyles( [
970 'mediawiki.interface.helpers.styles',
971 'mediawiki.diff.styles'
973 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
974 $slotDiffRenderer->addModules( $this->getOutput() );
980 * Get complete diff table, including header
982 * @param string|bool $otitle Header for old text or false
983 * @param string|bool $ntitle Header for new text or false
984 * @param string $notice HTML between diff header and body
988 public function getDiff( $otitle, $ntitle, $notice = '' ) {
989 $body = $this->getDiffBody();
990 if ( $body === false ) {
994 $multi = $this->getMultiNotice();
995 // Display a message when the diff is empty
996 if ( $body === '' ) {
997 $notice .= '<div class="mw-diff-empty">' .
998 $this->msg( 'diff-empty' )->parse() .
1002 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
1006 * Get the diff table body, without header
1008 * @return mixed (string/false)
1010 public function getDiffBody() {
1011 $this->mCacheHit
= true;
1012 // Check if the diff should be hidden from this user
1013 if ( !$this->isContentOverridden
) {
1014 if ( !$this->loadRevisionData() ) {
1016 } elseif ( $this->mOldRev
&&
1017 !$this->mOldRev
->userCan( RevisionRecord
::DELETED_TEXT
, $this->getUser() )
1020 } elseif ( $this->mNewRev
&&
1021 !$this->mNewRev
->userCan( RevisionRecord
::DELETED_TEXT
, $this->getUser() )
1026 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
&&
1027 $this->mOldRev
->getId() && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
1029 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
1037 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1038 if ( $this->mOldid
&& $this->mNewid
) {
1039 // Check if subclass is still using the old way
1040 // for backwards-compatibility
1041 $key = $this->getDiffBodyCacheKey();
1042 if ( $key === null ) {
1043 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
1047 if ( !$this->mRefreshCache
) {
1048 $difftext = $cache->get( $key );
1049 if ( is_string( $difftext ) ) {
1050 wfIncrStats( 'diff_cache.hit' );
1051 $difftext = $this->localiseDiff( $difftext );
1052 $difftext .= "\n<!-- diff cache key $key -->\n";
1056 } // don't try to load but save the result
1058 $this->mCacheHit
= false;
1060 // Loadtext is permission safe, this just clears out the diff
1061 if ( !$this->loadText() ) {
1066 // We've checked for revdelete at the beginning of this method; it's OK to ignore
1067 // read permissions here.
1068 $slotContents = $this->getSlotContents();
1069 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
1070 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
1071 $slotContents[$role]['new'] );
1072 if ( $slotDiff && $role !== SlotRecord
::MAIN
) {
1073 // FIXME: ask SlotRoleHandler::getSlotNameMessage
1075 $difftext .= $this->getSlotHeader( $slotTitle );
1077 $difftext .= $slotDiff;
1080 // Avoid PHP 7.1 warning from passing $this by reference
1081 $diffEngine = $this;
1083 // Save to cache for 7 days
1084 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1085 wfIncrStats( 'diff_cache.uncacheable' );
1086 } elseif ( $key !== false && $difftext !== false ) {
1087 wfIncrStats( 'diff_cache.miss' );
1088 $cache->set( $key, $difftext, 7 * 86400 );
1090 wfIncrStats( 'diff_cache.uncacheable' );
1092 // localise line numbers and title attribute text
1093 if ( $difftext !== false ) {
1094 $difftext = $this->localiseDiff( $difftext );
1101 * Get the diff table body for one slot, without header
1103 * @param string $role
1104 * @return string|false
1106 public function getDiffBodyForRole( $role ) {
1107 $diffRenderers = $this->getSlotDiffRenderers();
1108 if ( !isset( $diffRenderers[$role] ) ) {
1112 $slotContents = $this->getSlotContents();
1113 $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1114 $slotContents[$role]['new'] );
1119 if ( $role !== SlotRecord
::MAIN
) {
1120 // TODO use human-readable role name at least
1122 $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1125 return $this->localiseDiff( $slotDiff );
1129 * Get a slot header for inclusion in a diff body (as a table row).
1131 * @param string $headerText The text of the header
1135 protected function getSlotHeader( $headerText ) {
1136 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1137 $columnCount = $this->mOldRev ?
4 : 2;
1138 $userLang = $this->getLanguage()->getHtmlCode();
1139 return Html
::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1140 Html
::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1144 * Returns the cache key for diff body text or content.
1146 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1149 * @throws MWException
1150 * @return string|null
1152 protected function getDiffBodyCacheKey() {
1157 * Get the cache key parameters
1159 * Subclasses can replace the first element in the array to something
1160 * more specific to the type of diff (e.g. "inline-diff"), or append
1161 * if the cache should vary on more things. Overriding entirely should
1167 * @throws MWException
1169 protected function getDiffBodyCacheKeyParams() {
1170 if ( !$this->mOldid ||
!$this->mNewid
) {
1171 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1174 $engine = $this->getEngine();
1179 "old-{$this->mOldid}",
1180 "rev-{$this->mNewid}"
1183 if ( $engine === 'wikidiff2' ) {
1184 $params[] = phpversion( 'wikidiff2' );
1187 if ( !$this->isSlotDiffRenderer
) {
1188 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1189 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1197 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1198 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1200 * @internal for use by DifferenceEngineSlotDiffRenderer only
1203 public function getExtraCacheKeys() {
1204 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1205 // about special things, not the revision IDs, which are added to the cache key by the
1206 // page-level DifferenceEngine, and which might not have a valid value for this object.
1207 $this->mOldid
= 123456789;
1208 $this->mNewid
= 987654321;
1210 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1211 $cacheString = $this->getDiffBodyCacheKey();
1212 if ( $cacheString ) {
1213 return [ $cacheString ];
1216 $params = $this->getDiffBodyCacheKeyParams();
1218 // Try to get rid of the standard keys to keep the cache key human-readable:
1219 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1220 // the child class includes the same keys, drop them.
1221 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1222 // as long as we are already in a non-static method of the same class, and the call context
1223 // ($this) will be inherited.
1224 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1225 $standardParams = DifferenceEngine
::getDiffBodyCacheKeyParams();
1226 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1227 $params = array_slice( $params, count( $standardParams ) );
1234 * Generate a diff, no caching.
1238 * @param Content $old Old content
1239 * @param Content $new New content
1241 * @throws Exception If old or new content is not an instance of TextContent.
1242 * @return bool|string
1244 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1246 public function generateContentDiffBody( Content
$old, Content
$new ) {
1247 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1249 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1250 && $this->isSlotDiffRenderer
1252 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1253 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1254 // This will happen when a content model has no custom slot diff renderer, it does have
1255 // a custom difference engine, but that does not override this method.
1256 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1257 . 'Please use a SlotDiffRenderer.' );
1259 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1263 * Generate a diff, no caching
1265 * @param string $otext Old text, must be already segmented
1266 * @param string $ntext New text, must be already segmented
1268 * @throws Exception If content handling for text content is configured in a way
1269 * that makes maintaining B/C hard.
1270 * @return bool|string
1272 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1274 public function generateTextDiffBody( $otext, $ntext ) {
1275 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1276 ->getSlotDiffRenderer( $this->getContext() );
1277 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1278 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1279 // This is too unlikely to happen to bother handling properly.
1280 throw new Exception( 'The slot diff renderer for text content should be a '
1281 . 'TextSlotDiffRenderer subclass' );
1283 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1287 * Process $wgExternalDiffEngine and get a sane, usable engine
1289 * @return bool|string 'wikidiff2', path to an executable, or false
1290 * @internal For use by this class and TextSlotDiffRenderer only.
1292 public static function getEngine() {
1293 global $wgExternalDiffEngine;
1294 // We use the global here instead of Config because we write to the value,
1295 // and Config is not mutable.
1296 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
1297 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1298 $wgExternalDiffEngine = false;
1299 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1300 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1301 $wgExternalDiffEngine = false;
1302 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1303 // And prevent people from shooting themselves in the foot...
1304 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1305 $wgExternalDiffEngine = false;
1308 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1309 return $wgExternalDiffEngine;
1310 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1319 * Generates diff, to be wrapped internally in a logging/instrumentation
1321 * @param string $otext Old text, must be already segmented
1322 * @param string $ntext New text, must be already segmented
1324 * @throws Exception If content handling for text content is configured in a way
1325 * that makes maintaining B/C hard.
1326 * @return bool|string
1328 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1330 protected function textDiff( $otext, $ntext ) {
1331 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1332 ->getSlotDiffRenderer( $this->getContext() );
1333 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1334 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1335 // This is too unlikely to happen to bother handling properly.
1336 throw new Exception( 'The slot diff renderer for text content should be a '
1337 . 'TextSlotDiffRenderer subclass' );
1339 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1343 * Generate a debug comment indicating diff generating time,
1344 * server node, and generator backend.
1346 * @param string $generator : What diff engine was used
1350 protected function debug( $generator = "internal" ) {
1351 if ( !$this->enableDebugComment
) {
1354 $data = [ $generator ];
1355 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1356 $data[] = wfHostname();
1358 $data[] = wfTimestamp( TS_DB
);
1360 return "<!-- diff generator: " .
1361 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1365 private function getDebugString() {
1366 $engine = self
::getEngine();
1367 if ( $engine === 'wikidiff2' ) {
1368 return $this->debug( 'wikidiff2' );
1369 } elseif ( $engine === false ) {
1370 return $this->debug( 'native PHP' );
1372 return $this->debug( "external $engine" );
1377 * Localise diff output
1379 * @param string $text
1382 private function localiseDiff( $text ) {
1383 $text = $this->localiseLineNumbers( $text );
1384 if ( $this->getEngine() === 'wikidiff2' &&
1385 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1387 $text = $this->addLocalisedTitleTooltips( $text );
1393 * Replace line numbers with the text in the user's language
1395 * @param string $text
1399 public function localiseLineNumbers( $text ) {
1400 return preg_replace_callback(
1401 '/<!--LINE (\d+)-->/',
1402 [ $this, 'localiseLineNumbersCb' ],
1407 public function localiseLineNumbersCb( $matches ) {
1408 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1412 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1416 * Add title attributes for tooltips on moved paragraph indicators
1418 * @param string $text
1421 private function addLocalisedTitleTooltips( $text ) {
1422 return preg_replace_callback(
1423 '/class="mw-diff-movedpara-(left|right)"/',
1424 [ $this, 'addLocalisedTitleTooltipsCb' ],
1430 * @param array $matches
1433 private function addLocalisedTitleTooltipsCb( array $matches ) {
1434 $key = $matches[1] === 'right' ?
1435 'diff-paragraph-moved-toold' :
1436 'diff-paragraph-moved-tonew';
1437 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1441 * If there are revisions between the ones being compared, return a note saying so.
1445 public function getMultiNotice() {
1446 // The notice only make sense if we are diffing two saved revisions of the same page.
1448 !$this->mOldRev ||
!$this->mNewRev
1449 ||
!$this->mOldPage ||
!$this->mNewPage
1450 ||
!$this->mOldPage
->equals( $this->mNewPage
)
1455 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1456 $oldRev = $this->mNewRev
; // flip
1457 $newRev = $this->mOldRev
; // flip
1458 } else { // normal case
1459 $oldRev = $this->mOldRev
;
1460 $newRev = $this->mNewRev
;
1463 // Sanity: don't show the notice if too many rows must be scanned
1464 // @todo show some special message for that case
1465 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1466 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1467 $limit = 100; // use diff-multi-manyusers if too many users
1468 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1469 $numUsers = count( $users );
1471 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( RevisionRecord
::RAW
) ) {
1472 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1475 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1482 * Get a notice about how many intermediate edits and users there are
1484 * @param int $numEdits
1485 * @param int $numUsers
1490 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1491 if ( $numUsers === 0 ) {
1492 $msg = 'diff-multi-sameuser';
1493 } elseif ( $numUsers > $limit ) {
1494 $msg = 'diff-multi-manyusers';
1497 $msg = 'diff-multi-otherusers';
1500 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1504 * @param Revision $rev
1505 * @return bool whether the user can see and edit the revision.
1507 private function userCanEdit( Revision
$rev ) {
1508 $user = $this->getUser();
1510 if ( !$rev->getContentHandler()->supportsDirectEditing() ) {
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 = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1561 $msg = $this->msg( $key )->escaped();
1562 $editLink = $this->msg( 'parentheses' )->rawParams(
1563 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1564 $header .= ' ' . Html
::rawElement(
1566 [ 'class' => 'mw-diff-edit' ],
1569 if ( $rev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
1570 $header = Html
::rawElement(
1572 [ 'class' => 'history-deleted' ],
1577 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1584 * Add the header to a diff body
1586 * @param string $diff Diff body
1587 * @param string $otitle Old revision header
1588 * @param string $ntitle New revision header
1589 * @param string $multi Notice telling user that there are intermediate
1590 * revisions between the ones being compared
1591 * @param string $notice Other notices, e.g. that user is viewing deleted content
1595 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1596 // shared.css sets diff in interface language/dir, but the actual content
1597 // is often in a different language, mostly the page content language/dir
1598 $header = Html
::openElement( 'table', [
1599 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1600 'data-mw' => 'interface',
1602 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1604 if ( !$diff && !$otitle ) {
1606 <tr class=\"diff-title\" lang=\"{$userLang}\">
1607 <td class=\"diff-ntitle\">{$ntitle}</td>
1611 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1613 <col class=\"diff-marker\" />
1614 <col class=\"diff-content\" />
1615 <col class=\"diff-marker\" />
1616 <col class=\"diff-content\" />";
1623 if ( $otitle ||
$ntitle ) {
1625 <tr class=\"diff-title\" lang=\"{$userLang}\">
1626 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1627 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1632 if ( $multi != '' ) {
1633 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1634 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1636 if ( $notice != '' ) {
1637 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1638 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1641 return $header . $diff . "</table>";
1645 * Use specified text instead of loading from the database
1646 * @param Content $oldContent
1647 * @param Content $newContent
1649 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1651 public function setContent( Content
$oldContent, Content
$newContent ) {
1652 $this->mOldContent
= $oldContent;
1653 $this->mNewContent
= $newContent;
1655 $this->mTextLoaded
= 2;
1656 $this->mRevisionsLoaded
= true;
1657 $this->isContentOverridden
= true;
1658 $this->slotDiffRenderers
= null;
1662 * Use specified text instead of loading from the database.
1663 * @param RevisionRecord|null $oldRevision
1664 * @param RevisionRecord $newRevision
1666 public function setRevisions(
1667 RevisionRecord
$oldRevision = null, RevisionRecord
$newRevision
1669 if ( $oldRevision ) {
1670 $this->mOldRev
= new Revision( $oldRevision );
1671 $this->mOldid
= $oldRevision->getId();
1672 $this->mOldPage
= Title
::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1673 // This method is meant for edit diffs and such so there is no reason to provide a
1674 // revision that's not readable to the user, but check it just in case.
1675 $this->mOldContent
= $oldRevision->getContent( SlotRecord
::MAIN
,
1676 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1678 $this->mOldPage
= null;
1679 $this->mOldRev
= $this->mOldid
= false;
1681 $this->mNewRev
= new Revision( $newRevision );
1682 $this->mNewid
= $newRevision->getId();
1683 $this->mNewPage
= Title
::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1684 $this->mNewContent
= $newRevision->getContent( SlotRecord
::MAIN
,
1685 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1687 $this->mRevisionsIdsLoaded
= $this->mRevisionsLoaded
= true;
1688 $this->mTextLoaded
= $oldRevision ?
2 : 1;
1689 $this->isContentOverridden
= false;
1690 $this->slotDiffRenderers
= null;
1694 * Set the language in which the diff text is written
1696 * @param Language $lang
1699 public function setTextLanguage( Language
$lang ) {
1700 $this->mDiffLang
= $lang;
1704 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1705 * to a pair of actual integers representing revision ids.
1707 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1708 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1710 * @return array List of two revision ids, older first, later second.
1711 * Zero signifies invalid argument passed.
1712 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1714 public function mapDiffPrevNext( $old, $new ) {
1715 if ( $new === 'prev' ) {
1716 // Show diff between revision $old and the previous one. Get previous one from DB.
1717 $newid = intval( $old );
1718 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1719 } elseif ( $new === 'next' ) {
1720 // Show diff between revision $old and the next one. Get next one from DB.
1721 $oldid = intval( $old );
1722 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1724 $oldid = intval( $old );
1725 $newid = intval( $new );
1728 return [ $oldid, $newid ];
1734 private function loadRevisionIds() {
1735 if ( $this->mRevisionsIdsLoaded
) {
1739 $this->mRevisionsIdsLoaded
= true;
1741 $old = $this->mOldid
;
1742 $new = $this->mNewid
;
1744 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1745 if ( $new === 'next' && $this->mNewid
=== false ) {
1746 # if no result, NewId points to the newest old revision. The only newer
1747 # revision is cur, which is "0".
1752 'NewDifferenceEngine',
1753 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1758 * Load revision metadata for the specified revisions. If newid is 0, then compare
1759 * the old revision in oldid to the current revision of the current page (as defined
1760 * by the request context); if oldid is 0, then compare the revision in newid to the
1761 * immediately previous one.
1763 * If oldid is false, leave the corresponding revision object set to false. This can
1764 * happen with 'diff=prev' pointing to a non-existent revision, and is also used directly
1767 * @return bool Whether both revisions were loaded successfully. Setting mOldRev
1768 * to false counts as successful loading.
1770 public function loadRevisionData() {
1771 if ( $this->mRevisionsLoaded
) {
1772 return $this->isContentOverridden ||
( $this->mOldRev
!== null && $this->mNewRev
!== null );
1775 // Whether it succeeds or fails, we don't want to try again
1776 $this->mRevisionsLoaded
= true;
1778 $this->loadRevisionIds();
1780 // Load the new revision object
1781 if ( $this->mNewid
) {
1782 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1784 $this->mNewRev
= Revision
::newFromTitle(
1787 Revision
::READ_NORMAL
1791 if ( !$this->mNewRev
instanceof Revision
) {
1795 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1796 $this->mNewid
= $this->mNewRev
->getId();
1797 if ( $this->mNewid
) {
1798 $this->mNewPage
= $this->mNewRev
->getTitle();
1800 $this->mNewPage
= null;
1803 // Load the old revision object
1804 $this->mOldRev
= false;
1805 if ( $this->mOldid
) {
1806 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1807 } elseif ( $this->mOldid
=== 0 ) {
1808 $rev = $this->mNewRev
->getPrevious();
1810 $this->mOldid
= $rev->getId();
1811 $this->mOldRev
= $rev;
1813 // No previous revision; mark to show as first-version only.
1814 $this->mOldid
= false;
1815 $this->mOldRev
= false;
1817 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1819 if ( is_null( $this->mOldRev
) ) {
1823 if ( $this->mOldRev
&& $this->mOldRev
->getId() ) {
1824 $this->mOldPage
= $this->mOldRev
->getTitle();
1826 $this->mOldPage
= null;
1829 // Load tags information for both revisions
1830 $dbr = wfGetDB( DB_REPLICA
);
1831 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
1832 if ( $this->mOldid
!== false ) {
1833 $tagIds = $dbr->selectFieldValues(
1836 [ 'ct_rev_id' => $this->mOldid
],
1840 foreach ( $tagIds as $tagId ) {
1842 $tags[] = $changeTagDefStore->getName( (int)$tagId );
1843 } catch ( NameTableAccessException
$exception ) {
1847 $this->mOldTags
= implode( ',', $tags );
1849 $this->mOldTags
= false;
1852 $tagIds = $dbr->selectFieldValues(
1855 [ 'ct_rev_id' => $this->mNewid
],
1859 foreach ( $tagIds as $tagId ) {
1861 $tags[] = $changeTagDefStore->getName( (int)$tagId );
1862 } catch ( NameTableAccessException
$exception ) {
1866 $this->mNewTags
= implode( ',', $tags );
1872 * Load the text of the revisions, as well as revision data.
1873 * When the old revision is missing (mOldRev is false), loading mOldContent is not attempted.
1875 * @return bool Whether the content of both revisions could be loaded successfully.
1876 * (When mOldRev is false, that still counts as a success.)
1879 public function loadText() {
1880 if ( $this->mTextLoaded
== 2 ) {
1881 return $this->loadRevisionData() && ( $this->mOldRev
=== false ||
$this->mOldContent
)
1882 && $this->mNewContent
;
1885 // Whether it succeeds or fails, we don't want to try again
1886 $this->mTextLoaded
= 2;
1888 if ( !$this->loadRevisionData() ) {
1892 if ( $this->mOldRev
) {
1893 $this->mOldContent
= $this->mOldRev
->getContent(
1894 RevisionRecord
::FOR_THIS_USER
, $this->getUser()
1896 if ( $this->mOldContent
=== null ) {
1901 $this->mNewContent
= $this->mNewRev
->getContent(
1902 RevisionRecord
::FOR_THIS_USER
, $this->getUser()
1904 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1905 if ( $this->mNewContent
=== null ) {
1913 * Load the text of the new revision, not the old one
1915 * @return bool Whether the content of the new revision could be loaded successfully.
1917 public function loadNewText() {
1918 if ( $this->mTextLoaded
>= 1 ) {
1919 return $this->loadRevisionData();
1922 $this->mTextLoaded
= 1;
1924 if ( !$this->loadRevisionData() ) {
1928 $this->mNewContent
= $this->mNewRev
->getContent(
1929 RevisionRecord
::FOR_THIS_USER
, $this->getUser()
1932 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );