Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
83.86% covered (warning)
83.86%
904 / 1078
41.43% covered (danger)
41.43%
29 / 70
CRAP
0.00% covered (danger)
0.00%
0 / 1
DifferenceEngine
83.86% covered (warning)
83.86%
904 / 1078
41.43% covered (danger)
41.43%
29 / 70
758.02
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
2
 getSlotDiffRenderers
86.36% covered (warning)
86.36%
19 / 22
0.00% covered (danger)
0.00%
0 / 1
11.31
 markAsSlotDiffRenderer
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getSlotContents
96.15% covered (success)
96.15%
25 / 26
0.00% covered (danger)
0.00%
0 / 1
6
 loadSingleSlot
50.00% covered (danger)
50.00%
3 / 6
0.00% covered (danger)
0.00%
0 / 1
4.12
 addRevisionLoadError
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getRevisionLoadErrors
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 hasNewRevisionLoadError
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
4.12
 getTitle
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 setReducedLineNumbers
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getDiffLang
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getDefaultLanguage
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 wasCacheHit
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getOldid
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getNewid
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getOldRevision
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getNewRevision
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 deletedLink
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
7.23
 deletedIdMarker
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 showMissingRevision
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
6.02
 hasDeletedRevision
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 authorizeView
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 hasSuppressedRevision
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 getUserEditCount
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
2.00
 getUserRoles
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 getUserMetaData
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 isUserAllowedToSeeRevisions
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 shouldBeHiddenFromUser
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 showDiffPage
93.55% covered (success)
93.55%
203 / 217
0.00% covered (danger)
0.00%
0 / 1
43.50
 showTablePrefixes
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 markPatrolledLink
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
4
 getMarkPatrolledLinkInfo
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
8
 revisionDeleteLink
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
2.01
 renderNewRevision
77.36% covered (warning)
77.36%
41 / 53
0.00% covered (danger)
0.00%
0 / 1
12.40
 showDiff
70.00% covered (warning)
70.00%
7 / 10
0.00% covered (danger)
0.00%
0 / 1
3.24
 showDiffStyle
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 getDiff
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
4.10
 incrementStats
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getDiffBody
84.75% covered (warning)
84.75%
50 / 59
0.00% covered (danger)
0.00%
0 / 1
26.04
 getDiffBodyForRole
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 getSlotHeader
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getSlotError
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getDiffBodyCacheKeyParams
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
5.01
 getExtraCacheKeys
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 setSlotDiffOptions
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
5.93
 setExtraQueryParams
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 generateContentDiffBody
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 generateTextDiffBody
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
2.09
 getEngine
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
2.15
 debug
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
7.23
 getDebugString
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
3.33
 localiseDiff
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 localiseLineNumbers
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 getMultiNotice
42.86% covered (danger)
42.86%
21 / 49
0.00% covered (danger)
0.00%
0 / 1
103.29
 intermediateEditsMsg
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 userCanEdit
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getRevisionHeader
100.00% covered (success)
100.00%
47 / 47
100.00% covered (success)
100.00%
1 / 1
7
 addHeader
95.12% covered (success)
95.12%
39 / 41
0.00% covered (danger)
0.00%
0 / 1
8
 setContent
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 setRevisions
90.48% covered (success)
90.48%
19 / 21
0.00% covered (danger)
0.00%
0 / 1
5.02
 setTextLanguage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 mapDiffPrevNext
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
7
 loadRevisionIds
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
4.02
 loadRevisionData
81.13% covered (warning)
81.13%
43 / 53
0.00% covered (danger)
0.00%
0 / 1
20.18
 loadText
87.50% covered (warning)
87.50%
21 / 24
0.00% covered (danger)
0.00%
0 / 1
9.16
 loadNewText
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
3.01
 getTextDiffer
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 getSupportedFormats
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getTextDiffFormat
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getMobileFooter
98.61% covered (success)
98.61%
71 / 72
0.00% covered (danger)
0.00%
0 / 1
7
1<?php
2/**
3 * User interface for the difference engine.
4 *
5 * @license GPL-2.0-or-later
6 *
7 * @file
8 * @ingroup DifferenceEngine
9 */
10
11use MediaWiki\ChangeTags\ChangeTags;
12use MediaWiki\CommentFormatter\CommentFormatter;
13use MediaWiki\Content\Content;
14use MediaWiki\Content\IContentHandlerFactory;
15use MediaWiki\Context\ContextSource;
16use MediaWiki\Context\IContextSource;
17use MediaWiki\Debug\DeprecationHelper;
18use MediaWiki\Diff\TextDiffer\ManifoldTextDiffer;
19use MediaWiki\Exception\PermissionsError;
20use MediaWiki\HookContainer\HookRunner;
21use MediaWiki\Html\Html;
22use MediaWiki\Language\Language;
23use MediaWiki\Linker\Linker;
24use MediaWiki\Linker\LinkRenderer;
25use MediaWiki\MainConfigNames;
26use MediaWiki\MediaWikiServices;
27use MediaWiki\Message\Message;
28use MediaWiki\Page\ParserOutputAccess;
29use MediaWiki\Page\WikiPageFactory;
30use MediaWiki\Permissions\Authority;
31use MediaWiki\Permissions\PermissionStatus;
32use MediaWiki\RecentChanges\ChangesList;
33use MediaWiki\RecentChanges\RecentChange;
34use MediaWiki\RecentChanges\RecentChangeLookup;
35use MediaWiki\Revision\ArchivedRevisionLookup;
36use MediaWiki\Revision\BadRevisionException;
37use MediaWiki\Revision\RevisionRecord;
38use MediaWiki\Revision\RevisionStore;
39use MediaWiki\Revision\SlotRecord;
40use MediaWiki\SpecialPage\SpecialPage;
41use MediaWiki\Storage\NameTableAccessException;
42use MediaWiki\Title\Title;
43use MediaWiki\User\Options\UserOptionsLookup;
44use MediaWiki\User\UserEditTracker;
45use MediaWiki\User\UserGroupManager;
46use MediaWiki\User\UserGroupMembership;
47use MediaWiki\User\UserIdentity;
48use MediaWiki\User\UserIdentityUtils;
49use Wikimedia\Rdbms\IConnectionProvider;
50
51/**
52 * DifferenceEngine is responsible for rendering the difference between two revisions as HTML.
53 * This includes interpreting URL parameters, retrieving revision data, checking access permissions,
54 * selecting and invoking the diff generator class for the individual slots, doing post-processing
55 * on the generated diff, adding the rest of the HTML (such as headers) and writing the whole thing
56 * to OutputPage.
57 *
58 * DifferenceEngine can be subclassed by extensions, by customizing
59 * ContentHandler::createDifferenceEngine; the content handler will be selected based on the
60 * content model of the main slot (of the new revision, when the two are different).
61 * That might change after PageTypeHandler gets introduced.
62 *
63 * In the past, the class was also used for slot-level diff generation, and extensions might still
64 * subclass it and add such functionality. When that is the case (specifically, when a
65 * ContentHandler returns a standard SlotDiffRenderer but a nonstandard DifferenceEngine)
66 * DifferenceEngineSlotDiffRenderer will be used to convert the old behavior into the new one.
67 *
68 * @ingroup DifferenceEngine
69 *
70 * @todo This class is huge and poorly defined. It should be split into a controller responsible
71 * for interpreting query parameters, retrieving data and checking permissions; and a HTML renderer.
72 */
73class DifferenceEngine extends ContextSource {
74
75    use DeprecationHelper;
76
77    /**
78     * Constant to indicate diff cache compatibility.
79     * Bump this when changing the diff formatting in a way that
80     * fixes important bugs or such to force cached diff views to
81     * clear.
82     */
83    private const DIFF_VERSION = '1.41';
84
85    /**
86     * Revision ID for the old revision. 0 for the revision previous to $mNewid, false
87     * if the diff does not have an old revision (e.g. 'oldid=<first revision of page>&diff=prev'),
88     * or the revision does not exist, null if the revision is unsaved.
89     * @var int|false|null
90     */
91    protected $mOldid;
92
93    /**
94     * Revision ID for the new revision. 0 for the last revision of the current page
95     * (as defined by the request context), false if the revision does not exist, null
96     * if it is unsaved, or an alias such as 'next'.
97     * @var int|string|false|null
98     */
99    protected $mNewid;
100
101    /**
102     * Old revision (left pane).
103     * Allowed to be an unsaved revision, unlikely that's ever needed though.
104     * False when the old revision does not exist; this can happen when using
105     * diff=prev on the first revision. Null when the revision should exist but
106     * doesn't (e.g. load failure); loadRevisionData() will return false in that
107     * case. Also null until lazy-loaded. Ignored completely when isContentOverridden
108     * is set.
109     * @var RevisionRecord|null|false
110     */
111    private $mOldRevisionRecord;
112
113    /**
114     * New revision (right pane).
115     * Note that this might be an unsaved revision (e.g. for edit preview).
116     * Null in case of load failure; diff methods will just return an error message in that case,
117     * and loadRevisionData() will return false. Also null until lazy-loaded. Ignored completely
118     * when isContentOverridden is set.
119     * @var RevisionRecord|null
120     */
121    private $mNewRevisionRecord;
122
123    /**
124     * Title of old revision or null if the old revision does not exist or does not belong to a page.
125     * @var Title|null
126     */
127    protected $mOldPage;
128
129    /**
130     * Title of new revision or null if the new revision does not exist or does not belong to a page.
131     * @var Title|null
132     */
133    protected $mNewPage;
134
135    /**
136     * Change tags of old revision or null if it does not exist / is not saved.
137     * @var string|false|null
138     */
139    private $mOldTags;
140
141    /**
142     * Change tags of new revision or null if it does not exist / is not saved.
143     * @var string|null
144     */
145    private $mNewTags;
146
147    /**
148     * @var Content|null
149     * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
150     *   This property is set to the content of the main slot, but not actually used for the main diff.
151     */
152    private $mOldContent;
153
154    /**
155     * @var Content|null
156     * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
157     *   This property is set to the content of the main slot, but not actually used for the main diff.
158     */
159    private $mNewContent;
160
161    /** @var Language */
162    protected $mDiffLang;
163
164    /** @var bool Have the revisions IDs been loaded */
165    private $mRevisionsIdsLoaded = false;
166
167    /** @var bool Have the revisions been loaded */
168    protected $mRevisionsLoaded = false;
169
170    /** @var int How many text blobs have been loaded, 0, 1 or 2? */
171    protected $mTextLoaded = 0;
172
173    /**
174     * Was the content overridden via setContent()?
175     * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
176     * and only mOldContent and mNewContent is reliable.
177     * (Note that setRevisions() does not set this flag as in that case all properties are
178     * overridden and remain consistent with each other, so no special handling is needed.)
179     * @var bool
180     */
181    protected $isContentOverridden = false;
182
183    /** @var bool Was the diff fetched from cache? */
184    protected $mCacheHit = false;
185
186    /** @var string|null Cache key if the diff was fetched from cache */
187    private $cacheHitKey = null;
188
189    /**
190     * Set this to true to add debug info to the HTML output.
191     * Warning: this may cause RSS readers to spuriously mark articles as "new"
192     * (T22601)
193     * @var bool
194     */
195    public $enableDebugComment = false;
196
197    /** @var bool If true, line X is not displayed when X is 1, for example
198     *    to increase readability and conserve space with many small diffs.
199     */
200    protected $mReducedLineNumbers = false;
201
202    /** @var string Link to action=markpatrolled */
203    protected $mMarkPatrolledLink = null;
204
205    /** @var bool Show rev_deleted content if allowed */
206    protected $unhide = false;
207
208    /** @var bool Refresh the diff cache */
209    protected $mRefreshCache = false;
210
211    /** @var SlotDiffRenderer[]|null DifferenceEngine classes for the slots, keyed by role name. */
212    protected $slotDiffRenderers = null;
213
214    /**
215     * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
216     * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
217     * $slotDiffRenderers should not be used.
218     * @var bool
219     */
220    protected $isSlotDiffRenderer = false;
221
222    /**
223     * A set of options that will be passed to the SlotDiffRenderer upon creation
224     * @var array
225     */
226    private $slotDiffOptions = [];
227
228    /**
229     * Extra query parameters to be appended to diff page links
230     * @var array
231     */
232    private $extraQueryParams = [];
233
234    /** @var ManifoldTextDiffer|null */
235    private $textDiffer;
236
237    protected LinkRenderer $linkRenderer;
238    private IContentHandlerFactory $contentHandlerFactory;
239    private RevisionStore $revisionStore;
240    private ArchivedRevisionLookup $archivedRevisionLookup;
241    private HookRunner $hookRunner;
242    private WikiPageFactory $wikiPageFactory;
243    private UserOptionsLookup $userOptionsLookup;
244    private CommentFormatter $commentFormatter;
245    private IConnectionProvider $dbProvider;
246    private UserGroupManager $userGroupManager;
247    private UserEditTracker $userEditTracker;
248    private UserIdentityUtils $userIdentityUtils;
249    private RecentChangeLookup $recentChangeLookup;
250
251    /** @var Message[] */
252    private $revisionLoadErrors = [];
253
254    /**
255     * @param IContextSource|null $context Context to use, anything else will be ignored
256     * @param int $old Old ID we want to show and diff with.
257     * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
258     * @param int $rcid Deprecated, no longer used!
259     * @param bool $refreshCache If set, refreshes the diff cache
260     * @param bool $unhide If set, allow viewing deleted revs
261     */
262    public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
263        $refreshCache = false, $unhide = false
264    ) {
265        if ( $context instanceof IContextSource ) {
266            $this->setContext( $context );
267        }
268
269        wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'" );
270
271        $this->mOldid = $old;
272        $this->mNewid = $new;
273        $this->mRefreshCache = $refreshCache;
274        $this->unhide = $unhide;
275
276        $services = MediaWikiServices::getInstance();
277        $this->linkRenderer = $services->getLinkRenderer();
278        $this->contentHandlerFactory = $services->getContentHandlerFactory();
279        $this->revisionStore = $services->getRevisionStore();
280        $this->archivedRevisionLookup = $services->getArchivedRevisionLookup();
281        $this->hookRunner = new HookRunner( $services->getHookContainer() );
282        $this->wikiPageFactory = $services->getWikiPageFactory();
283        $this->userOptionsLookup = $services->getUserOptionsLookup();
284        $this->commentFormatter = $services->getCommentFormatter();
285        $this->dbProvider = $services->getConnectionProvider();
286        $this->userGroupManager = $services->getUserGroupManager();
287        $this->userEditTracker = $services->getUserEditTracker();
288        $this->userIdentityUtils = $services->getUserIdentityUtils();
289        $this->recentChangeLookup = $services->getRecentChangeLookup();
290    }
291
292    /**
293     * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
294     *   Includes slots only present in one of the revisions. Does not include slots
295     *   for which content is identical in the two revisions.
296     */
297    protected function getSlotDiffRenderers() {
298        if ( $this->isSlotDiffRenderer ) {
299            throw new LogicException( __METHOD__ . ' called in slot diff renderer mode' );
300        }
301
302        if ( $this->slotDiffRenderers === null ) {
303            if ( !$this->loadRevisionData() ) {
304                return [];
305            }
306
307            $slotContents = $this->getSlotContents();
308            $this->slotDiffRenderers = [];
309            foreach ( $slotContents as $role => $contents ) {
310                if ( $contents['new'] && $contents['old']
311                    && $contents['new']->equals( $contents['old'] )
312                ) {
313                    // Do not produce a diff of identical content
314                    continue;
315                }
316                if ( !$contents['new'] && !$contents['old'] ) {
317                    // Nothing to diff (i.e both revisions are corrupted), just ignore
318                    continue;
319                }
320                $handler = ( $contents['new'] ?: $contents['old'] )->getContentHandler();
321                $this->slotDiffRenderers[$role] = $handler->getSlotDiffRenderer(
322                    $this->getContext(),
323                    $this->slotDiffOptions + [
324                        'contentLanguage' => $this->getDiffLang()->getCode(),
325                        'textDiffer' => $this->getTextDiffer()
326                    ]
327                );
328            }
329        }
330
331        return $this->slotDiffRenderers;
332    }
333
334    /**
335     * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
336     * This is used in legacy mode when the DifferenceEngine is wrapped in a
337     * DifferenceEngineSlotDiffRenderer.
338     * @internal For use by DifferenceEngineSlotDiffRenderer only.
339     */
340    public function markAsSlotDiffRenderer() {
341        $this->isSlotDiffRenderer = true;
342    }
343
344    /**
345     * Get the old and new content objects for all slots.
346     * This method does not do any permission checks.
347     * @return (Content|null)[][] [ role => [ 'old' => Content|null, 'new' => Content|null ], ... ]
348     */
349    protected function getSlotContents() {
350        if ( $this->isContentOverridden ) {
351            return [
352                SlotRecord::MAIN => [ 'old' => $this->mOldContent, 'new' => $this->mNewContent ]
353            ];
354        } elseif ( !$this->loadRevisionData() ) {
355            return [];
356        }
357
358        $newSlots = $this->mNewRevisionRecord->getPrimarySlots()->getSlots();
359        $oldSlots = $this->mOldRevisionRecord ?
360            $this->mOldRevisionRecord->getPrimarySlots()->getSlots() :
361            [];
362        // The order here will determine the visual order of the diff. The current logic is
363        // slots of the new revision first in natural order, then deleted ones. This is ad hoc
364        // and should not be relied on - in the future we may want the ordering to depend
365        // on the page type.
366        $roles = array_keys( array_merge( $newSlots, $oldSlots ) );
367
368        $slots = [];
369        foreach ( $roles as $role ) {
370            $slots[$role] = [
371                'old' => $this->loadSingleSlot(
372                    $oldSlots[$role] ?? null,
373                    'old'
374                ),
375                'new' => $this->loadSingleSlot(
376                    $newSlots[$role] ?? null,
377                    'new'
378                )
379            ];
380        }
381        // move main slot to front
382        if ( isset( $slots[SlotRecord::MAIN] ) ) {
383            $slots = [ SlotRecord::MAIN => $slots[SlotRecord::MAIN] ] + $slots;
384        }
385        return $slots;
386    }
387
388    /**
389     * Load the content of a single slot record
390     *
391     * @param SlotRecord|null $slot
392     * @param string $which "new" or "old"
393     * @return Content|null
394     */
395    private function loadSingleSlot( ?SlotRecord $slot, string $which ) {
396        if ( !$slot ) {
397            return null;
398        }
399        try {
400            return $slot->getContent();
401        } catch ( BadRevisionException ) {
402            $this->addRevisionLoadError( $which );
403            return null;
404        }
405    }
406
407    /**
408     * Set a message to show as a notice at the top of the page
409     *
410     * @param string $which "new" or "old"
411     */
412    private function addRevisionLoadError( $which ) {
413        $this->revisionLoadErrors[] = $this->msg( $which === 'new'
414            ? 'difference-bad-new-revision' : 'difference-bad-old-revision'
415        );
416    }
417
418    /**
419     * If errors were encountered while loading the revision contents, this
420     * will return an array of Messages describing the errors.
421     *
422     * @return Message[]
423     */
424    public function getRevisionLoadErrors() {
425        return $this->revisionLoadErrors;
426    }
427
428    /**
429     * Determine whether there was an error loading the new revision
430     * @return bool
431     */
432    private function hasNewRevisionLoadError() {
433        foreach ( $this->revisionLoadErrors as $error ) {
434            if ( $error->getKey() === 'difference-bad-new-revision' ) {
435                return true;
436            }
437        }
438        return false;
439    }
440
441    /** @inheritDoc */
442    public function getTitle() {
443        // T202454 avoid errors when there is no title
444        return parent::getTitle() ?: Title::makeTitle( NS_SPECIAL, 'BadTitle/DifferenceEngine' );
445    }
446
447    /**
448     * Set reduced line numbers mode.
449     * When set, line X is not displayed when X is 1, for example to increase readability and
450     * conserve space with many small diffs.
451     * @param bool $value
452     */
453    public function setReducedLineNumbers( $value = true ) {
454        $this->mReducedLineNumbers = $value;
455    }
456
457    /**
458     * Get the language in which the diff text is written
459     *
460     * @return Language
461     */
462    public function getDiffLang() {
463        # Default language in which the diff text is written.
464        $this->mDiffLang ??= $this->getDefaultLanguage();
465        return $this->mDiffLang;
466    }
467
468    /**
469     * Get the language to use if none has been set by setTextLanguage().
470     * Wikibase overrides this to use the user language.
471     *
472     * @return Language
473     */
474    protected function getDefaultLanguage() {
475        return $this->getTitle()->getPageLanguage();
476    }
477
478    /**
479     * @return bool
480     */
481    public function wasCacheHit() {
482        return $this->mCacheHit;
483    }
484
485    /**
486     * Get the ID of old revision (left pane) of the diff. 0 for the revision
487     * previous to getNewid(), false if the old revision does not exist, null
488     * if it's unsaved.
489     * To get a real revision ID instead of 0, call loadRevisionData() first.
490     * @return int|false|null
491     */
492    public function getOldid() {
493        $this->loadRevisionIds();
494
495        return $this->mOldid;
496    }
497
498    /**
499     * Get the ID of new revision (right pane) of the diff. 0 for the current revision,
500     * false if the new revision does not exist, null if it's unsaved.
501     * To get a real revision ID instead of 0, call loadRevisionData() first.
502     * @return int|false|null
503     */
504    public function getNewid() {
505        $this->loadRevisionIds();
506
507        return $this->mNewid;
508    }
509
510    /**
511     * Get the left side of the diff.
512     * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
513     * load failure).
514     * @return RevisionRecord|null
515     */
516    public function getOldRevision() {
517        return $this->mOldRevisionRecord ?: null;
518    }
519
520    /**
521     * Get the right side of the diff.
522     * Should not be null but can still happen in the case of load failure.
523     * @return RevisionRecord|null
524     */
525    public function getNewRevision() {
526        return $this->mNewRevisionRecord;
527    }
528
529    /**
530     * Look up a special:Undelete link to the given deleted revision id,
531     * as a workaround for being unable to load deleted diffs in currently.
532     *
533     * @param int $id Revision ID
534     *
535     * @return string|bool Link HTML or false
536     */
537    public function deletedLink( $id ) {
538        if ( $this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
539            $revRecord = $this->archivedRevisionLookup->getArchivedRevisionRecord( null, $id );
540            if ( $revRecord ) {
541                $title = Title::newFromPageIdentity( $revRecord->getPage() );
542
543                return SpecialPage::getTitleFor( 'Undelete' )->getFullURL( [
544                    'target' => $title->getPrefixedText(),
545                    'timestamp' => $revRecord->getTimestamp()
546                ] );
547            }
548        }
549
550        return false;
551    }
552
553    /**
554     * Build a wikitext link toward a deleted revision, if viewable.
555     *
556     * @param int $id Revision ID
557     *
558     * @return string Wikitext fragment
559     */
560    public function deletedIdMarker( $id ) {
561        $link = $this->deletedLink( $id );
562        if ( $link ) {
563            return "[$link $id]";
564        } else {
565            return (string)$id;
566        }
567    }
568
569    private function showMissingRevision() {
570        $out = $this->getOutput();
571
572        $missing = [];
573        if ( $this->mOldid && ( !$this->mOldRevisionRecord || !$this->mOldContent ) ) {
574            $missing[] = $this->deletedIdMarker( $this->mOldid );
575        }
576        if ( !$this->mNewRevisionRecord || !$this->mNewContent ) {
577            $missing[] = $this->deletedIdMarker( $this->mNewid );
578        }
579
580        $out->setPageTitleMsg( $this->msg( 'errorpagetitle' ) );
581        $msg = $this->msg( 'difference-missing-revision' )
582            ->params( $this->getLanguage()->listToText( $missing ) )
583            ->numParams( count( $missing ) )
584            ->parseAsBlock();
585        $out->addHTML( $msg );
586    }
587
588    /**
589     * Checks whether one of the given Revisions was deleted
590     *
591     * @return bool
592     */
593    public function hasDeletedRevision() {
594        $this->loadRevisionData();
595        return (
596                $this->mNewRevisionRecord &&
597                $this->mNewRevisionRecord->isDeleted( RevisionRecord::DELETED_TEXT )
598            ) ||
599            (
600                $this->mOldRevisionRecord &&
601                $this->mOldRevisionRecord->isDeleted( RevisionRecord::DELETED_TEXT )
602            );
603    }
604
605    /**
606     * Check whether the user can read both of the pages for the current diff.
607     *
608     * This does not check access to deleted revisions, use isUserAllowedToSeeRevisions() for that.
609     *
610     * @since 1.44
611     */
612    public function authorizeView( Authority $performer ): PermissionStatus {
613        $this->loadRevisionData();
614        $permStatus = PermissionStatus::newEmpty();
615        if ( $this->mNewPage ) {
616            $performer->authorizeRead( 'read', $this->mNewPage, $permStatus );
617        }
618        if ( $this->mOldPage ) {
619            $performer->authorizeRead( 'read', $this->mOldPage, $permStatus );
620        }
621        return $permStatus;
622    }
623
624    /**
625     * Checks whether one of the given Revisions was suppressed
626     *
627     * @return bool
628     */
629    public function hasSuppressedRevision() {
630        return $this->hasDeletedRevision() && (
631            ( $this->mOldRevisionRecord &&
632                $this->mOldRevisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ) ||
633            ( $this->mNewRevisionRecord &&
634                $this->mNewRevisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) )
635        );
636    }
637
638    /**
639     * Renders user associated edit count
640     *
641     * @param UserIdentity $user
642     * @return string
643     */
644    private function getUserEditCount( $user ): string {
645        $editCount = $this->userEditTracker->getUserEditCount( $user );
646        if ( $editCount === null ) {
647            return '';
648        }
649
650        return Html::rawElement( 'div', [
651            'class' => 'mw-diff-usereditcount',
652        ],
653            $this->msg(
654                'diff-user-edits',
655                $this->getLanguage()->formatNum( $editCount )
656            )->parse()
657        );
658    }
659
660    /**
661     * Renders user roles
662     *
663     * @param UserIdentity $user
664     * @return string
665     */
666    private function getUserRoles( UserIdentity $user ) {
667        if ( !$this->userIdentityUtils->isNamed( $user ) ) {
668            return '';
669        }
670        $userGroups = $this->userGroupManager->getUserGroups( $user );
671        $userGroupLinks = [];
672        foreach ( $userGroups as $group ) {
673            $userGroupLinks[] = UserGroupMembership::getLinkHTML( $group, $this->getContext() );
674        }
675        return Html::rawElement( 'div', [
676            'class' => 'mw-diff-userroles',
677        ], $this->getLanguage()->commaList( $userGroupLinks ) );
678    }
679
680    /**
681     * Renders user associated meta data
682     *
683     * @param UserIdentity|null $user
684     * @return string
685     */
686    private function getUserMetaData( ?UserIdentity $user ) {
687        if ( !$user ) {
688            return '';
689        }
690        return Html::rawElement( 'div', [
691            'class' => 'mw-diff-usermetadata',
692        ], $this->getUserRoles( $user ) . $this->getUserEditCount( $user ) );
693    }
694
695    /**
696     * Checks whether the current user has permission for accessing the revisions of the diff.
697     * Note that this does not check whether the user has permission to view the page, it only
698     * checks revdelete permissions.
699     *
700     * It is the caller's responsibility to call
701     * $this->getUserPermissionErrors or similar checks.
702     *
703     * @param Authority $performer
704     * @return bool
705     */
706    public function isUserAllowedToSeeRevisions( Authority $performer ) {
707        $this->loadRevisionData();
708
709        if ( $this->mOldRevisionRecord && !$this->mOldRevisionRecord->userCan(
710            RevisionRecord::DELETED_TEXT,
711            $performer
712        ) ) {
713            return false;
714        }
715
716        // $this->mNewRev will only be falsy if a loading error occurred
717        // (in which case the user is allowed to see).
718        return !$this->mNewRevisionRecord || $this->mNewRevisionRecord->userCan(
719            RevisionRecord::DELETED_TEXT,
720            $performer
721        );
722    }
723
724    /**
725     * Checks whether the diff should be hidden from the current user
726     * This is based on whether the user is allowed to see it and has specifically asked to see it.
727     *
728     * @param Authority $performer
729     * @return bool
730     */
731    public function shouldBeHiddenFromUser( Authority $performer ) {
732        return $this->hasDeletedRevision() && ( !$this->unhide ||
733            !$this->isUserAllowedToSeeRevisions( $performer ) );
734    }
735
736    /**
737     * @param bool $diffOnly
738     */
739    public function showDiffPage( $diffOnly = false ) {
740        # Allow frames except in certain special cases
741        $out = $this->getOutput();
742        $out->getMetadata()->setPreventClickjacking( false );
743        $out->setRobotPolicy( 'noindex,nofollow' );
744
745        // Allow extensions to add any extra output here
746        $this->hookRunner->onDifferenceEngineShowDiffPage( $out );
747
748        if ( !$this->loadRevisionData() ) {
749            if ( $this->hookRunner->onDifferenceEngineShowDiffPageMaybeShowMissingRevision( $this ) ) {
750                $this->showMissingRevision();
751            }
752            return;
753        }
754
755        $user = $this->getUser();
756        $permStatus = $this->authorizeView( $this->getAuthority() );
757        if ( !$permStatus->isGood() ) {
758            throw new PermissionsError( 'read', $permStatus );
759        }
760
761        $rollback = '';
762
763        $query = $this->extraQueryParams;
764        # Carry over 'diffonly' param via navigation links
765        if ( $diffOnly != MediaWikiServices::getInstance()
766            ->getUserOptionsLookup()->getBoolOption( $user, 'diffonly' )
767        ) {
768            $query['diffonly'] = $diffOnly;
769        }
770        # Cascade unhide param in links for easy deletion browsing
771        if ( $this->unhide ) {
772            $query['unhide'] = 1;
773        }
774
775        # Check if one of the revisions is deleted/suppressed
776        $deleted = $this->hasDeletedRevision();
777        $suppressed = $this->hasSuppressedRevision();
778        $allowed = $this->isUserAllowedToSeeRevisions( $this->getAuthority() );
779
780        $revisionTools = [];
781        $breadCrumbs = '';
782
783        # mOldRevisionRecord is false if the difference engine is called with a "vague" query for
784        # a diff between a version V and its previous version V' AND the version V
785        # is the first version of that article. In that case, V' does not exist.
786        if ( $this->mOldRevisionRecord === false ) {
787            if ( $this->mNewPage ) {
788                $out->setPageTitleMsg(
789                    $this->msg( 'difference-title' )->plaintextParams( $this->mNewPage->getPrefixedText() )
790                );
791            }
792            $samePage = true;
793            $oldHeader = '';
794            // Allow extensions to change the $oldHeader variable
795            $this->hookRunner->onDifferenceEngineOldHeaderNoOldRev( $oldHeader );
796        } else {
797            $this->hookRunner->onDifferenceEngineViewHeader( $this );
798
799            if ( !$this->mOldPage || !$this->mNewPage ) {
800                // XXX say something to the user?
801                $samePage = false;
802            } elseif ( $this->mNewPage->equals( $this->mOldPage ) ) {
803                $out->setPageTitleMsg(
804                    $this->msg( 'difference-title' )->plaintextParams( $this->mNewPage->getPrefixedText() )
805                );
806                $samePage = true;
807            } else {
808                $out->setPageTitleMsg( $this->msg( 'difference-title-multipage' )->plaintextParams(
809                    $this->mOldPage->getPrefixedText(), $this->mNewPage->getPrefixedText() ) );
810                $out->addSubtitle( $this->msg( 'difference-multipage' ) );
811                $samePage = false;
812            }
813
814            if ( $samePage && $this->mNewPage &&
815                $this->getAuthority()->probablyCan( 'edit', $this->mNewPage )
816            ) {
817                if ( $this->mNewRevisionRecord->isCurrent() &&
818                    $this->getAuthority()->probablyCan( 'rollback', $this->mNewPage )
819                ) {
820                    $rollbackLink = Linker::generateRollback(
821                        $this->mNewRevisionRecord,
822                        $this->getContext(),
823                        [ 'noBrackets' ]
824                    );
825                    if ( $rollbackLink ) {
826                        $out->getMetadata()->setPreventClickjacking( true );
827                        $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
828                    }
829                }
830
831                if ( $this->userCanEdit( $this->mOldRevisionRecord ) &&
832                    $this->userCanEdit( $this->mNewRevisionRecord )
833                ) {
834                    $undoLink = $this->linkRenderer->makeKnownLink(
835                        $this->mNewPage,
836                        $this->msg( 'editundo' )->text(),
837                        [ 'title' => Linker::titleAttrib( 'undo' ) ],
838                        [
839                            'action' => 'edit',
840                            'undoafter' => $this->mOldid,
841                            'undo' => $this->mNewid
842                        ]
843                    );
844                    $revisionTools['mw-diff-undo'] = $undoLink;
845                }
846            }
847            # Make "previous revision link"
848            $hasPrevious = $samePage && $this->mOldPage &&
849                $this->revisionStore->getPreviousRevision( $this->mOldRevisionRecord );
850            if ( $hasPrevious ) {
851                $prevlinkQuery = [ 'diff' => 'prev', 'oldid' => $this->mOldid ] + $query;
852                $prevlink = $this->linkRenderer->makeKnownLink(
853                    $this->mOldPage,
854                    $this->msg( 'previousdiff' )->text(),
855                    [ 'id' => 'differences-prevlink' ],
856                    $prevlinkQuery
857                );
858                $breadCrumbs .= $this->linkRenderer->makeKnownLink(
859                    $this->mOldPage,
860                    $this->msg( 'previousdiff' )->text(),
861                    [
862                        'class' => 'mw-diff-revision-history-link-previous'
863                    ],
864                    $prevlinkQuery
865                );
866            } else {
867                $prevlink = "\u{00A0}";
868            }
869
870            if ( $this->mOldRevisionRecord->isMinor() ) {
871                $oldminor = ChangesList::flag( 'minor' );
872            } else {
873                $oldminor = '';
874            }
875
876            $oldRevRecord = $this->mOldRevisionRecord;
877
878            $ldel = $this->revisionDeleteLink( $oldRevRecord );
879            $oldRevisionHeader = $this->getRevisionHeader( $oldRevRecord, 'complete' );
880            $oldChangeTags = ChangeTags::formatSummaryRow( $this->mOldTags, 'diff', $this->getContext() );
881            $oldRevComment = $this->commentFormatter
882                ->formatRevision(
883                    $oldRevRecord, $user, !$diffOnly, !$this->unhide, /** disable parentheseses */ false
884                );
885
886            if ( $oldRevComment === '' ) {
887                $defaultComment = $this->msg( 'changeslist-nocomment' )->escaped();
888                $oldRevComment = "<span class=\"comment mw-comment-none\">$defaultComment</span>";
889            }
890
891            $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
892                '<div id="mw-diff-otitle2">' .
893                Linker::revUserTools( $oldRevRecord, !$this->unhide ) .
894                $this->getUserMetaData( $oldRevRecord->getUser() ) .
895                '</div>' .
896                '<div id="mw-diff-otitle3">' . $oldminor . $oldRevComment . $ldel . '</div>' .
897                '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
898                '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
899
900            // Allow extensions to change the $oldHeader variable
901            $this->hookRunner->onDifferenceEngineOldHeader(
902                $this, $oldHeader, $prevlink, $oldminor, $diffOnly, $ldel, $this->unhide );
903        }
904
905        $out->addJsConfigVars( [
906            'wgDiffOldId' => $this->mOldid,
907            'wgDiffNewId' => $this->mNewid,
908        ] );
909
910        # Make "next revision link"
911        # Skip next link on the top revision
912        if ( $samePage && $this->mNewPage && !$this->mNewRevisionRecord->isCurrent() ) {
913            $nextlinkQuery = [ 'diff' => 'next', 'oldid' => $this->mNewid ] + $query;
914            $nextlink = $this->linkRenderer->makeKnownLink(
915                $this->mNewPage,
916                $this->msg( 'nextdiff' )->text(),
917                [ 'id' => 'differences-nextlink' ],
918                $nextlinkQuery
919            );
920            $breadCrumbs .= $this->linkRenderer->makeKnownLink(
921                $this->mNewPage,
922                $this->msg( 'nextdiff' )->text(),
923                [
924                    'class' => 'mw-diff-revision-history-link-next'
925                ],
926                $nextlinkQuery
927            );
928        } else {
929            $nextlink = "\u{00A0}";
930        }
931
932        if ( $this->mNewRevisionRecord->isMinor() ) {
933            $newminor = ChangesList::flag( 'minor' );
934        } else {
935            $newminor = '';
936        }
937
938        # Handle RevisionDelete links...
939        $rdel = $this->revisionDeleteLink( $this->mNewRevisionRecord );
940
941        # Allow extensions to define their own revision tools
942        $this->hookRunner->onDiffTools(
943            $this->mNewRevisionRecord,
944            $revisionTools,
945            $this->mOldRevisionRecord ?: null,
946            $user
947        );
948
949        $formattedRevisionTools = [];
950        // Put each one in parentheses (poor man's button)
951        foreach ( $revisionTools as $key => $tool ) {
952            $toolClass = is_string( $key ) ? $key : 'mw-diff-tool';
953            $element = Html::rawElement(
954                'span',
955                [ 'class' => $toolClass ],
956                $tool
957            );
958            $formattedRevisionTools[] = $element;
959        }
960
961        $newRevRecord = $this->mNewRevisionRecord;
962
963        $newRevisionHeader = $this->getRevisionHeader( $newRevRecord, 'complete' ) .
964            ' ' . implode( ' ', $formattedRevisionTools );
965        $newChangeTags = ChangeTags::formatSummaryRow( $this->mNewTags, 'diff', $this->getContext() );
966        $newRevComment = $this->commentFormatter->formatRevision(
967            $newRevRecord, $user, !$diffOnly, !$this->unhide, /** disable parentheseses */ false
968        );
969
970        if ( $newRevComment === '' ) {
971            $defaultComment = $this->msg( 'changeslist-nocomment' )->escaped();
972            $newRevComment = "<span class=\"comment mw-comment-none\">$defaultComment</span>";
973        }
974
975        $newMobileFooter = $this->getMobileFooter( $newRevRecord, $formattedRevisionTools );
976
977        $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
978            '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $newRevRecord, !$this->unhide ) .
979            $rollback .
980            $this->getUserMetaData( $newRevRecord->getUser() ) .
981            '</div>' .
982            '<div id="mw-diff-ntitle3">' . $newminor . $newRevComment . $rdel . '</div>' .
983            '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
984            '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
985
986        // Allow extensions to change the $newHeader variable
987        $this->hookRunner->onDifferenceEngineNewHeader( $this, $newHeader,
988            $formattedRevisionTools, $nextlink, $rollback, $newminor, $diffOnly,
989            $rdel, $this->unhide );
990
991        $out->addHTML(
992            Html::rawElement( 'div', [
993                'class' => 'mw-diff-revision-history-links'
994            ], $breadCrumbs )
995        );
996
997        $out->addHTML(
998            Html::rawElement( 'div', [
999                'class' => 'mw-diff-mobile-footer'
1000            ], $newMobileFooter )
1001        );
1002        $addMessageBoxStyles = false;
1003        # If the diff cannot be shown due to a deleted revision, then output
1004        # the diff header and links to unhide (if available)...
1005        if ( $this->shouldBeHiddenFromUser( $this->getAuthority() ) ) {
1006            $this->showDiffStyle();
1007            $multi = $this->getMultiNotice();
1008            $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
1009            if ( !$allowed ) {
1010                # Give explanation for why revision is not visible
1011                $msg = [ $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff' ];
1012            } else {
1013                # Give explanation and add a link to view the diff...
1014                $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
1015                $msg = [
1016                    $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff',
1017                    $this->getTitle()->getFullURL( $query )
1018                ];
1019            }
1020            $out->addHTML( Html::warningBox( $this->msg( ...$msg )->parse(), 'plainlinks' ) );
1021            $addMessageBoxStyles = true;
1022        # Otherwise, output a regular diff...
1023        } else {
1024            # Add deletion notice if the user is viewing deleted content
1025            $notice = '';
1026            if ( $deleted ) {
1027                $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
1028                $notice = Html::warningBox( $this->msg( $msg )->parse(), 'plainlinks' );
1029                $addMessageBoxStyles = true;
1030            }
1031
1032            # Add an error if the content can't be loaded
1033            $this->getSlotContents();
1034            foreach ( $this->getRevisionLoadErrors() as $msg ) {
1035                $notice .= Html::warningBox( $msg->parse() );
1036                $addMessageBoxStyles = true;
1037            }
1038
1039            // Check if inline switcher will be needed
1040            if ( $this->getTextDiffer()->hasFormat( 'inline' ) ) {
1041                $out->enableOOUI();
1042            }
1043
1044            $this->showTablePrefixes();
1045            $this->showDiff( $oldHeader, $newHeader, $notice );
1046            if ( !$diffOnly ) {
1047                $this->renderNewRevision();
1048            }
1049
1050            // Allow extensions to optionally not show the final patrolled link
1051            if ( $this->hookRunner->onDifferenceEngineRenderRevisionShowFinalPatrolLink() ) {
1052                # Add redundant patrol link on bottom...
1053                $out->addHTML( $this->markPatrolledLink() );
1054            }
1055        }
1056        if ( $addMessageBoxStyles ) {
1057            $out->addModuleStyles( 'mediawiki.codex.messagebox.styles' );
1058        }
1059    }
1060
1061    /**
1062     * Add table prefixes
1063     */
1064    private function showTablePrefixes() {
1065        $parts = [];
1066        foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1067            $parts += $slotDiffRenderer->getTablePrefix( $this->getContext(), $this->mNewPage );
1068        }
1069        ksort( $parts );
1070        $nonEmptyParts = array_values( array_filter( $parts ) );
1071        if ( $nonEmptyParts ) {
1072            $language = $this->getLanguage();
1073            $attrs = [
1074                'class' => 'mw-diff-table-prefix',
1075                'dir' => $language->getDir(),
1076                'lang' => $language->getCode(),
1077            ];
1078            $this->getOutput()->addHTML(
1079                Html::rawElement( 'div', $attrs, implode( '', $nonEmptyParts ) ) );
1080        }
1081    }
1082
1083    /**
1084     * Build a link to mark a change as patrolled.
1085     *
1086     * Returns empty string if there's either no revision to patrol or the user is not allowed to.
1087     *
1088     * Side effect: When the patrol link is build, this method will call
1089     * OutputPage::getMetadata()->setPreventClickjacking(true) and load a
1090     * JS module.
1091     *
1092     * @return string HTML or empty string
1093     */
1094    public function markPatrolledLink() {
1095        if ( $this->mMarkPatrolledLink === null ) {
1096            $linkInfo = $this->getMarkPatrolledLinkInfo();
1097            // If false, there is no patrol link needed/allowed
1098            if ( !$linkInfo || !$this->mNewPage ) {
1099                $this->mMarkPatrolledLink = '';
1100            } else {
1101                $patrolLinkClass = 'patrollink';
1102                $this->mMarkPatrolledLink = ' <span class="' . $patrolLinkClass . '" data-mw="interface">[' .
1103                    $this->linkRenderer->makeKnownLink(
1104                        $this->mNewPage,
1105                        $this->msg( 'markaspatrolleddiff' )->text(),
1106                        [],
1107                        [
1108                            'action' => 'markpatrolled',
1109                            'rcid' => $linkInfo['rcid'],
1110                        ]
1111                    ) . ']</span>';
1112                // Allow extensions to change the markpatrolled link
1113                $this->hookRunner->onDifferenceEngineMarkPatrolledLink( $this,
1114                    $this->mMarkPatrolledLink, $linkInfo['rcid'] );
1115            }
1116        }
1117        return $this->mMarkPatrolledLink;
1118    }
1119
1120    /**
1121     * Returns an array of meta data needed to build a "mark as patrolled" link and
1122     * adds a JS module to the output.
1123     *
1124     * @return array|false An array of meta data for a patrol link (rcid only)
1125     *  or false if no link is needed
1126     */
1127    protected function getMarkPatrolledLinkInfo() {
1128        $user = $this->getUser();
1129        $config = $this->getConfig();
1130
1131        // Prepare a change patrol link, if applicable
1132        if (
1133            // Is patrolling enabled and the user allowed to?
1134            $config->get( MainConfigNames::UseRCPatrol ) &&
1135            $this->mNewPage &&
1136            $this->getAuthority()->probablyCan( 'patrol', $this->mNewPage ) &&
1137            // Only do this if the revision isn't more than 6 hours older
1138            // than the Max RC age (6h because the RC might not be cleaned out regularly)
1139            RecentChange::isInRCLifespan( $this->mNewRevisionRecord->getTimestamp(), 21600 )
1140        ) {
1141            // Look for an unpatrolled change corresponding to this diff
1142            $change = $this->recentChangeLookup->getRecentChangeByConds(
1143                [
1144                    'rc_this_oldid' => $this->mNewid,
1145                    'rc_patrolled' => RecentChange::PRC_UNPATROLLED
1146                ],
1147                __METHOD__
1148            );
1149
1150            if ( $change && !$change->getPerformerIdentity()->equals( $user ) ) {
1151                $rcid = $change->getAttribute( 'rc_id' );
1152            } else {
1153                // None found or the page has been created by the current user.
1154                // If the user could patrol this it already would be patrolled
1155                $rcid = 0;
1156            }
1157
1158            // Allow extensions to possibly change the rcid here
1159            // For example the rcid might be set to zero due to the user
1160            // being the same as the performer of the change but an extension
1161            // might still want to show it under certain conditions
1162            $this->hookRunner->onDifferenceEngineMarkPatrolledRCID( $rcid, $this, $change, $user );
1163
1164            // Build the link
1165            if ( $rcid ) {
1166                $this->getOutput()->getMetadata()->setPreventClickjacking( true );
1167                $this->getOutput()->addModules( 'mediawiki.misc-authed-curate' );
1168
1169                return [ 'rcid' => $rcid ];
1170            }
1171        }
1172
1173        // No mark as patrolled link applicable
1174        return false;
1175    }
1176
1177    /**
1178     * @param RevisionRecord $revRecord
1179     *
1180     * @return string
1181     */
1182    private function revisionDeleteLink( RevisionRecord $revRecord ) {
1183        $link = Linker::getRevDeleteLink(
1184            $this->getAuthority(),
1185            $revRecord,
1186            $revRecord->getPageAsLinkTarget()
1187        );
1188        if ( $link !== '' ) {
1189            $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
1190        }
1191
1192        return $link;
1193    }
1194
1195    /**
1196     * Show the new revision of the page.
1197     *
1198     * @note Not supported after calling setContent().
1199     */
1200    public function renderNewRevision() {
1201        if ( $this->isContentOverridden ) {
1202            // The code below only works with a RevisionRecord object. We could construct a
1203            // fake RevisionRecord (here or in setContent), but since this does not seem
1204            // needed at the moment, we'll just fail for now.
1205            throw new LogicException(
1206                __METHOD__
1207                . ' is not supported after calling setContent(). Use setRevisions() instead.'
1208            );
1209        }
1210
1211        $out = $this->getOutput();
1212        $revHeader = $this->getRevisionHeader( $this->mNewRevisionRecord );
1213        # Add "current version as of X" title
1214        $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
1215        <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
1216        # Page content may be handled by a hooked call instead...
1217        if ( $this->hookRunner->onArticleContentOnDiff( $this, $out ) ) {
1218            $this->loadNewText();
1219            if ( !$this->mNewPage ) {
1220                // New revision is unsaved; bail out.
1221                // TODO in theory rendering the new revision is a meaningful thing to do
1222                // even if it's unsaved, but a lot of untangling is required to do it safely.
1223                return;
1224            }
1225            if ( $this->hasNewRevisionLoadError() ) {
1226                // There was an error loading the new revision
1227                return;
1228            }
1229
1230            $out->setRevisionId( $this->mNewid );
1231            $out->setRevisionIsCurrent( $this->mNewRevisionRecord->isCurrent() );
1232            $out->getMetadata()->setRevisionTimestamp( $this->mNewRevisionRecord->getTimestamp() );
1233            $out->setArticleFlag( true );
1234
1235            if ( !$this->hookRunner->onArticleRevisionViewCustom(
1236                $this->mNewRevisionRecord, $this->mNewPage, $this->mOldid, $out )
1237            ) {
1238                // Handled by extension
1239                // NOTE: sync with hooks called in Article::view()
1240            } else {
1241                // Normal page
1242                if ( $this->getTitle()->equals( $this->mNewPage ) ) {
1243                    // If the Title stored in the context is the same as the one
1244                    // of the new revision, we can use its associated WikiPage
1245                    // object.
1246                    $wikiPage = $this->getWikiPage();
1247                } else {
1248                    // Otherwise we need to create our own WikiPage object
1249                    $wikiPage = $this->wikiPageFactory->newFromTitle( $this->mNewPage );
1250                }
1251
1252                $parserOptions = $wikiPage->makeParserOptions( $this->getContext() );
1253                $parserOptions->setRenderReason( 'diff-page' );
1254
1255                $parserOutputAccess = MediaWikiServices::getInstance()->getParserOutputAccess();
1256                $status = $parserOutputAccess->getParserOutput(
1257                    $wikiPage,
1258                    $parserOptions,
1259                    $this->mNewRevisionRecord,
1260                    [
1261                        // we already checked
1262                        ParserOutputAccess::OPT_NO_AUDIENCE_CHECK => true,
1263                        // Update cascading protection
1264                        ParserOutputAccess::OPT_LINKS_UPDATE => true,
1265                    ],
1266                );
1267                if ( $status->isOK() ) {
1268                    $parserOutput = $status->getValue();
1269                    // Allow extensions to change parser output here
1270                    if ( $this->hookRunner->onDifferenceEngineRenderRevisionAddParserOutput(
1271                        $this, $out, $parserOutput, $wikiPage )
1272                    ) {
1273                        $out->addParserOutput( $parserOutput, $parserOptions, [
1274                            'enableSectionEditLinks' => $this->mNewRevisionRecord->isCurrent()
1275                                && $this->getAuthority()->probablyCan(
1276                                    'edit',
1277                                    $this->mNewRevisionRecord->getPage()
1278                                ),
1279                            'absoluteURLs' => $this->slotDiffOptions['expand-url'] ?? false
1280                        ] );
1281                    }
1282                } else {
1283                    $out->addModuleStyles( 'mediawiki.codex.messagebox.styles' );
1284                    foreach ( $status->getMessages() as $msg ) {
1285                        $out->addHTML( Html::errorBox(
1286                            $this->msg( $msg )->parse()
1287                        ) );
1288                    }
1289                }
1290            }
1291        }
1292    }
1293
1294    /**
1295     * Get the diff text, send it to the OutputPage object
1296     * Returns false if the diff could not be generated, otherwise returns true
1297     *
1298     * @param string|false $otitle Header for old text or false
1299     * @param string|false $ntitle Header for new text or false
1300     * @param string $notice HTML between diff header and body
1301     *
1302     * @return bool
1303     */
1304    public function showDiff( $otitle, $ntitle, $notice = '' ) {
1305        // Allow extensions to affect the output here
1306        $this->hookRunner->onDifferenceEngineShowDiff( $this );
1307
1308        $diff = $this->getDiff( $otitle, $ntitle, $notice );
1309        if ( $diff === false ) {
1310            $this->showMissingRevision();
1311            return false;
1312        }
1313
1314        $this->showDiffStyle();
1315        if ( $this->slotDiffOptions['expand-url'] ?? false ) {
1316            $diff = Linker::expandLocalLinks( $diff );
1317        }
1318        $this->getOutput()->addHTML( $diff );
1319        return true;
1320    }
1321
1322    /**
1323     * Add style sheets for diff display.
1324     */
1325    public function showDiffStyle() {
1326        if ( !$this->isSlotDiffRenderer ) {
1327            $this->getOutput()->addModules( 'mediawiki.diff' );
1328            $this->getOutput()->addModuleStyles( [
1329                'mediawiki.interface.helpers.styles',
1330                'mediawiki.diff.styles'
1331            ] );
1332            foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1333                $slotDiffRenderer->addModules( $this->getOutput() );
1334            }
1335        }
1336    }
1337
1338    /**
1339     * Get complete diff table, including header
1340     *
1341     * @param string|false $otitle Header for old text or false
1342     * @param string|false $ntitle Header for new text or false
1343     * @param string $notice HTML between diff header and body
1344     *
1345     * @return string|false
1346     */
1347    public function getDiff( $otitle, $ntitle, $notice = '' ) {
1348        $body = $this->getDiffBody();
1349        if ( $body === false ) {
1350            return false;
1351        }
1352
1353        $multi = $this->getMultiNotice();
1354        // Display a message when the diff is empty
1355        if ( $body === '' ) {
1356            $notice .= '<div class="mw-diff-empty">' .
1357                $this->msg( 'diff-empty' )->parse() .
1358                "</div>\n";
1359        }
1360
1361        if ( $this->cacheHitKey !== null ) {
1362            $body .= "\n<!-- diff cache key " . htmlspecialchars( $this->cacheHitKey ) . " -->\n";
1363        }
1364
1365        return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
1366    }
1367
1368    private function incrementStats( string $cacheStatus ): void {
1369        $stats = MediaWikiServices::getInstance()->getStatsFactory();
1370        $stats->getCounter( 'diff_cache_total' )
1371            ->setLabel( 'status', $cacheStatus )
1372            ->increment();
1373    }
1374
1375    /**
1376     * Get the diff table body, without header
1377     *
1378     * @return string|false
1379     */
1380    public function getDiffBody() {
1381        $this->mCacheHit = true;
1382        // Check if the diff should be hidden from this user
1383        if ( !$this->isContentOverridden ) {
1384            if ( !$this->loadRevisionData() ) {
1385                return false;
1386            } elseif ( $this->mOldRevisionRecord &&
1387                !$this->mOldRevisionRecord->userCan(
1388                    RevisionRecord::DELETED_TEXT,
1389                    $this->getAuthority()
1390                )
1391            ) {
1392                return false;
1393            } elseif ( $this->mNewRevisionRecord &&
1394                !$this->mNewRevisionRecord->userCan(
1395                    RevisionRecord::DELETED_TEXT,
1396                    $this->getAuthority()
1397                ) ) {
1398                return false;
1399            }
1400            // Short-circuit
1401            if ( $this->mOldRevisionRecord === false || (
1402                $this->mOldRevisionRecord &&
1403                $this->mNewRevisionRecord &&
1404                $this->mOldRevisionRecord->getId() &&
1405                $this->mOldRevisionRecord->getId() == $this->mNewRevisionRecord->getId()
1406            ) ) {
1407                if ( $this->hookRunner->onDifferenceEngineShowEmptyOldContent( $this ) ) {
1408                    return '';
1409                }
1410            }
1411        }
1412
1413        // Cacheable?
1414        $key = false;
1415        $services = MediaWikiServices::getInstance();
1416        $cache = $services->getMainWANObjectCache();
1417        $stats = $services->getStatsdDataFactory();
1418        if ( $this->mOldid && $this->mNewid ) {
1419            $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
1420
1421            // Try cache
1422            if ( !$this->mRefreshCache ) {
1423                $difftext = $cache->get( $key );
1424                if ( is_string( $difftext ) ) {
1425                    $this->incrementStats( 'hit' );
1426                    $difftext = $this->localiseDiff( $difftext );
1427                    $this->cacheHitKey = $key;
1428                    return $difftext;
1429                }
1430            } // don't try to load but save the result
1431        }
1432        $this->mCacheHit = false;
1433        $this->cacheHitKey = null;
1434
1435        // Loadtext is permission safe, this just clears out the diff
1436        if ( !$this->loadText() ) {
1437            return false;
1438        }
1439
1440        $difftext = '';
1441        // We've checked for revdelete at the beginning of this method; it's OK to ignore
1442        // read permissions here.
1443        $slotContents = $this->getSlotContents();
1444        foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
1445            try {
1446                $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
1447                    $slotContents[$role]['new'] );
1448            } catch ( IncompatibleDiffTypesException $e ) {
1449                $slotDiff = $this->getSlotError( $e->getMessageObject()->parse() );
1450            }
1451            if ( $slotDiff && $role !== SlotRecord::MAIN ) {
1452                // FIXME: ask SlotRoleHandler::getSlotNameMessage
1453                $slotTitle = $role;
1454                $difftext .= $this->getSlotHeader( $slotTitle );
1455            }
1456            $difftext .= $slotDiff;
1457        }
1458
1459        // Save to cache for 7 days
1460        if ( !$this->hookRunner->onAbortDiffCache( $this ) ) {
1461            $this->incrementStats( 'uncacheable' );
1462        } elseif ( $key !== false ) {
1463            $this->incrementStats( 'miss' );
1464            $cache->set( $key, $difftext, 7 * 86400 );
1465        } else {
1466            $this->incrementStats( 'uncacheable' );
1467        }
1468        // localise line numbers and title attribute text
1469        $difftext = $this->localiseDiff( $difftext );
1470
1471        return $difftext;
1472    }
1473
1474    /**
1475     * Get the diff table body for one slot, without header
1476     *
1477     * @param string $role
1478     * @return string|false
1479     */
1480    public function getDiffBodyForRole( $role ) {
1481        $diffRenderers = $this->getSlotDiffRenderers();
1482        if ( !isset( $diffRenderers[$role] ) ) {
1483            return false;
1484        }
1485
1486        $slotContents = $this->getSlotContents();
1487        try {
1488            $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1489                $slotContents[$role]['new'] );
1490        } catch ( IncompatibleDiffTypesException $e ) {
1491            $slotDiff = $this->getSlotError( $e->getMessageObject()->parse() );
1492        }
1493        if ( $slotDiff === '' ) {
1494            return false;
1495        }
1496
1497        if ( $role !== SlotRecord::MAIN ) {
1498            // TODO use human-readable role name at least
1499            $slotTitle = $role;
1500            $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1501        }
1502
1503        return $this->localiseDiff( $slotDiff );
1504    }
1505
1506    /**
1507     * Get a slot header for inclusion in a diff body (as a table row).
1508     *
1509     * @param string $headerText The text of the header
1510     * @return string
1511     */
1512    protected function getSlotHeader( $headerText ) {
1513        // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1514        $columnCount = $this->mOldRevisionRecord ? 4 : 2;
1515        $userLang = $this->getLanguage()->getHtmlCode();
1516        return Html::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1517            Html::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1518    }
1519
1520    /**
1521     * Get an error message for inclusion in a diff body (as a table row).
1522     *
1523     * @param string $errorText The HTML of the error
1524     * @return string
1525     */
1526    protected function getSlotError( $errorText ) {
1527        // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1528        $columnCount = $this->mOldRevisionRecord ? 4 : 2;
1529        $userLang = $this->getLanguage()->getHtmlCode();
1530        return Html::rawElement( 'tr', [ 'class' => 'mw-diff-slot-error', 'lang' => $userLang ],
1531            Html::rawElement( 'td', [ 'colspan' => $columnCount ], $errorText ) );
1532    }
1533
1534    /**
1535     * Get the cache key parameters
1536     *
1537     * Subclasses can replace the first element in the array to something
1538     * more specific to the type of diff (e.g. "inline-diff"), or append
1539     * if the cache should vary on more things. Overriding entirely should
1540     * be avoided.
1541     *
1542     * @since 1.31
1543     *
1544     * @return string[]
1545     * @phan-return non-empty-array<string>
1546     */
1547    protected function getDiffBodyCacheKeyParams() {
1548        if ( !$this->mOldid || !$this->mNewid ) {
1549            throw new BadMethodCallException( 'mOldid and mNewid must be set to get diff cache key.' );
1550        }
1551
1552        $params = [
1553            'diff',
1554            self::DIFF_VERSION,
1555            "old-{$this->mOldid}",
1556            "rev-{$this->mNewid}"
1557        ];
1558
1559        $extraKeys = [];
1560        if ( !$this->isSlotDiffRenderer ) {
1561            foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1562                $extraKeys = array_merge( $extraKeys, $slotDiffRenderer->getExtraCacheKeys() );
1563            }
1564        }
1565        ksort( $extraKeys );
1566        return array_merge( $params, array_values( $extraKeys ) );
1567    }
1568
1569    /**
1570     * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1571     * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1572     * @return string[]
1573     * @internal for use by DifferenceEngineSlotDiffRenderer only
1574     * @deprecated
1575     */
1576    public function getExtraCacheKeys() {
1577        // This method is called when the DifferenceEngine is used for a slot diff. We only care
1578        // about special things, not the revision IDs, which are added to the cache key by the
1579        // page-level DifferenceEngine, and which might not have a valid value for this object.
1580        $this->mOldid = 123456789;
1581        $this->mNewid = 987654321;
1582
1583        // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1584        $params = $this->getDiffBodyCacheKeyParams();
1585
1586        // Try to get rid of the standard keys to keep the cache key human-readable:
1587        // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1588        // the child class includes the same keys, drop them.
1589        // Uses an obscure PHP feature where static calls to non-static methods are allowed
1590        // as long as we are already in a non-static method of the same class, and the call context
1591        // ($this) will be inherited.
1592        // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1593        $standardParams = DifferenceEngine::getDiffBodyCacheKeyParams();
1594        if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1595            $params = array_slice( $params, count( $standardParams ) );
1596        }
1597
1598        return $params;
1599    }
1600
1601    /**
1602     * @param array $options for the difference engine. Available options:
1603     *    - diff-type: The text diff format, e.g. "table" or "inline". If the
1604     *      specified format is not supported, the option will be ignored, so
1605     *      the site default format (table) will be used.
1606     *    - expand-url: If true, put full URLs in href attributes (for action=render)
1607     *      FIXME: expand-url is not a slot diff option, it is a DifferenceEngine option.
1608     *    - inline-toggle: If true, and the inline format is supported
1609     *      a format selector toggle switch will be shown.
1610     */
1611    public function setSlotDiffOptions( $options ) {
1612        $validatedOptions = [];
1613        if ( isset( $options['diff-type'] )
1614            && $this->getTextDiffer()->hasFormat( $options['diff-type'] )
1615        ) {
1616            $validatedOptions['diff-type'] = $options['diff-type'];
1617        }
1618        if ( !empty( $options['expand-url'] ) ) {
1619            $validatedOptions['expand-url'] = true;
1620        }
1621        if ( !empty( $options['inline-toggle'] ) ) {
1622            $validatedOptions['inline-toggle'] = true;
1623        }
1624        $this->slotDiffOptions = $validatedOptions;
1625    }
1626
1627    /**
1628     * Set query parameters to append to diff page links
1629     *
1630     * @since 1.41
1631     *
1632     * @param array $params
1633     */
1634    public function setExtraQueryParams( $params ) {
1635        $this->extraQueryParams = $params;
1636    }
1637
1638    /**
1639     * Generate a diff, no caching.
1640     *
1641     * @since 1.21
1642     *
1643     * @param Content $old Old content
1644     * @param Content $new New content
1645     *
1646     * @throws Exception If old or new content is not an instance of TextContent.
1647     * @return bool|string
1648     *
1649     * @deprecated since 1.32, use a SlotDiffRenderer instead.
1650     */
1651    public function generateContentDiffBody( Content $old, Content $new ) {
1652        $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1653        if (
1654            $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1655            && $this->isSlotDiffRenderer
1656        ) {
1657            // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1658            // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1659            // This will happen when a content model has no custom slot diff renderer, it does have
1660            // a custom difference engine, but that does not override this method.
1661            throw new LogicException( get_class( $this ) . ': could not maintain backwards compatibility. '
1662                . 'Please use a SlotDiffRenderer.' );
1663        }
1664        return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1665    }
1666
1667    /**
1668     * Generate a diff, no caching
1669     *
1670     * @param string $otext Old text, must be already segmented
1671     * @param string $ntext New text, must be already segmented
1672     *
1673     * @throws LogicException If content handling for text content is configured in a way
1674     *   that makes maintaining B/C hard.
1675     * @return bool|string
1676     *
1677     * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1678     */
1679    public function generateTextDiffBody( $otext, $ntext ) {
1680        $slotDiffRenderer = $this->contentHandlerFactory
1681            ->getContentHandler( CONTENT_MODEL_TEXT )
1682            ->getSlotDiffRenderer( $this->getContext() );
1683        if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer ) ) {
1684            // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1685            // This is too unlikely to happen to bother handling properly.
1686            throw new LogicException( 'The slot diff renderer for text content should be a '
1687                . 'TextSlotDiffRenderer subclass' );
1688        }
1689        return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1690    }
1691
1692    /**
1693     * Process DiffEngine config and get a sensible, usable engine
1694     *
1695     * @return string 'wikidiff2', 'php', or path to an executable
1696     * @internal For use by this class and within Core only.
1697     */
1698    public static function getEngine() {
1699        $differenceEngine = new self;
1700        $engine = $differenceEngine->getTextDiffer()->getEngineForFormat( 'table' );
1701        if ( $engine === 'external' ) {
1702            return MediaWikiServices::getInstance()->getMainConfig()
1703                ->get( MainConfigNames::ExternalDiffEngine );
1704        } else {
1705            return $engine;
1706        }
1707    }
1708
1709    /**
1710     * Generate a debug comment indicating diff generating time,
1711     * server node, and generator backend.
1712     *
1713     * @param string $generator What diff engine was used
1714     *
1715     * @return string
1716     */
1717    protected function debug( $generator = "internal" ) {
1718        if ( !$this->enableDebugComment ) {
1719            return '';
1720        }
1721        $data = [ $generator ];
1722        if ( $this->getConfig()->get( MainConfigNames::ShowHostnames ) ) {
1723            $data[] = wfHostname();
1724        }
1725        $data[] = wfTimestamp( TS_DB );
1726
1727        return "<!-- diff generator: " .
1728            implode( " ", array_map( "htmlspecialchars", $data ) ) .
1729            " -->\n";
1730    }
1731
1732    /**
1733     * @return string
1734     */
1735    private function getDebugString() {
1736        $engine = self::getEngine();
1737        if ( $engine === 'wikidiff2' ) {
1738            return $this->debug( 'wikidiff2' );
1739        } elseif ( $engine === 'php' ) {
1740            return $this->debug( 'native PHP' );
1741        } else {
1742            return $this->debug( "external $engine" );
1743        }
1744    }
1745
1746    /**
1747     * Localise diff output
1748     *
1749     * @param string $text
1750     * @return string
1751     */
1752    private function localiseDiff( $text ) {
1753        return $this->getTextDiffer()->localize( $this->getTextDiffFormat(), $text );
1754    }
1755
1756    /**
1757     * Replace a common convention for language-independent line numbers with
1758     * the text in the user's language.
1759     *
1760     * @deprecated since 1.41, use BaseTextDiffer::localizeLineNumbers()
1761     * @param string $text
1762     * @return string
1763     */
1764    public function localiseLineNumbers( $text ) {
1765        return preg_replace_callback( '/<!--LINE (\d+)-->/',
1766            function ( array $matches ) {
1767                if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
1768                    return '';
1769                }
1770                return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1771            }, $text );
1772    }
1773
1774    /**
1775     * If there are revisions between the ones being compared, return a note saying so.
1776     *
1777     * @return string
1778     */
1779    public function getMultiNotice() {
1780        // The notice only make sense if we are diffing two saved revisions of the same page.
1781        if (
1782            !$this->mOldRevisionRecord || !$this->mNewRevisionRecord
1783            || !$this->mOldPage || !$this->mNewPage
1784            || !$this->mOldPage->equals( $this->mNewPage )
1785            || $this->mOldRevisionRecord->getId() === null
1786            || $this->mNewRevisionRecord->getId() === null
1787            // (T237709) Deleted revs might have different page IDs
1788            || $this->mNewPage->getArticleID() !== $this->mOldRevisionRecord->getPageId()
1789            || $this->mNewPage->getArticleID() !== $this->mNewRevisionRecord->getPageId()
1790        ) {
1791            return '';
1792        }
1793
1794        if ( $this->mOldRevisionRecord->getTimestamp() > $this->mNewRevisionRecord->getTimestamp() ) {
1795            $oldRevRecord = $this->mNewRevisionRecord; // flip
1796            $newRevRecord = $this->mOldRevisionRecord; // flip
1797        } else { // normal case
1798            $oldRevRecord = $this->mOldRevisionRecord;
1799            $newRevRecord = $this->mNewRevisionRecord;
1800        }
1801
1802        // Don't show the notice if too many rows must be scanned
1803        // @todo show some special message for that case
1804        $nEdits = 0;
1805        $revisionIdList = $this->revisionStore->getRevisionIdsBetween(
1806            $this->mNewPage->getArticleID(),
1807            $oldRevRecord,
1808            $newRevRecord,
1809            1000
1810        );
1811        // only count revisions that are visible
1812        if ( count( $revisionIdList ) > 0 ) {
1813            foreach ( $revisionIdList as $revisionId ) {
1814                $revision = $this->revisionStore->getRevisionById( $revisionId );
1815                if ( $revision->getUser( RevisionRecord::FOR_THIS_USER, $this->getAuthority() ) ) {
1816                    $nEdits++;
1817                }
1818            }
1819        }
1820        if ( $nEdits > 0 && $nEdits <= 1000 ) {
1821            // Use an invalid username to get the wiki's default gender (as fallback)
1822            $newRevUserForGender = '[HIDDEN]';
1823            $limit = 100; // use diff-multi-manyusers if too many users
1824            try {
1825                $users = $this->revisionStore->getAuthorsBetween(
1826                    $this->mNewPage->getArticleID(),
1827                    $oldRevRecord,
1828                    $newRevRecord,
1829                    null,
1830                    $limit
1831                );
1832                $numUsers = count( $users );
1833
1834                $newRevUser = $newRevRecord->getUser( RevisionRecord::RAW );
1835                $newRevUserText = $newRevUser ? $newRevUser->getName() : '';
1836                $newRevUserSafe = $newRevRecord->getUser(
1837                    RevisionRecord::FOR_THIS_USER,
1838                    $this->getAuthority()
1839                );
1840                $newRevUserForGender = $newRevUserSafe ? $newRevUserSafe->getName() : '[HIDDEN]';
1841                if ( $numUsers == 1 && $users[0]->getName() == $newRevUserText ) {
1842                    $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1843                }
1844            } catch ( InvalidArgumentException ) {
1845                $numUsers = 0;
1846            }
1847
1848            return self::intermediateEditsMsg( $nEdits, $numUsers, $limit, $newRevUserForGender );
1849        }
1850
1851        return '';
1852    }
1853
1854    /**
1855     * Get a notice about how many intermediate edits and users there are
1856     *
1857     * @param int $numEdits
1858     * @param int $numUsers
1859     * @param int $limit
1860     * @param string $lastUser
1861     *
1862     * @return string
1863     */
1864    public static function intermediateEditsMsg( $numEdits, $numUsers, $limit, $lastUser = '[HIDDEN]' ) {
1865        if ( $numUsers === 0 ) {
1866            $msg = 'diff-multi-sameuser';
1867            return wfMessage( $msg )
1868                ->numParams( $numEdits, $numUsers )
1869                ->params( $lastUser )
1870                ->parse();
1871        } elseif ( $numUsers > $limit ) {
1872            $msg = 'diff-multi-manyusers';
1873            $numUsers = $limit;
1874        } else {
1875            $msg = 'diff-multi-otherusers';
1876        }
1877
1878        return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1879    }
1880
1881    /**
1882     * @param RevisionRecord $revRecord
1883     * @return bool whether the user can see and edit the revision.
1884     */
1885    private function userCanEdit( RevisionRecord $revRecord ) {
1886        if ( !$revRecord->userCan( RevisionRecord::DELETED_TEXT, $this->getAuthority() ) ) {
1887            return false;
1888        }
1889
1890        return true;
1891    }
1892
1893    /**
1894     * Get a header for a specified revision.
1895     *
1896     * @param RevisionRecord $rev
1897     * @param string $complete 'complete' to get the header wrapped depending
1898     *        the visibility of the revision and a link to edit the page.
1899     *
1900     * @return string HTML fragment
1901     */
1902    public function getRevisionHeader( RevisionRecord $rev, $complete = '' ) {
1903        $lang = $this->getLanguage();
1904        $user = $this->getUser();
1905        $revtimestamp = $rev->getTimestamp();
1906        $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1907        $dateofrev = $lang->userDate( $revtimestamp, $user );
1908        $timeofrev = $lang->userTime( $revtimestamp, $user );
1909
1910        $header = $this->msg(
1911            $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
1912            $timestamp,
1913            $dateofrev,
1914            $timeofrev
1915        );
1916
1917        if ( $complete !== 'complete' ) {
1918            return $header->escaped();
1919        }
1920
1921        $title = $rev->getPageAsLinkTarget();
1922
1923        if ( $this->userCanEdit( $rev ) ) {
1924            $header = $this->linkRenderer->makeKnownLink(
1925                $title,
1926                $header->text(),
1927                [],
1928                [ 'oldid' => $rev->getId() ]
1929            );
1930            $editQuery = [ 'action' => 'edit' ];
1931            if ( !$rev->isCurrent() ) {
1932                $editQuery['oldid'] = $rev->getId();
1933            }
1934
1935            $key = $this->getAuthority()->probablyCan( 'edit', $rev->getPage() ) ? 'editold' : 'viewsourceold';
1936            $msg = $this->msg( $key )->text();
1937            $editLink = $this->linkRenderer->makeKnownLink( $title, $msg, [], $editQuery );
1938            $header .= ' ' . Html::rawElement(
1939                'span',
1940                [ 'class' => 'mw-diff-edit' ],
1941                $editLink
1942            );
1943        } else {
1944            $header = $header->escaped();
1945        }
1946
1947        // Machine readable information
1948        $header .= Html::element( 'span',
1949            [
1950                'class' => 'mw-diff-timestamp',
1951                'data-timestamp' => wfTimestamp( TS_ISO_8601, $revtimestamp ),
1952            ], ''
1953        );
1954
1955        if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
1956            return Html::rawElement(
1957                'span',
1958                [ 'class' => Linker::getRevisionDeletedClass( $rev ) ],
1959                $header
1960            );
1961        }
1962
1963        return $header;
1964    }
1965
1966    /**
1967     * Add the header to a diff body
1968     *
1969     * @param string $diff Diff body
1970     * @param string $otitle Old revision header
1971     * @param string $ntitle New revision header
1972     * @param string $multi Notice telling user that there are intermediate
1973     *   revisions between the ones being compared
1974     * @param string $notice Other notices, e.g. that user is viewing deleted content
1975     *
1976     * @return string
1977     */
1978    public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1979        // shared.css sets diff in interface language/dir, but the actual content
1980        // is often in a different language, mostly the page content language/dir
1981        $header = Html::openElement( 'table', [
1982            'class' => [
1983                'diff',
1984                // The following classes are used here:
1985                // * diff-type-table
1986                // * diff-type-inline
1987                'diff-type-' . $this->getTextDiffFormat(),
1988                // The following classes are used here:
1989                // * diff-contentalign-left
1990                // * diff-contentalign-right
1991                'diff-contentalign-' . $this->getDiffLang()->alignStart(),
1992                // The following classes are used here:
1993                // * diff-editfont-monospace
1994                // * diff-editfont-sans-serif
1995                // * diff-editfont-serif
1996                'diff-editfont-' . $this->userOptionsLookup->getOption(
1997                    $this->getUser(),
1998                    'editfont'
1999                )
2000            ],
2001            'data-mw' => 'interface',
2002        ] );
2003        $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
2004
2005        if ( !$diff && !$otitle ) {
2006            $header .= "
2007            <tr class=\"diff-title\" lang=\"{$userLang}\">
2008            <td class=\"diff-ntitle\">{$ntitle}</td>
2009            </tr>";
2010            $multiColspan = 1;
2011        } else {
2012            if ( $diff ) { // Safari/Chrome show broken output if cols not used
2013                $header .= "
2014                <col class=\"diff-marker\" />
2015                <col class=\"diff-content\" />
2016                <col class=\"diff-marker\" />
2017                <col class=\"diff-content\" />";
2018                $colspan = 2;
2019                $multiColspan = 4;
2020            } else {
2021                $colspan = 1;
2022                $multiColspan = 2;
2023            }
2024            if ( $otitle || $ntitle ) {
2025                // FIXME Hardcoding values from TableDiffFormatter.
2026                $deletedClass = 'diff-side-deleted';
2027                $addedClass = 'diff-side-added';
2028                $header .= "
2029                <tr class=\"diff-title\" lang=\"{$userLang}\">
2030                <td colspan=\"$colspan\" class=\"diff-otitle {$deletedClass}\">{$otitle}</td>
2031                <td colspan=\"$colspan\" class=\"diff-ntitle {$addedClass}\">{$ntitle}</td>
2032                </tr>";
2033            }
2034        }
2035
2036        if ( $multi != '' ) {
2037            $header .= "<tr><td colspan=\"{$multiColspan}\" " .
2038                "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
2039        }
2040        if ( $notice != '' ) {
2041            $header .= "<tr><td colspan=\"{$multiColspan}\" " .
2042                "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
2043        }
2044
2045        return $header . $diff . "</table>";
2046    }
2047
2048    /**
2049     * Use specified text instead of loading from the database
2050     * @param Content $oldContent
2051     * @param Content $newContent
2052     * @since 1.21
2053     * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
2054     */
2055    public function setContent( Content $oldContent, Content $newContent ) {
2056        $this->mOldContent = $oldContent;
2057        $this->mNewContent = $newContent;
2058
2059        $this->mTextLoaded = 2;
2060        $this->mRevisionsLoaded = true;
2061        $this->isContentOverridden = true;
2062        $this->slotDiffRenderers = null;
2063    }
2064
2065    /**
2066     * Use specified text instead of loading from the database.
2067     * @param RevisionRecord|null $oldRevision
2068     * @param RevisionRecord $newRevision
2069     */
2070    public function setRevisions(
2071        ?RevisionRecord $oldRevision, RevisionRecord $newRevision
2072    ) {
2073        if ( $oldRevision ) {
2074            $this->mOldRevisionRecord = $oldRevision;
2075            $this->mOldid = $oldRevision->getId();
2076            $this->mOldPage = Title::newFromPageIdentity( $oldRevision->getPage() );
2077            // This method is meant for edit diffs and such so there is no reason to provide a
2078            // revision that's not readable to the user, but check it just in case.
2079            $this->mOldContent = $oldRevision->getContent( SlotRecord::MAIN,
2080                RevisionRecord::FOR_THIS_USER, $this->getAuthority() );
2081            if ( !$this->mOldContent ) {
2082                $this->addRevisionLoadError( 'old' );
2083            }
2084        } else {
2085            $this->mOldPage = null;
2086            $this->mOldRevisionRecord = $this->mOldid = false;
2087        }
2088        $this->mNewRevisionRecord = $newRevision;
2089        $this->mNewid = $newRevision->getId();
2090        $this->mNewPage = Title::newFromPageIdentity( $newRevision->getPage() );
2091        $this->mNewContent = $newRevision->getContent( SlotRecord::MAIN,
2092            RevisionRecord::FOR_THIS_USER, $this->getAuthority() );
2093        if ( !$this->mNewContent ) {
2094            $this->addRevisionLoadError( 'new' );
2095        }
2096
2097        $this->mRevisionsIdsLoaded = $this->mRevisionsLoaded = true;
2098        $this->mTextLoaded = $oldRevision ? 2 : 1;
2099        $this->isContentOverridden = false;
2100        $this->slotDiffRenderers = null;
2101    }
2102
2103    /**
2104     * Set the language in which the diff text is written
2105     *
2106     * @param Language $lang
2107     * @since 1.19
2108     */
2109    public function setTextLanguage( Language $lang ) {
2110        $this->mDiffLang = $lang;
2111    }
2112
2113    /**
2114     * Maps a revision pair definition as accepted by DifferenceEngine constructor
2115     * to a pair of actual integers representing revision ids.
2116     *
2117     * @param int $old Revision id, e.g. from URL parameter 'oldid'
2118     * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
2119     *
2120     * @return array List of two revision ids, older first, later second.
2121     *     Zero signifies invalid argument passed.
2122     *     false signifies that there is no previous/next revision ($old is the oldest/newest one).
2123     * @phan-return (int|false)[]
2124     */
2125    public function mapDiffPrevNext( $old, $new ) {
2126        if ( $new === 'prev' ) {
2127            // Show diff between revision $old and the previous one. Get previous one from DB.
2128            $newid = intval( $old );
2129            $oldid = false;
2130            $newRev = $this->revisionStore->getRevisionById( $newid );
2131            if ( $newRev ) {
2132                $oldRev = $this->revisionStore->getPreviousRevision( $newRev );
2133                if ( $oldRev ) {
2134                    $oldid = $oldRev->getId();
2135                }
2136            }
2137        } elseif ( $new === 'next' ) {
2138            // Show diff between revision $old and the next one. Get next one from DB.
2139            $oldid = intval( $old );
2140            $newid = false;
2141            $oldRev = $this->revisionStore->getRevisionById( $oldid );
2142            if ( $oldRev ) {
2143                $newRev = $this->revisionStore->getNextRevision( $oldRev );
2144                if ( $newRev ) {
2145                    $newid = $newRev->getId();
2146                }
2147            }
2148        } else {
2149            $oldid = intval( $old );
2150            $newid = intval( $new );
2151        }
2152
2153        // @phan-suppress-next-line PhanTypeMismatchReturn getId does not return null here
2154        return [ $oldid, $newid ];
2155    }
2156
2157    private function loadRevisionIds() {
2158        if ( $this->mRevisionsIdsLoaded ) {
2159            return;
2160        }
2161
2162        $this->mRevisionsIdsLoaded = true;
2163
2164        $old = $this->mOldid;
2165        $new = $this->mNewid;
2166
2167        [ $this->mOldid, $this->mNewid ] = self::mapDiffPrevNext( $old, $new );
2168        if ( $new === 'next' && $this->mNewid === false ) {
2169            # if no result, NewId points to the newest old revision. The only newer
2170            # revision is cur, which is "0".
2171            $this->mNewid = 0;
2172        }
2173
2174        $this->hookRunner->onNewDifferenceEngine(
2175            // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
2176            $this->getTitle(), $this->mOldid, $this->mNewid, $old, $new );
2177    }
2178
2179    /**
2180     * Load revision metadata for the specified revisions. If newid is 0, then compare
2181     * the old revision in oldid to the current revision of the current page (as defined
2182     * by the request context); if oldid is 0, then compare the revision in newid to the
2183     * immediately previous one.
2184     *
2185     * If oldid is false, leave the corresponding RevisionRecord object set to false. This can
2186     * happen with 'diff=prev' pointing to a non-existent revision, and is also used directly
2187     * by the API.
2188     *
2189     * @return bool Whether both revisions were loaded successfully. Setting mOldRevisionRecord
2190     *   to false counts as successful loading.
2191     */
2192    public function loadRevisionData() {
2193        if ( $this->mRevisionsLoaded ) {
2194            return $this->isContentOverridden ||
2195            ( $this->mOldRevisionRecord !== null && $this->mNewRevisionRecord !== null );
2196        }
2197
2198        // Whether it succeeds or fails, we don't want to try again
2199        $this->mRevisionsLoaded = true;
2200
2201        $this->loadRevisionIds();
2202
2203        // Load the new RevisionRecord object
2204        if ( $this->mNewid ) {
2205            $this->mNewRevisionRecord = $this->revisionStore->getRevisionById( $this->mNewid );
2206        } else {
2207            $this->mNewRevisionRecord = $this->revisionStore->getRevisionByTitle( $this->getTitle() );
2208        }
2209
2210        if ( !$this->mNewRevisionRecord instanceof RevisionRecord ) {
2211            return false;
2212        }
2213
2214        // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
2215        $this->mNewid = $this->mNewRevisionRecord->getId();
2216        $this->mNewPage = $this->mNewid ?
2217            Title::newFromPageIdentity( $this->mNewRevisionRecord->getPage() ) :
2218            null;
2219
2220        // Load the old RevisionRecord object
2221        $this->mOldRevisionRecord = false;
2222        if ( $this->mOldid ) {
2223            $this->mOldRevisionRecord = $this->revisionStore->getRevisionById( $this->mOldid );
2224        } elseif ( $this->mOldid === 0 ) {
2225            $revRecord = $this->revisionStore->getPreviousRevision( $this->mNewRevisionRecord );
2226            // No previous revision; mark to show as first-version only.
2227            $this->mOldid = $revRecord ? $revRecord->getId() : false;
2228            $this->mOldRevisionRecord = $revRecord ?? false;
2229        } /* elseif ( $this->mOldid === false ) leave mOldRevisionRecord false; */
2230
2231        if ( $this->mOldRevisionRecord === null ) {
2232            return false;
2233        }
2234
2235        if ( $this->mOldRevisionRecord && $this->mOldRevisionRecord->getId() ) {
2236            $this->mOldPage = Title::newFromPageIdentity( $this->mOldRevisionRecord->getPage() );
2237        } else {
2238            $this->mOldPage = null;
2239        }
2240
2241        // Load tags information for both revisions
2242        $dbr = $this->dbProvider->getReplicaDatabase();
2243        $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
2244        if ( $this->mOldid !== false ) {
2245            $tagIds = $dbr->newSelectQueryBuilder()
2246                ->select( 'ct_tag_id' )
2247                ->from( 'change_tag' )
2248                ->where( [ 'ct_rev_id' => $this->mOldid ] )
2249                ->caller( __METHOD__ )->fetchFieldValues();
2250            $tags = [];
2251            foreach ( $tagIds as $tagId ) {
2252                try {
2253                    $tags[] = $changeTagDefStore->getName( (int)$tagId );
2254                } catch ( NameTableAccessException ) {
2255                    continue;
2256                }
2257            }
2258            $this->mOldTags = implode( ',', $tags );
2259        } else {
2260            $this->mOldTags = false;
2261        }
2262
2263        $tagIds = $dbr->newSelectQueryBuilder()
2264            ->select( 'ct_tag_id' )
2265            ->from( 'change_tag' )
2266            ->where( [ 'ct_rev_id' => $this->mNewid ] )
2267            ->caller( __METHOD__ )->fetchFieldValues();
2268        $tags = [];
2269        foreach ( $tagIds as $tagId ) {
2270            try {
2271                $tags[] = $changeTagDefStore->getName( (int)$tagId );
2272            } catch ( NameTableAccessException ) {
2273                continue;
2274            }
2275        }
2276        $this->mNewTags = implode( ',', $tags );
2277
2278        return true;
2279    }
2280
2281    /**
2282     * Load the text of the revisions, as well as revision data.
2283     * When the old revision is missing (mOldRev is false), loading mOldContent is not attempted.
2284     *
2285     * @return bool Whether the content of both revisions could be loaded successfully.
2286     *   (When mOldRev is false, that still counts as a success.)
2287     */
2288    public function loadText() {
2289        if ( $this->mTextLoaded == 2 ) {
2290            return $this->loadRevisionData() &&
2291                ( $this->mOldRevisionRecord === false || $this->mOldContent )
2292                && $this->mNewContent;
2293        }
2294
2295        // Whether it succeeds or fails, we don't want to try again
2296        $this->mTextLoaded = 2;
2297
2298        if ( !$this->loadRevisionData() ) {
2299            return false;
2300        }
2301
2302        if ( $this->mOldRevisionRecord ) {
2303            $this->mOldContent = $this->mOldRevisionRecord->getContent(
2304                SlotRecord::MAIN,
2305                RevisionRecord::FOR_THIS_USER,
2306                $this->getAuthority()
2307            );
2308            if ( $this->mOldContent === null ) {
2309                return false;
2310            }
2311        }
2312
2313        $this->mNewContent = $this->mNewRevisionRecord->getContent(
2314            SlotRecord::MAIN,
2315            RevisionRecord::FOR_THIS_USER,
2316            $this->getAuthority()
2317        );
2318        $this->hookRunner->onDifferenceEngineLoadTextAfterNewContentIsLoaded( $this );
2319        if ( $this->mNewContent === null ) {
2320            return false;
2321        }
2322
2323        return true;
2324    }
2325
2326    /**
2327     * Load the text of the new revision, not the old one
2328     *
2329     * @return bool Whether the content of the new revision could be loaded successfully.
2330     */
2331    public function loadNewText() {
2332        if ( $this->mTextLoaded >= 1 ) {
2333            return $this->loadRevisionData();
2334        }
2335
2336        $this->mTextLoaded = 1;
2337
2338        if ( !$this->loadRevisionData() ) {
2339            return false;
2340        }
2341
2342        $this->mNewContent = $this->mNewRevisionRecord->getContent(
2343            SlotRecord::MAIN,
2344            RevisionRecord::FOR_THIS_USER,
2345            $this->getAuthority()
2346        );
2347
2348        $this->hookRunner->onDifferenceEngineAfterLoadNewText( $this );
2349
2350        return true;
2351    }
2352
2353    /**
2354     * Get the TextDiffer which will be used for rendering text
2355     *
2356     * @return ManifoldTextDiffer
2357     */
2358    protected function getTextDiffer() {
2359        if ( $this->textDiffer === null ) {
2360            $this->textDiffer = new ManifoldTextDiffer(
2361                $this->getContext(),
2362                $this->getDiffLang(),
2363                $this->getConfig()->get( MainConfigNames::DiffEngine ),
2364                $this->getConfig()->get( MainConfigNames::ExternalDiffEngine ),
2365                $this->getConfig()->get( MainConfigNames::Wikidiff2Options )
2366            );
2367        }
2368        return $this->textDiffer;
2369    }
2370
2371    /**
2372     * Get the list of supported text diff formats
2373     *
2374     * @since 1.41
2375     * @return array|string[]
2376     */
2377    public function getSupportedFormats() {
2378        return $this->getTextDiffer()->getFormats();
2379    }
2380
2381    /**
2382     * Get the selected text diff format
2383     *
2384     * @since 1.41
2385     * @return string
2386     */
2387    public function getTextDiffFormat() {
2388        return $this->slotDiffOptions['diff-type'] ?? 'table';
2389    }
2390
2391    /**
2392     * @param RevisionRecord|null $newRevRecord
2393     * @param array $formattedRevisionTools
2394     * @return string
2395     */
2396    private function getMobileFooter( ?RevisionRecord $newRevRecord, array $formattedRevisionTools ): string {
2397        $this->getOutput()->addModuleStyles( [ 'codex-styles' ] );
2398        $summary = Html::rawElement(
2399            'summary',
2400            [ "class" => "cdx-accordion--has-icon" ],
2401            Html::rawElement(
2402                'h3',
2403                [ "class" => "cdx-accordion__header" ],
2404                Html::rawElement(
2405                    'span',
2406                    [ 'class' => 'cdx-accordion__header__title' ],
2407                    Linker::revUserTools( $newRevRecord, !$this->unhide )
2408                )
2409            )
2410        );
2411        $rollbackLink = '';
2412        if ( $this->mNewRevisionRecord->isCurrent() &&
2413            $this->getAuthority()->probablyCan( 'rollback', $this->mNewPage )
2414        ) {
2415            $rollbackLink = Linker::generateRollback(
2416                $this->mNewRevisionRecord,
2417                $this->getContext(),
2418                [ 'noBrackets' ]
2419            );
2420        }
2421        $user = $newRevRecord->getUser();
2422        $userGroups = [];
2423        if ( $user !== null ) {
2424            $userGroups = $this->userGroupManager->getUserGroups( $user );
2425        }
2426        $userGroupCount = count( $userGroups );
2427        $userEditCount = $user === null ? '' : $this->getUserEditCount( $user );
2428        $userGroupList = [];
2429        foreach ( $userGroups as $userGroup ) {
2430            $userGroupList[] = $this->msg( "group-$userGroup" )->escaped();
2431        }
2432        if ( $userGroupCount == 0 ) {
2433            $userGroupsPopover = '';
2434        } else {
2435            $popover = Html::rawElement(
2436                'div',
2437                [ 'class' => 'cdx-popover mw-diff-usergroups-popover', 'role' => 'tooltip' ],
2438                Html::rawElement(
2439                    'div',
2440                    [ 'class' => 'cdx-popover__body' ],
2441                    $this->msg( 'diff-usergroups-list', $this->getLanguage()->commaList( $userGroupList ) )->escaped()
2442                ) . Html::rawElement( 'div', [ 'class' => 'cdx-popover__arrow' ] )
2443            );
2444            $popoverTrigger = Html::element(
2445                'span',
2446                [ 'class' => 'cdx-popover-trigger cdx-button__icon cdx-icon cdx-icon--info ', 'tabindex' => '0' ],
2447            );
2448            $userGroupsPopover = Html::rawElement(
2449                'div',
2450                [ 'class' => 'mw-diff-usermetadata' ],
2451
2452                Html::element( 'span',
2453                    [ 'class' => 'mw-diff-usergroups-popover-text' ],
2454                    $this->msg( 'diff-usergroups', $userGroupCount )->text()
2455                ) .
2456                Html::rawElement(
2457                    'div',
2458                    [ 'class' => 'mw-diff-usergroups-popover-wrapper' ],
2459                    $popoverTrigger . $popover
2460                )
2461            );
2462        }
2463
2464        $content = Html::rawElement(
2465            'div',
2466            [ "class" => "cdx-accordion__content" ],
2467            $userGroupsPopover
2468            . $userEditCount
2469            . $rollbackLink
2470            . implode( '', $formattedRevisionTools )
2471        );
2472        return Html::rawElement(
2473            'details',
2474            [ "class" => "mw-diff-new-mobile-footer-accordion cdx-accordion cdx-accordion--separation-minimal" ],
2475            $summary . $content
2476        );
2477    }
2478
2479}