Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
12.74% covered (danger)
12.74%
98 / 769
13.46% covered (danger)
13.46%
7 / 52
CRAP
0.00% covered (danger)
0.00%
0 / 1
FlaggablePageView
12.74% covered (danger)
12.74%
98 / 769
13.46% covered (danger)
13.46%
7 / 52
55390.78
0.00% covered (danger)
0.00%
0 / 1
 getInstanceCache
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 newFromTitle
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 singleton
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 __construct
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 __clone
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 clear
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 diffRevRecordsAreSet
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 showingStable
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
6
 useSimpleUI
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 getPageViewStabilityModeForUser
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 isPageViewOrDiff
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 isPageView
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 displayTag
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 addStatusIndicator
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
110
 setPageContent
47.83% covered (danger)
47.83%
11 / 23
0.00% covered (danger)
0.00%
0 / 1
32.45
 addTagNoticeIfApplicable
9.09% covered (danger)
9.09%
1 / 11
0.00% covered (danger)
0.00%
0 / 1
9.76
 determineRequestedRevision
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
4.37
 setRobotPolicy
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
56
 makeParserOptions
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 showDraftVersion
0.00% covered (danger)
0.00%
0 / 53
0.00% covered (danger)
0.00%
0 / 1
210
 showStableVersion
38.16% covered (danger)
38.16%
29 / 76
0.00% covered (danger)
0.00%
0 / 1
60.36
 showUnreviewedVersion
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 getTopDiffToggle
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
72
 addToHistView
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 getEditNotices
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
272
 pendingEditNoticeMessage
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 stabilityLogNotice
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 addToNoSuchSection
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 addToCategoryView
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 addReviewForm
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
156
 addStabilizationLink
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
 setActionTabs
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
72
 setViewTabs
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
156
 addDraftTab
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
182
 pageWriteOpRequested
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 getOldIDFromRequest
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 setPendingNotice
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 addToDiffView
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
240
 buildDiffHeaderItems
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 diffLinkAndMarkers
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 diffToStableLink
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
30
 diffReviewMarkers
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
20
 getDiffRevMsgAndClass
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
 setViewFlags
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
90
 isDiffToStable
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
42
 injectPostEditURLParams
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
90
 changeSaveButton
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 editWillRequireReview
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
 editWillBeAutoreviewed
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
72
 addReviewCheck
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
56
 getBaseRevId
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 getAltBaseRevId
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2
3use MediaWiki\Context\ContextSource;
4use MediaWiki\Context\RequestContext;
5use MediaWiki\Diff\DifferenceEngine;
6use MediaWiki\EditPage\EditPage;
7use MediaWiki\Extension\FlaggedRevs\Backend\FlaggedRevsParserCacheFactory;
8use MediaWiki\HookContainer\HookRunner;
9use MediaWiki\Html\Html;
10use MediaWiki\MediaWikiServices;
11use MediaWiki\Message\Message;
12use MediaWiki\Output\OutputPage;
13use MediaWiki\Page\Article;
14use MediaWiki\Page\CacheKeyHelper;
15use MediaWiki\Page\PageIdentity;
16use MediaWiki\Page\ParserOutputAccess;
17use MediaWiki\Parser\ParserOptions;
18use MediaWiki\Parser\ParserOutput;
19use MediaWiki\Request\WebRequest;
20use MediaWiki\Revision\RevisionRecord;
21use MediaWiki\Skin\Skin;
22use MediaWiki\SpecialPage\SpecialPage;
23use MediaWiki\Title\Title;
24use MediaWiki\User\User;
25use MediaWiki\User\UserIdentity;
26use OOUI\ButtonInputWidget;
27use Wikimedia\ObjectCache\MapCacheLRU;
28use Wikimedia\Rdbms\IDBAccessObject;
29
30/**
31 * Class representing a web view of a MediaWiki page
32 */
33class FlaggablePageView extends ContextSource {
34    private static ?MapCacheLRU $instances = null;
35
36    private OutputPage $out;
37    private FlaggableWikiPage $article;
38    /** @var RevisionRecord[]|null Array of `old` and `new` RevisionsRecords for diffs */
39    private ?array $diffRevRecords = null;
40    private bool $isReviewableDiff = false;
41    private bool $isDiffFromStable = false;
42    private bool $isMultiPageDiff = false;
43    private string $reviewNotice = '';
44    private string $diffNoticeBox = '';
45    private ?RevisionRecord $reviewFormRevRecord = null;
46    /**
47     * The stable revision.
48     */
49    private ?FlaggedRevision $srev = null;
50
51    /**
52     * The flagged revision being viewed.
53     */
54    private ?FlaggedRevision $frev = null;
55    private FlaggedRevsParserCacheFactory $flaggedRevsParserCacheFactory;
56
57    /**
58     * @return MapCacheLRU
59     */
60    private static function getInstanceCache(): MapCacheLRU {
61        if ( !self::$instances ) {
62            self::$instances = new MapCacheLRU( 10 );
63        }
64        return self::$instances;
65    }
66
67    /**
68     * Get a FlaggableWikiPage for a given title
69     *
70     * @param PageIdentity $title
71     *
72     * @return self
73     */
74    public static function newFromTitle( PageIdentity $title ): FlaggablePageView {
75        $cache = self::getInstanceCache();
76        $key = CacheKeyHelper::getKeyForPage( $title );
77        $view = $cache->get( $key );
78        if ( !$view ) {
79            $view = new self( $title );
80            $cache->set( $key, $view );
81        }
82        return $view;
83    }
84
85    /**
86     * Get the FlaggablePageView for this request
87     *
88     * @deprecated Use ::newFromTitle() instead
89     * @return self
90     */
91    public static function singleton(): FlaggablePageView {
92        return self::newFromTitle( RequestContext::getMain()->getTitle() );
93    }
94
95    /**
96     * @param Title|PageIdentity $title
97     */
98    private function __construct( PageIdentity $title ) {
99        // Title is injected (a step up from everything being global), but
100        // the rest is still implicitly uses RequestContext::getMain()
101        // via parent class ContextSource::getContext().
102        // TODO: Inject $context and call setContext() here.
103
104        if ( !$title->canExist() ) {
105            throw new InvalidArgumentException( 'FlaggablePageView needs a proper page' );
106        }
107        $this->article = FlaggableWikiPage::getTitleInstance( $title );
108        $this->out = $this->getOutput(); // convenience
109        $this->flaggedRevsParserCacheFactory =
110            MediaWikiServices::getInstance()->getService( FlaggedRevsParserCacheFactory::SERVICE_NAME );
111    }
112
113    private function __clone() {
114    }
115
116    /**
117     * Clear the FlaggablePageView for this request.
118     * Only needed when page redirection changes the environment.
119     */
120    public function clear(): void {
121        self::$instances = null;
122    }
123
124    /**
125     * Check if the old and new diff revs are set for this page view
126     */
127    public function diffRevRecordsAreSet(): bool {
128        return (bool)$this->diffRevRecords;
129    }
130
131    /**
132     * Assuming that the current request is a page view (see isPageView()),
133     * check if a stable version exists and should be displayed.
134     */
135    public function showingStable(): bool {
136        $request = $this->getRequest();
137
138        $canShowStable = (
139            // Page is reviewable and has a stable version
140            $this->article->getStableRev() &&
141            // No parameters requesting a different version of the page
142            !$request->getCheck( 'oldid' )
143        );
144        if ( !$canShowStable ) {
145            return false;
146        }
147
148        // Check if a stable or unstable version is explicitly requested (?stable=1 or ?stable=0).
149        $stableQuery = $request->getIntOrNull( 'stable' );
150        if ( $stableQuery !== null ) {
151            return $stableQuery === 1;
152        }
153
154        // Otherwise follow site/page config and user preferences.
155        $reqUser = $this->getUser();
156        $defaultForUser = $this->getPageViewStabilityModeForUser( $reqUser );
157        return (
158            // User is not configured to prefer current versions
159            $defaultForUser !== FR_SHOW_STABLE_NEVER &&
160            // User explicitly prefers stable versions of pages
161            (
162                $defaultForUser === FR_SHOW_STABLE_ALWAYS ||
163                // Check if the stable version overrides the draft
164                $this->article->getStabilitySettings()['override']
165            )
166        );
167    }
168
169    /**
170     * Should this be using a simple icon-based UI?
171     * Check the user's preferences first, using the site settings as the default.
172     */
173    private function useSimpleUI(): bool {
174        $default = (int)$this->getConfig()->get( 'SimpleFlaggedRevsUI' );
175        $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
176        return (bool)$userOptionsLookup->getOption(
177            $this->getUser(),
178            'flaggedrevssimpleui',
179            $default
180        );
181    }
182
183    /**
184     * What version of pages should this user see by default?
185     *
186     * @param UserIdentity $user The user to get the stability mode for.
187     * @return int One of the FR_SHOW_STABLE_* constants
188     */
189    private function getPageViewStabilityModeForUser( UserIdentity $user ): int {
190        $services = MediaWikiServices::getInstance();
191
192        # Check user preferences (e.g. "show stable version by default?")
193        $userOptionsLookup = $services->getUserOptionsLookup();
194        $preference = (int)$userOptionsLookup->getOption( $user, 'flaggedrevsstable' );
195        if ( $preference === FR_SHOW_STABLE_ALWAYS || $preference === FR_SHOW_STABLE_NEVER ) {
196            return $preference;
197        }
198
199        $userIdentityUtils = $services->getUserIdentityUtils();
200
201        return $userIdentityUtils->isNamed( $user ) ? FR_SHOW_STABLE_NEVER : FR_SHOW_STABLE_DEFAULT;
202    }
203
204    /**
205     * Is this a view page action (including diffs)?
206     */
207    private function isPageViewOrDiff(): bool {
208        $action = $this->getActionName();
209        return $action === 'view' || $action === 'render';
210    }
211
212    /**
213     * Is this a view page action (not including diffs)?
214     */
215    private function isPageView(): bool {
216        $request = $this->getRequest();
217        return $this->isPageViewOrDiff()
218            && $request->getVal( 'diff' ) === null;
219    }
220
221    /**
222     * Output review notice
223     */
224    public function displayTag(): void {
225        // Sanity check that this is a reviewable page
226        if ( $this->article->isReviewable() && $this->reviewNotice ) {
227            $this->out->addSubtitle( $this->reviewNotice );
228        }
229    }
230
231    /**
232     * Adds a visual indicator to the page view based on the review status of the current page revision.
233     *
234     * This indicator helps users quickly identify whether the current revision is stable, a draft,
235     * or unchecked. The indicator is displayed using an appropriate icon and message at the top
236     * of the page, near the title.
237     *
238     * @return void
239     */
240    public function addStatusIndicator(): void {
241        if ( $this->getSkin()->getSkinName() === 'minerva' ) {
242            return;
243        }
244
245        if ( !$this->article->isReviewable() ) {
246            return;
247        }
248
249        // Determine the requested revision type
250        $requestedRevision = $this->determineRequestedRevision();
251
252        // Determine the message key, icon class, and indicator ID based on the requested revision type
253        $statusMessageKey = '';
254        $iconClass = '';
255        $indicatorId = 'mw-fr-revision-toggle'; // Default ID for the indicator
256
257        switch ( $requestedRevision ) {
258            case 'stable':
259                $statusMessageKey = 'revreview-quick-basic-same-title';
260                $iconClass = 'cdx-fr-css-icon-review--status--stable';
261                break;
262            case 'draft':
263                $statusMessageKey = 'revreview-draft-indicator-title';
264                $iconClass = 'cdx-fr-css-icon-review--status--pending';
265                break;
266            case 'unreviewed':
267                $statusMessageKey = $this->useSimpleUI() ? 'revreview-quick-none' : 'revreview-noflagged';
268                $iconClass = 'cdx-fr-css-icon-review--status--unchecked';
269                break;
270            case 'invalid':
271            case 'old':
272                break;
273        }
274
275        // Only proceed if a valid status message key was determined
276        if ( $statusMessageKey ) {
277            // Prepare the attributes for the indicator element
278            $attributes = [
279                'class' => 'mw-fr-review-status-indicator',
280                'id' => $indicatorId,
281            ];
282
283            // Generate the HTML for the indicator
284            $indicatorHtml = Html::rawElement(
285                'div',
286                $attributes,
287                Html::element( 'span', [ 'class' => $iconClass ] ) . $this->msg( $statusMessageKey )->parse()
288            );
289
290            // Add the indicator to the output page
291            $this->out->setIndicators( [ 'indicator-fr-review-status' => $indicatorHtml ] );
292        }
293    }
294
295    /**
296     * Determines what page content to display, prioritizing the most recent stable version if
297     * $wgFlaggedRevsOverride is set to true.
298     *
299     * Handles regular page views (?action=view) only. Does not handle oldids or diffs. VisualEditor
300     * publishes also trigger this behaviour.
301     *
302     * This method replaces the current page view with the last stable version if conditions allow.
303     * It determines the type of revision requested by the user (e.g., 'stable', 'draft', 'unreviewed'),
304     * and adjusts the page content accordingly. Depending on the revision type, it may display tags,
305     * notices, and a review form.
306     *
307     * The method also controls whether the parser cache should be used and whether the parser output
308     * is completed.
309     *
310     * @param bool|ParserOutput|null &$outputDone Indicates whether the parser output is completed.
311     * @param bool &$useParserCache Controls whether the parser cache should be used for this page view.
312     *
313     * @return void
314     */
315    public function setPageContent( &$outputDone, &$useParserCache ): void {
316        $request = $this->getRequest();
317
318        // Only proceed if this is a page view without an oldid parameter, and the page exists and is reviewable
319        if ( !$this->isPageView() || $request->getVal( 'oldid' ) || !$this->article->exists() ||
320            !$this->article->isReviewable() ) {
321            return;
322        }
323
324        // Initialize $tag as an empty string
325        $tag = '';
326
327        // Determine the requested revision type
328        $requestedRevision = $this->determineRequestedRevision();
329
330        switch ( $requestedRevision ) {
331            // "Stable" means that a reviewed version of the page is being displayed. This can happen
332            // if the top revision has been marked reviewed, or if $wgFlaggedRevsOverride is set to
333            // true and a non-reviewer is viewing a page with unreviewed edits. In the latter case,
334            // the unreviewed edits will be hidden and replaced with the "stable", reviewed version.
335            case 'stable':
336                $outputDone = $this->showStableVersion( $this->srev, $tag );
337                $tagTypeClass = $this->article->stableVersionIsSynced() ? 'mw-fr-stable-synced' :
338                    'mw-fr-stable-not-synced';
339                $useParserCache = false;
340                break;
341
342            // "Draft" means that a reviewer is viewing a page with some unreviewed edits. Unreviewed
343            // edits are being displayed. If $wgFlaggedRevsOverride is set to true, unreviewed edits
344            // are only displayed to reviewers.
345            case 'draft':
346                $this->showDraftVersion( $this->srev, $tag );
347                $tagTypeClass = $this->article->stableVersionIsSynced() ? 'mw-fr-draft-synced' :
348                    'mw-fr-draft-not-synced';
349                break;
350
351            // A new article that has never been reviewed. No revisions will be hidden regardless of
352            // settings. We don't have a "stable", reviewed revision yet, so we have to show an
353            // unreviewed revision.
354            case 'unreviewed':
355            default:
356                $outputDone = $this->showUnreviewedVersion( $tag );
357                $tagTypeClass = $this->article->stableVersionIsSynced() ? 'mw-fr-stable-unreviewed' :
358                    'mw-fr-stable-not-unreviewed';
359                break;
360        }
361
362        $this->addTagNoticeIfApplicable( $tag, $tagTypeClass );
363    }
364
365    /**
366     * Add the tag notice if applicable.
367     *
368     * @param string $tag The tag message.
369     * @param string $tagTypeClass The CSS class for the tag type.
370     */
371    private function addTagNoticeIfApplicable( string $tag, string $tagTypeClass ): void {
372        if ( $tag !== '' ) {
373            $notice = Html::openElement( 'div', [ 'id' => 'mw-fr-revision-messages' ] );
374            if ( $this->useSimpleUI() ) {
375                $this->addStatusIndicator();
376                $notice .= $tag;
377            } else {
378                $cssClasses = "mw-fr-basic $tagTypeClass plainlinks noprint";
379                $notice .= FlaggedRevsHTML::addMessageBox( 'block', $tag, [
380                    'class' => $cssClasses,
381                ] );
382            }
383            $notice .= Html::closeElement( 'div' );
384            $this->reviewNotice .= $notice;
385        }
386    }
387
388    /**
389     * Determines the type of revision requested based on the current request.
390     *
391     * This method determines whether to show a stable, old reviewed, draft, or unreviewed version of
392     * the page. If no specific revision is requested, it falls back on the user's preferences and
393     * site configuration to decide which version to show.
394     *
395     * The method updates the stable and flagged revision properties (`$srev` and `$frev`) accordingly.
396     *
397     * @return string The type of revision requested: 'invalid', 'old', 'stable', 'draft', or 'unreviewed'.
398     */
399    private function determineRequestedRevision(): string {
400        $this->srev = $this->article->getStableRev();
401        $this->frev = $this->srev;
402
403        // Determine whether to show the draft or unreviewed version
404        if ( $this->frev ) {
405            if ( $this->showingStable() || $this->article->stableVersionIsSynced() ) {
406                return 'stable';
407            }
408            return 'draft';
409        } else {
410            return 'unreviewed';
411        }
412    }
413
414    /**
415     * If the page has a stable version and it shows by default,
416     * tell search crawlers to index only that version of the page.
417     * Also index the draft as well if they are synced (bug 27173).
418     */
419    public function setRobotPolicy(): void {
420        if ( $this->article->getStableRev() && $this->article->isStableShownByDefault() ) {
421            if ( $this->isPageView() && $this->showingStable() ) {
422                return; // stable version - index this
423            } elseif ( $this->out->getRevisionId() == $this->article->getStable()
424                && $this->article->stableVersionIsSynced()
425            ) {
426                return; // draft that is synced with the stable version - index this
427            }
428            $this->out->setRobotPolicy( 'noindex,nofollow' ); // don't index this version
429        }
430    }
431
432    /**
433     * @param User $reqUser
434     * @return ParserOptions
435     */
436    private function makeParserOptions( User $reqUser ): ParserOptions {
437        $parserOptions = $this->article->makeParserOptions( $reqUser );
438        # T349037: The ArticleParserOptions hook should be broadened to take
439        # a WikiPage (aka $this->article) instead of an Article.  But for now
440        # fake the Article.
441        $article = Article::newFromWikiPage( $this->article, RequestContext::getMain() );
442        # Allow extensions to vary parser options used for article rendering,
443        # in the same way Article does
444        ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
445            ->onArticleParserOptions( $article, $parserOptions );
446
447        return $parserOptions;
448    }
449
450    /**
451     * Displays the draft version of a page.
452     *
453     * This method outputs the draft version of a page, which may differ from the stable version.
454     * It adds a notice indicating that the page is pending review and optionally displays a diff
455     * between the stable and draft versions. If the stable and draft versions are synchronized,
456     * the method does not display a diff. It also adds a "your edit will pending" notice for users
457     * who have made unreviewed edits, especially if the user lacks review rights.
458     *
459     * The method also adjusts the tag that is used for the review box/bar info.
460     *
461     * @param FlaggedRevision $srev The stable revision.
462     * @param string &$tag Reference to the variable holding the review box/bar info.
463     *
464     * @return void
465     */
466    private function showDraftVersion( FlaggedRevision $srev, string &$tag ): void {
467        $request = $this->getRequest();
468        $reqUser = $this->getUser();
469        $time = $this->getLanguage()->date( $srev->getTimestamp(), true );
470        # Get stable version sync status
471        $synced = $this->article->stableVersionIsSynced();
472        if ( $synced ) { // draft == stable
473            $diffToggle = ''; // no diff to show
474        } else { // draft != stable
475            # The user may want the diff (via prefs)
476            $diffToggle = $this->getTopDiffToggle( $srev );
477            if ( $diffToggle != '' ) {
478                $diffToggle = " $diffToggle";
479            }
480            # Make sure there is always a notice bar when viewing the draft.
481            if ( $this->useSimpleUI() ) { // we already one for detailed UI
482                $this->setPendingNotice( $srev, $diffToggle );
483            }
484        }
485        # Give a "your edit is pending" notice to newer users if
486        # an unreviewed edit was completed...
487        $pm = MediaWikiServices::getInstance()->getPermissionManager();
488        if ( $request->getVal( 'shownotice' )
489            && $this->article->getUserText( RevisionRecord::RAW ) == $reqUser->getName()
490            && $this->article->revsArePending()
491            && !$pm->userHasRight( $reqUser, 'review' )
492        ) {
493            $revsSince = $this->article->getPendingRevCount();
494            $pending = $this->msg( 'revreview-edited', $srev->getRevId() )
495                ->numParams( $revsSince )->parse();
496            $anchor = $request->getVal( 'fromsection' );
497            if ( $anchor != null ) {
498                // Hack: reverse some of the Sanitizer::escapeId() encoding
499                $section = urldecode( str_replace( // bug 35661
500                    [ ':', '.' ], [ '%3A', '%' ], $anchor
501                ) );
502                $section = str_replace( '_', ' ', $section ); // prettify
503                $pending .= $this->msg( 'revreview-edited-section', $anchor, $section )
504                    ->parseAsBlock();
505            }
506        # Notice should always use subtitle
507            $this->reviewNotice = Html::openElement( 'div', [
508                    'id' => 'mw-fr-reviewnotice',
509                    'class' => 'cdx-message cdx-message--block cdx-message--notice
510                    flaggedrevs_preview plainlinks noprint',
511                ] )
512                . Html::element( 'span', [ 'class' => 'cdx-message__icon' ] )
513                . Html::rawElement( 'div', [ 'class' => 'cdx-message__content' ], $pending )
514                . Html::closeElement( 'div' );
515        # Otherwise, construct some tagging info for non-printable outputs.
516        # Also, if low profile UI is enabled and the page is synced, skip the tag.
517        # Note: the "your edit is pending" notice has all this info, so we never add both.
518        } elseif ( !( $this->article->lowProfileUI() && $synced ) ) {
519            $revsSince = $this->article->getPendingRevCount();
520            // Simple icon-based UI
521            if ( $this->useSimpleUI() ) {
522                $revisionId = $srev->getRevId();
523                $tag .= FlaggedRevsHTML::reviewDialog(
524                    $this,
525                    $srev,
526                    $revisionId,
527                    $revsSince,
528                    'draft',
529                    $synced,
530                );
531            // Standard UI
532            } else {
533                if ( $synced ) {
534                    $msg = 'revreview-basic-same';
535                } else {
536                    $msg = !$revsSince ? 'revreview-newest-basic-i' : 'revreview-newest-basic';
537                }
538                $msgHTML = $this->msg( $msg, $srev->getRevId(), $time )
539                    ->numParams( $revsSince )->parse();
540                $tag .= $msgHTML . $diffToggle;
541            }
542        }
543    }
544
545    /**
546     * Displays the stable version of a page.
547     *
548     * This method outputs the stable version of a page, which is the version that has been flagged as reviewed.
549     * It generates and caches the `ParserOutput` for the stable version, if not already cached. If the stable
550     * version is synchronized with the current draft, it skips the diff display. The method also adds relevant
551     * tags and notices based on the stability and synchronization status.
552     *
553     * The method ensures that only the stable version or a synced draft is indexed by search engines.
554     *
555     * @param FlaggedRevision $srev The stable revision.
556     * @param string &$tag Reference to the variable holding the review box/bar info.
557     *
558     * @return ?ParserOutput The generated ParserOutput for the stable version, or null if generation fails.
559     */
560    private function showStableVersion( FlaggedRevision $srev, string &$tag ): ?ParserOutput {
561        $reqUser = $this->getUser();
562        $time = $this->getLanguage()->date( $srev->getTimestamp(), true );
563        # Set display revision ID
564        $this->out->setRevisionId( $srev->getRevId() );
565        $synced = $this->article->stableVersionIsSynced();
566        # Construct some tagging
567        if (
568            !( $this->article->lowProfileUI() && $synced )
569        ) {
570            $revsSince = $this->article->getPendingRevCount();
571            // Simple icon-based UI
572            if ( $this->useSimpleUI() ) {
573                # For protection based configs, show lock only if it's not redundant.
574                $revisionId = $srev->getRevId();
575                $tag = FlaggedRevsHTML::reviewDialog(
576                    $this,
577                    $srev,
578                    $revisionId,
579                    $revsSince,
580                    'stable',
581                    $synced,
582                );
583            // Standard UI
584            } else {
585                if ( $synced ) {
586                    $msg = 'revreview-basic-same';
587                } else {
588                    $msg = !$revsSince ? 'revreview-basic-i' : 'revreview-basic';
589                }
590                $tag = $this->msg( $msg, $srev->getRevId(), $time )
591                    ->numParams( $revsSince )->parse();
592            }
593        }
594
595        // TODO: Rewrite to use ParserOutputAccess
596        $parserOptions = $this->makeParserOptions( $reqUser );
597
598        // Check the stable version cache for the parser output
599        $skin = $this->out->getSkin();
600        $poOptions = [
601            // (T391788) This should always be used for full page views
602            'includeDebugInfo' => true,
603            'skin' => $skin,
604            'injectTOC' => $skin->getOptions()['toc'],
605        ];
606        // Copy these to the parser options as well
607        $parserOptions->setOption( 'includeDebugInfo', true );
608        $parserOptions->setOption( 'skin', $skin );
609        $parserOptions->setOption( 'injectTOC', $skin->getOptions()['toc'] );
610
611        // TODO when refactoring this to get rid of $poOptions, check on the discrepancy between $pm->quickUserCan and
612        // $authority->probablyCan in Article::view, as well as check whether the behaviour of these need to be aligned
613        // (additional deprecation warning box), and if so move that aligned behaviour to core
614        $pm = MediaWikiServices::getInstance()->getPermissionManager();
615        if (
616            !$pm->quickUserCan( 'edit', $reqUser, $this->article->getTitle() )
617        ) {
618            $poOptions['enableSectionEditLinks'] = false;
619            $parserOptions->setOption( 'enableSectionEditLinks', false );
620        }
621
622        $parserOptions->enablePostproc();
623        $stableParserCache = $this->flaggedRevsParserCacheFactory->getParserCache( $parserOptions );
624
625        $parserOut = $stableParserCache->get( $this->article, $parserOptions );
626        if ( !$parserOut ) {
627            if ( FlaggedRevs::inclusionSetting() == FR_INCLUDES_CURRENT && $synced ) {
628                # Stable and draft version are identical; check the draft version cache
629                $draftParserOutputAccess = MediaWikiServices::getInstance()->getParserOutputAccess();
630                $draftStatus = $draftParserOutputAccess->getParserOutput(
631                    $this->article, $parserOptions, $srev->getRevisionRecord(),
632                    [
633                        ParserOutputAccess::OPT_NO_AUDIENCE_CHECK => true,
634                        ParserOutputAccess::OPT_POOL_COUNTER =>
635                            ParserOutputAccess::POOL_COUNTER_ARTICLE_VIEW,
636                        ParserOutputAccess::OPT_POOL_COUNTER_FALLBACK => true
637                    ],
638                );
639                $parserOut = $draftStatus->isOK() ? $draftStatus->getValue() : null;
640            }
641
642            if ( !$parserOut ) {
643                # Regenerate the parser output, debouncing parse requests via PoolCounter
644                $status = FlaggedRevs::parseStableRevisionPooled( $srev, $parserOptions );
645                if ( !$status->isGood() ) {
646                    $this->out->disableClientCache();
647                    $this->out->setRobotPolicy( 'noindex,nofollow' );
648                    $statusFormatter = MediaWikiServices::getInstance()
649                        ->getFormatterFactory()
650                        ->getStatusFormatter( $this->getContext() );
651                    $errorText = $statusFormatter->getMessage( $status );
652                    $this->out->addHTML(
653                        Html::errorBox( $this->out->parseAsContent( $errorText->text() ) )
654                    );
655                    return null;
656                }
657                $parserOut = $status->getValue();
658            }
659        }
660
661        if ( !$parserOut ) {
662            $this->out->disableClientCache();
663            $this->out->setRobotPolicy( 'noindex,nofollow' );
664
665            $this->out->addWikiMsg(
666                'missing-article',
667                $this->article->getTitle()->getPrefixedText(),
668                $this->msg( 'missingarticle-rev', $srev->getRevId() )->plain()
669            );
670            return null;
671        }
672
673        # Add the parser output to the page view
674        $this->out->addPostProcessedParserOutput( $parserOut );
675        return $parserOut;
676    }
677
678    /**
679     * Displays a page with no reviewed revisions. Will display the most recent revision.
680     *
681     * This method handles the display of an unreviewed version of the page, showing the appropriate
682     * UI elements based on user preferences (simple or detailed). It sets the appropriate tag and
683     * tag type class to indicate the page's unreviewed status. The method generates a `ParserOutput`
684     * for the unreviewed version and adds it to the output page.
685     *
686     * The method is used when a page has no reviewed revisions in its history. In other words, it
687     * is used for newly created pages by non-reviewers.
688     *
689     * @param string &$tag Reference to the variable holding the review box/bar info.
690     *
691     * @return ParserOutput|bool The generated ParserOutput for the unreviewed version, or null if none is available.
692     */
693    private function showUnreviewedVersion( string &$tag ) {
694        $reqUser = $this->getUser();
695
696        if ( $this->useSimpleUI() ) {
697            $this->addStatusIndicator();
698            $tag = FlaggedRevsHTML::reviewDialog( $this, null, 0, 0, 'unreviewed' );
699        } else {
700            $tag = $this->msg( 'revreview-noflagged' )->parse();
701        }
702
703        // Generate the ParserOutput for the unreviewed version
704        $parserOptions = $this->makeParserOptions( $reqUser );
705        $parserOut = $this->article->getParserOutput( $parserOptions );
706
707        // Set the output revision ID so that the "Permanent link" link works. T384778
708        // (T394381) Note that there is a tiny delay between publishing in VisualEditor
709        // and a Revision ID being available, which affects the page reload right after
710        // VisualEditor saves an edit; if so, skip.
711        $rev = $this->article->getRevisionRecord();
712        if ( $rev ) {
713            $this->out->setRevisionId( $rev->getId() );
714        }
715
716        // Add the ParserOutput to the output page
717        if ( $parserOut ) {
718            $this->out->addParserOutput( $parserOut, $parserOptions, [
719                // (T391788) This should always be used for full page views
720                'includeDebugInfo' => true,
721            ] );
722        }
723
724        return $parserOut;
725    }
726
727    /**
728     * Get a toggle for a collapsible diff-to-stable to add to the review notice as needed
729     * @param FlaggedRevision $srev stable version
730     * @return string|false the html line (either "" or "<diff toggle>")
731     */
732    private function getTopDiffToggle( FlaggedRevision $srev ) {
733        $reqUser = $this->getUser();
734        if ( !MediaWikiServices::getInstance()->getUserOptionsLookup()
735            ->getBoolOption( $reqUser, 'flaggedrevsviewdiffs' )
736        ) {
737            return false; // nothing to do here
738        }
739        # Diff should only show for the draft
740        $oldid = $this->getOldIDFromRequest();
741        $latest = $this->article->getLatest();
742        if ( $oldid && $oldid != $latest ) {
743            return false; // not viewing the draft
744        }
745        $revsSince = $this->article->getPendingRevCount();
746        if ( !$revsSince ) {
747            return false; // no pending changes
748        }
749
750        $title = $this->article->getTitle(); // convenience
751        if ( $srev->getRevId() !== $latest ) {
752            $nEdits = $revsSince - 1; // full diff-to-stable, no need for query
753            if ( $nEdits ) {
754                $limit = 100;
755                try {
756                    $latestRevObj = MediaWikiServices::getInstance()
757                        ->getRevisionLookup()
758                        ->getRevisionById( $latest );
759                    $users = MediaWikiServices::getInstance()
760                        ->getRevisionStore()
761                        ->getAuthorsBetween(
762                            $title->getArticleID(),
763                            $srev->getRevisionRecord(),
764                            $latestRevObj,
765                            null,
766                            $limit
767                        );
768                    $nUsers = count( $users );
769                } catch ( InvalidArgumentException ) {
770                    $nUsers = 0;
771                }
772                $multiNotice = DifferenceEngine::intermediateEditsMsg( $nEdits, $nUsers, $limit );
773            } else {
774                $multiNotice = '';
775            }
776            $this->isDiffFromStable = true; // alter default review form tags
777            // @phan-suppress-next-line SecurityCheck-DoubleEscaped multiNotice is used in a-tag
778            return FlaggedRevsHTML::diffToggle( $title, $srev->getRevId(), $latest, $multiNotice );
779        }
780
781        return '';
782    }
783
784    /**
785     * Adds stable version tags to page when viewing history
786     */
787    public function addToHistView(): void {
788        # Add a notice if there are pending edits...
789        $srev = $this->article->getStableRev();
790        if ( $srev && $this->article->revsArePending() ) {
791            $revsSince = $this->article->getPendingRevCount();
792            $noticeContent = $this->pendingEditNoticeMessage( $srev, $revsSince )->parse();
793            $tag = FlaggedRevsHTML::addMessageBox( 'block', $noticeContent, [
794                'id' => 'mw-fr-revision-tag-edit',
795                'class' => 'flaggedrevs_notice plainlinks'
796            ] );
797            $this->out->addHTML( $tag );
798        }
799    }
800
801    /**
802     * @param Title $title
803     * @param int $oldid
804     * @param string[] &$notices
805     */
806    public function getEditNotices( Title $title, int $oldid, array &$notices ): void {
807        if ( !$this->article->isReviewable() ) {
808            return;
809        }
810        $article = new Article( $title, $oldid );
811        $reqUser = $this->getUser();
812
813        $lines = [];
814
815        $log = $this->stabilityLogNotice();
816        if ( $log ) {
817            $lines[] = $log;
818        } elseif ( $this->editWillRequireReview( $article, false ) ) {
819            $lines[] = $this->msg( 'revreview-editnotice' )->parseAsBlock();
820        }
821        $frev = $this->article->getStableRev();
822        if ( $frev && $this->article->revsArePending() ) {
823            $revsSince = $this->article->getPendingRevCount();
824            $pendingMsg = $this->pendingEditNoticeMessage( $frev, $revsSince );
825            $lines[] = $pendingMsg->parseAsBlock();
826        }
827        $latestId = $this->article->getLatest();
828        $revId  = $oldid ?: $latestId;
829        if ( $frev && $frev->getRevId() < $latestId // changes were made
830            && MediaWikiServices::getInstance()->getUserOptionsLookup()
831                ->getBoolOption( $reqUser, 'flaggedrevseditdiffs' ) // not disabled via prefs
832            && $revId === $latestId // only for current rev
833        ) {
834            $lines[] = '<p>' . $this->msg( 'review-edit-diff' )->parse() . ' ' .
835                FlaggedRevsHTML::diffToggle( $this->article->getTitle(), $frev->getRevId(), $revId ) . '</p>';
836        }
837
838        $srev = $this->article->getStableRev();
839        $revsSince = $this->article->getPendingRevCount();
840
841        if ( $frev && $this->article->onlyTemplatesPending() && $revsSince === 0 && $srev ) {
842            $time = $this->getLanguage()->userTimeAndDate( $srev->getTimestamp(), $this->getUser() );
843            $lines[] = '<p>' . $this->msg( 'revreview-newest-basic-i',
844                    $srev->getRevId(), $time )->numParams( $revsSince )->parse() . '</p>';
845        }
846
847        if ( $lines ) {
848            $lineMessages = FlaggedRevsHTML::addMessageBox( 'block', implode( "\n", $lines ) );
849
850            $notices['flaggedrevs_editnotice'] = Html::rawElement( 'div', [
851                'class' => 'mw-fr-edit-messages',
852            ], $lineMessages );
853        }
854    }
855
856    /**
857     * Creates "stable rev reviewed on"/"x pending edits" message
858     */
859    private function pendingEditNoticeMessage( FlaggedRevision $frev, int $revsSince ): Message {
860        $time = $this->getLanguage()->date( $frev->getTimestamp(), true );
861        # Add message text for pending edits
862        return $this->msg( 'revreview-pending-basic', $frev->getRevId(), $time )->numParams( $revsSince );
863    }
864
865    private function stabilityLogNotice(): string {
866        if ( $this->article->isPageLocked() ) {
867            $msg = 'revreview-locked';
868        } elseif ( $this->article->isPageUnlocked() ) {
869            $msg = 'revreview-unlocked';
870        } else {
871            return '';
872        }
873        $s = $this->msg( $msg )->parseAsBlock();
874        return $s . FlaggedRevsHTML::stabilityLogExcerpt( $this->article->getTitle() );
875    }
876
877    public function addToNoSuchSection( string &$s ): void {
878        $srev = $this->article->getStableRev();
879        # Add notice for users that may have clicked "edit" for a
880        # section in the stable version that isn't in the draft.
881        if ( $srev && $this->article->revsArePending() ) {
882            $revsSince = $this->article->getPendingRevCount();
883            if ( $revsSince ) {
884                $s .= "<div class='flaggedrevs_editnotice plainlinks'>" .
885                    $this->msg( 'revreview-pending-nosection',
886                        $srev->getRevId() )->numParams( $revsSince )->parse() . "</div>";
887            }
888        }
889    }
890
891    /**
892     * Add unreviewed pages links
893     */
894    public function addToCategoryView(): void {
895        $reqUser = $this->getUser();
896        $pm = MediaWikiServices::getInstance()->getPermissionManager();
897        if ( !$pm->userHasRight( $reqUser, 'review' ) ) {
898            return;
899        }
900
901        if ( !FlaggedRevs::useOnlyIfProtected() ) {
902            # Add links to lists of unreviewed pages and pending changes in this category
903            $category = $this->article->getTitle()->getText();
904            $this->out->addSubtitle(
905                Html::rawElement(
906                    'span',
907                    [ 'class' => 'plainlinks', 'id' => 'mw-fr-category-oldreviewed' ],
908                    $this->msg( 'flaggedrevs-categoryview', urlencode( $category ) )->parse()
909                )
910            );
911        }
912    }
913
914    /**
915     * Add review form to pages when necessary on a regular page view (action=view).
916     * If $output is an OutputPage then this prepends the form onto it.
917     * If $output is a string then this appends the review form to it.
918     * @param string|OutputPage &$output
919     */
920    public function addReviewForm( &$output ): void {
921        # User must have review rights
922        $reqUser = $this->getUser();
923        if ( !MediaWikiServices::getInstance()->getPermissionManager()
924            ->userHasRight( $reqUser, 'review' )
925        ) {
926            return;
927        }
928        # Page must exist and be reviewable
929        if ( !$this->article->exists() || !$this->article->isReviewable() ) {
930            return;
931        }
932        # Must be a page view action...
933        if ( !$this->isPageViewOrDiff() ) {
934            return;
935        }
936        // Determine the revision to be reviewed, either from the current output or fallback to
937        // the latest revision for unchecked pages
938        $revisionId = $this->out->getRevisionId() ?: $this->article->getLatest();
939        $revRecord = $this->reviewFormRevRecord ?: MediaWikiServices::getInstance()
940            ->getRevisionLookup()
941            ->getRevisionById( $revisionId );
942
943        # Build the review form as needed
944        if ( $revRecord && ( !$this->diffRevRecords || $this->isReviewableDiff ) ) {
945            $form = new RevisionReviewFormUI(
946                $this->getContext(),
947                $this->article,
948                $revRecord
949            );
950            # Default tags and existence of "reject" button depend on context
951            if ( $this->diffRevRecords ) {
952                $oldRevRecord = $this->diffRevRecords['old'];
953                $form->setDiffPriorRevRecord( $oldRevRecord );
954            }
955            # Review notice box goes in top of form
956            $form->setTopNotice( $this->diffNoticeBox );
957
958            [ $html, ] = $form->getHtml();
959            # Diff action: place the form at the top of the page
960            if ( $output instanceof OutputPage ) {
961                $output->prependHTML( $html );
962            # View action: place the form at the bottom of the page
963            } else {
964                $output .= $html;
965            }
966        }
967    }
968
969    /**
970     * Add link to stable version setting to protection form
971     */
972    public function addStabilizationLink(): void {
973        $request = $this->getRequest();
974        if ( FlaggedRevs::useOnlyIfProtected() ) {
975            // Simple custom levels set for action=protect
976            return;
977        }
978        # Check only if the title is reviewable
979        if ( !FlaggedRevs::inReviewNamespace( $this->article ) ) {
980            return;
981        }
982        $action = $request->getVal( 'action', 'view' );
983        if ( $action == 'protect' || $action == 'unprotect' ) {
984            $title = SpecialPage::getTitleFor( 'Stabilization' );
985            # Give a link to the page to configure the stable version
986            $frev = $this->article->getStableRev();
987            if ( !$frev ) {
988                $msg = 'revreview-visibility-nostable';
989            } elseif ( $frev->getRevId() == $this->article->getLatest() ) {
990                $msg = 'revreview-visibility-synced';
991            } else {
992                $msg = 'revreview-visibility-outdated';
993            }
994            $this->out->prependHTML( "<span class='revreview-visibility $msg plainlinks'>" .
995                $this->msg( $msg, $title->getPrefixedText() )->parse() . '</span>' );
996        }
997    }
998
999    /**
1000     * Modify an array of action links, as used by SkinTemplateNavigation and
1001     * SkinTemplateTabs, to include flagged revs UI elements
1002     *
1003     * @param array &$actions
1004     */
1005    public function setActionTabs( array &$actions ): void {
1006        $reqUser = $this->getUser();
1007
1008        if ( FlaggedRevs::useOnlyIfProtected() ) {
1009            return; // simple custom levels set for action=protect
1010        }
1011
1012        if ( !FlaggedRevs::inReviewNamespace( $this->article ) ) {
1013            return; // Only reviewable pages need these tabs
1014        }
1015
1016        // Check if we should show a stabilization tab
1017        $pm = MediaWikiServices::getInstance()->getPermissionManager();
1018        if (
1019            !$this->article->getTitle()->isTalkPage() &&
1020            !isset( $actions['protect'] ) &&
1021            !isset( $actions['unprotect'] ) &&
1022            $pm->userHasRight( $reqUser, 'stablesettings' ) &&
1023            $this->article->exists()
1024        ) {
1025            $stableTitle = SpecialPage::getTitleFor( 'Stabilization' );
1026            // Add the tab
1027            $actions['default'] = [
1028                'class' => false,
1029                'text' => $this->msg( 'stabilization-tab' )->text(),
1030                'href' => $stableTitle->getLocalURL( 'page=' . $this->article->getTitle()->getPrefixedURL() )
1031            ];
1032        }
1033    }
1034
1035    /**
1036     * Modify an array of tab links to include flagged revs UI elements
1037     * @param Skin $skin
1038     * @param array[] &$views
1039     */
1040    public function setViewTabs( Skin $skin, array &$views ): void {
1041        if ( !FlaggedRevs::inReviewNamespace( $this->article ) ) {
1042            // Short-circuit for non-reviewable pages
1043            return;
1044        }
1045        # Hack for bug 16734 (some actions update and view all at once)
1046        if ( $this->pageWriteOpRequested() &&
1047            MediaWikiServices::getInstance()->getDBLoadBalancer()->hasOrMadeRecentPrimaryChanges()
1048        ) {
1049            # Tabs need to reflect the new stable version so users actually
1050            # see the results of their action (i.e. "delete"/"rollback")
1051            $this->article->loadPageData( IDBAccessObject::READ_LATEST );
1052        }
1053        $srev = $this->article->getStableRev();
1054        if ( !$srev ) {
1055            // No stable revision exists
1056            return;
1057        }
1058        $synced = $this->article->stableVersionIsSynced();
1059        $pendingEdits = !$synced && $this->article->isStableShownByDefault();
1060        // Set the edit tab names as needed...
1061        if ( $pendingEdits && $this->isPageView() && $this->showingStable() ) {
1062            // bug 31489; direct user to current
1063            if ( isset( $views['edit'] ) ) {
1064                $views['edit']['href'] = $skin->getTitle()->getFullURL( 'action=edit' );
1065            }
1066            if ( isset( $views['viewsource'] ) ) {
1067                $views['viewsource']['href'] = $skin->getTitle()->getFullURL( 'action=edit' );
1068            }
1069            // Instruct alternative editors like VisualEditor to load the latest ("current")
1070            // revision for editing, rather than the one from 'wgRevisionId'
1071            $skin->getOutput()->addJsConfigVars( 'wgEditLatestRevision', true );
1072        }
1073        # Add "pending changes" tab if the page is not synced
1074        if ( !$synced ) {
1075            $this->addDraftTab( $views, $srev );
1076        }
1077    }
1078
1079    /**
1080     * Add "pending changes" tab and set tab selection CSS
1081     * @param array[] &$views
1082     * @param FlaggedRevision $srev
1083     */
1084    private function addDraftTab( array &$views, FlaggedRevision $srev ): void {
1085        $request = $this->getRequest();
1086        $title = $this->article->getTitle(); // convenience
1087        $tabs = [
1088            'read' => [ // view stable
1089                'text'  => '', // unused
1090                'href'  => $title->getLocalURL( 'stable=1' ),
1091                'class' => ''
1092            ],
1093            'draft' => [ // view draft
1094                'text'  => $this->msg( 'revreview-current' )->text(),
1095                'href'  => $title->getLocalURL( 'stable=0&redirect=no' ),
1096                'class' => 'collapsible'
1097            ],
1098        ];
1099        // Set tab selection CSS
1100        if ( ( $this->isPageView() && $this->showingStable() ) || $request->getVal( 'stableid' ) ) {
1101            // We are looking a the stable version or an old reviewed one
1102            $tabs['read']['class'] = 'selected';
1103        } elseif ( $this->isPageViewOrDiff() ) {
1104            $ts = null;
1105            if ( $this->out->getRevisionId() ) { // @TODO: avoid same query in Skin.php
1106                if ( $this->out->getRevisionId() == $this->article->getLatest() ) {
1107                    $ts = $this->article->getTimestamp(); // skip query
1108                } else {
1109                    $ts = MediaWikiServices::getInstance()
1110                        ->getRevisionLookup()
1111                        ->getTimestampFromId( $this->out->getRevisionId() );
1112                }
1113            }
1114            // Are we looking at a pending revision?
1115            if ( $ts > $srev->getRevTimestamp() ) { // bug 15515
1116                $tabs['draft']['class'] .= ' selected';
1117            // Are there *just* pending template changes.
1118            } elseif ( $this->article->onlyTemplatesPending()
1119                && $this->out->getRevisionId() == $this->article->getStable()
1120            ) {
1121                $tabs['draft']['class'] .= ' selected';
1122            // Otherwise, fallback to regular tab behavior
1123            } else {
1124                $tabs['read']['class'] = 'selected';
1125            }
1126        }
1127        $newViews = [];
1128        // Rebuild tabs array
1129        $previousTab = null;
1130        foreach ( $views as $tabAction => $data ) {
1131            // The 'view' tab. Make it go to the stable version...
1132            if ( $tabAction == 'view' ) {
1133                // 'view' for content page; make it go to the stable version
1134                $newViews[$tabAction]['text'] = $data['text']; // keep tab name
1135                $newViews[$tabAction]['href'] = $tabs['read']['href'];
1136                $newViews[$tabAction]['class'] = $tabs['read']['class'];
1137            // All other tabs...
1138            } else {
1139                if ( $previousTab == 'view' ) {
1140                    $newViews['current'] = $tabs['draft'];
1141                }
1142                $newViews[$tabAction] = $data;
1143            }
1144            $previousTab = $tabAction;
1145        }
1146        // Replaces old tabs with new tabs
1147        $views = $newViews;
1148    }
1149
1150    /**
1151     * Check if a flaggedrevs relevant write op was done this page view
1152     */
1153    private function pageWriteOpRequested(): bool {
1154        $request = $this->getRequest();
1155        # Hack for bug 16734 (some actions update and view all at once)
1156        $action = $request->getVal( 'action' );
1157        return $action === 'rollback' ||
1158            ( $action === 'delete' && $request->wasPosted() );
1159    }
1160
1161    private function getOldIDFromRequest(): int {
1162        $article = Article::newFromWikiPage( $this->article, RequestContext::getMain() );
1163        return $article->getOldIDFromRequest();
1164    }
1165
1166    /**
1167     * Adds a notice saying that this revision is pending review
1168     *
1169     * @param FlaggedRevision $srev The stable version
1170     * @param string $diffToggle either "" or " <diff toggle><diff div>"
1171     */
1172    private function setPendingNotice( FlaggedRevision $srev, string $diffToggle = '' ): void {
1173        $time = $this->getLanguage()->date( $srev->getTimestamp(), true );
1174        $revsSince = $this->article->getPendingRevCount();
1175        $msg = !$revsSince ? 'revreview-newest-basic-i' : 'revreview-newest-basic';
1176        # Add bar msg to the top of the page...
1177        $msgHTML = $this->msg( $msg, $srev->getRevId(), $time )->numParams( $revsSince )->parse();
1178
1179        if ( !$this->useSimpleUI() ) {
1180            $this->reviewNotice .= FlaggedRevsHTML::addMessageBox( 'block', $msgHTML . $diffToggle );
1181        }
1182    }
1183
1184    /**
1185     * When viewing a diff:
1186     * (a) Add the review form to the top of the page
1187     * (b) Mark off which versions are checked or not
1188     * (c) When comparing the stable revision to the current:
1189     *   (i)  Show a tag with some explanation for the diff
1190     */
1191    public function addToDiffView( ?RevisionRecord $oldRevRecord, ?RevisionRecord $newRevRecord ): void {
1192        $pm = MediaWikiServices::getInstance()->getPermissionManager();
1193        $request = $this->getRequest();
1194        $reqUser = $this->getUser();
1195        # Multi-page diffs are useless and misbehave (bug 19327). Sanity check $newRevRecord.
1196        if ( $this->isMultiPageDiff || !$newRevRecord ) {
1197            return;
1198        # Page must be reviewable.
1199        } elseif ( !$this->article->isReviewable() ) {
1200            return;
1201        }
1202        $srev = $this->article->getStableRev();
1203        if ( $srev && $this->isReviewableDiff ) {
1204            $this->reviewFormRevRecord = $newRevRecord;
1205        }
1206        # Check if this is a diff-to-stable. If so:
1207        # (a) prompt reviewers to review the changes
1208        if ( $srev
1209            && $this->isDiffFromStable
1210            && !$this->article->stableVersionIsSynced() // pending changes
1211        ) {
1212            # If there are pending revs, notify the user...
1213            if ( $this->article->revsArePending() ) {
1214                # If the user can review then prompt them to review them...
1215                if ( $pm->userHasRight( $reqUser, 'review' ) ) {
1216                    // Reviewer just edited...
1217                    if ( $request->getInt( 'shownotice' )
1218                        && $newRevRecord->isCurrent()
1219                        && $newRevRecord->getUser( RevisionRecord::RAW )
1220                            ->equals( $reqUser )
1221                    ) {
1222                        $title = $this->article->getTitle(); // convenience
1223                        // @TODO: make diff class cache this
1224                        $n = MediaWikiServices::getInstance()
1225                            ->getRevisionStore()
1226                            ->countRevisionsBetween(
1227                                $title->getArticleID(),
1228                                $oldRevRecord,
1229                                $newRevRecord
1230                            );
1231                        if ( $n ) {
1232                            $msg = 'revreview-update-edited-prev'; // previous pending edits
1233                        } else {
1234                            $msg = 'revreview-update-edited'; // just couldn't autoreview
1235                        }
1236                    // All other cases...
1237                    } else {
1238                        $msg = 'revreview-update'; // generic "please review" notice...
1239                    }
1240                    // add as part of form
1241                    $this->diffNoticeBox = $this->msg( $msg )->parseAsBlock();
1242                }
1243            }
1244        }
1245        # Add a link to diff from stable to current as needed.
1246        # Show review status of the diff revision(s). Uses a <table>.
1247        $this->out->addHTML(
1248            '<div id="mw-fr-diff-headeritems">' .
1249            self::diffLinkAndMarkers(
1250                $this->article,
1251                $oldRevRecord,
1252                $newRevRecord
1253            ) .
1254            '</div>'
1255        );
1256    }
1257
1258    /**
1259     * get new diff header items for in-place page review
1260     */
1261    public static function buildDiffHeaderItems( int $oldid, int $newid ): string {
1262        $revLookup = MediaWikiServices::getInstance()->getRevisionLookup();
1263        $newRevRecord = $revLookup->getRevisionById( $newid );
1264        if ( $newRevRecord && $newRevRecord->getPageAsLinkTarget() ) {
1265            $oldRevRecord = $revLookup->getRevisionById( $oldid );
1266            $fa = FlaggableWikiPage::getTitleInstance(
1267                Title::newFromLinkTarget( $newRevRecord->getPageAsLinkTarget() )
1268            );
1269            return self::diffLinkAndMarkers( $fa, $oldRevRecord, $newRevRecord );
1270        }
1271        return '';
1272    }
1273
1274    /**
1275     * (a) Add a link to diff from stable to current as needed
1276     * (b) Show review status of the diff revision(s). Uses a <table>.
1277     * Note: used by ajax function to rebuild diff page
1278     */
1279    private static function diffLinkAndMarkers(
1280        FlaggableWikiPage $article,
1281        ?RevisionRecord $oldRevRecord,
1282        ?RevisionRecord $newRevRecord
1283    ): string {
1284        $s = '<form id="mw-fr-diff-dataform">';
1285        $s .= Html::hidden( 'oldid', $oldRevRecord ? $oldRevRecord->getId() : 0 );
1286        $s .= Html::hidden( 'newid', $newRevRecord ? $newRevRecord->getId() : 0 );
1287        $s .= "</form>\n";
1288        if ( $newRevRecord && $oldRevRecord ) { // sanity check
1289            $s .= self::diffToStableLink( $article, $oldRevRecord, $newRevRecord );
1290            $s .= self::diffReviewMarkers( $article, $oldRevRecord, $newRevRecord );
1291        }
1292        return $s;
1293    }
1294
1295    /**
1296     * Add a link to diff-to-stable for reviewable pages
1297     */
1298    private static function diffToStableLink(
1299        FlaggableWikiPage $article,
1300        RevisionRecord $oldRevRecord,
1301        RevisionRecord $newRevRecord
1302    ): string {
1303        $srev = $article->getStableRev();
1304        if ( !$srev ) {
1305            return ''; // nothing to do
1306        }
1307        $review = '';
1308        # Is this already the full diff-to-stable?
1309        $fullStableDiff = $newRevRecord->isCurrent()
1310            && self::isDiffToStable(
1311                $srev,
1312                $oldRevRecord,
1313                $newRevRecord
1314            );
1315        # Make a link to the full diff-to-stable if:
1316        # (a) Actual revs are pending and (b) We are not viewing the full diff-to-stable
1317        if ( $article->revsArePending() && !$fullStableDiff ) {
1318            $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1319            $reviewLink = $linkRenderer->makeKnownLink(
1320                $article->getTitle(),
1321                wfMessage( 'review-diff2stable' )->text(),
1322                [],
1323                [ 'oldid' => $srev->getRevId(), 'diff' => 'cur' ]
1324            );
1325            $reviewWrapped = wfMessage( 'parentheses' )->rawParams( $reviewLink )->escaped();
1326            $review = "<div class='fr-diff-to-stable' style='text-align: center;'>$reviewWrapped</div>";
1327        }
1328        return $review;
1329    }
1330
1331    /**
1332     * Add [checked version] and such to left and right side of diff
1333     */
1334    private static function diffReviewMarkers(
1335        FlaggableWikiPage $article,
1336        ?RevisionRecord $oldRevRecord,
1337        ?RevisionRecord $newRevRecord
1338    ): string {
1339        $table = '';
1340        $srev = $article->getStableRev();
1341        # Diff between two revisions
1342        if ( $oldRevRecord && $newRevRecord ) {
1343            [ $msg, $class ] = self::getDiffRevMsgAndClass( $oldRevRecord, $srev );
1344            $table .= "<table class='fr-diff-ratings'><tr>";
1345            $table .= "<td style='text-align: center; width: 50%;'>";
1346            // @todo i18n FIXME: Hard coded brackets
1347            $table .= "<span class='$class'>[" .
1348                wfMessage( $msg )->escaped() . "]</span>";
1349
1350            [ $msg, $class ] = self::getDiffRevMsgAndClass( $newRevRecord, $srev );
1351            $table .= "</td><td style='text-align: center; width: 50%;'>";
1352            // @todo i18n FIXME: Hard coded brackets
1353            $table .= "<span class='$class'>[" .
1354                wfMessage( $msg )->escaped() . "]</span>";
1355
1356            $table .= "</td></tr></table>\n";
1357        # New page "diffs" - just one rev
1358        } elseif ( $newRevRecord ) {
1359            [ $msg, $class ] = self::getDiffRevMsgAndClass( $newRevRecord, $srev );
1360            $table .= "<table class='fr-diff-ratings'>";
1361            $table .= "<tr><td style='text-align: center;'><span class='$class'>";
1362            // @todo i18n FIXME: Hard coded brackets
1363            $table .= '[' . wfMessage( $msg )->escaped() . ']';
1364            $table .= "</span></td></tr></table>\n";
1365        }
1366        return $table;
1367    }
1368
1369    /**
1370     * @return string[]
1371     */
1372    private static function getDiffRevMsgAndClass(
1373        RevisionRecord $revRecord, ?FlaggedRevision $srev
1374    ): array {
1375        $checked = FlaggedRevision::revIsFlagged( $revRecord->getId() );
1376        if ( $checked ) {
1377            $msg = 'revreview-hist-basic';
1378        } else {
1379            $msg = ( $srev && $revRecord->getTimestamp() > $srev->getRevTimestamp() ) ? // bug 15515
1380                'revreview-hist-pending' :
1381                'revreview-hist-draft';
1382        }
1383        return [ $msg, $checked ? 'flaggedrevs-color-1' : 'flaggedrevs-color-0' ];
1384    }
1385
1386    /**
1387     * Set $this->isDiffFromStable and $this->isMultiPageDiff fields
1388     */
1389    public function setViewFlags(
1390        DifferenceEngine $diff,
1391        ?RevisionRecord $oldRevRecord,
1392        ?RevisionRecord $newRevRecord
1393    ): void {
1394        // We only want valid diffs that actually make sense...
1395        if ( !( $newRevRecord
1396            && $oldRevRecord
1397            && $newRevRecord->getTimestamp() >= $oldRevRecord->getTimestamp() )
1398        ) {
1399            return;
1400        }
1401
1402        // Is this a diff between two pages?
1403        if ( $newRevRecord->getPageId() != $oldRevRecord->getPageId() ) {
1404            $this->isMultiPageDiff = true;
1405        // Is there a stable version?
1406        } elseif ( $this->article->isReviewable() ) {
1407            $srev = $this->article->getStableRev();
1408            // Is this a diff of a draft rev against the stable rev?
1409            if ( self::isDiffToStable(
1410                $srev,
1411                $oldRevRecord,
1412                $newRevRecord
1413            ) ) {
1414                $this->isDiffFromStable = true;
1415                $this->isReviewableDiff = true;
1416            // Is this a diff of a draft rev against a reviewed rev?
1417            } elseif (
1418                FlaggedRevision::newFromTitle(
1419                    $diff->getTitle(),
1420                    $oldRevRecord->getId()
1421                ) ||
1422                FlaggedRevision::newFromTitle(
1423                    $diff->getTitle(),
1424                    $newRevRecord->getId()
1425                )
1426            ) {
1427                $this->isReviewableDiff = true;
1428            }
1429        }
1430
1431        $this->diffRevRecords = [
1432            'old' => $oldRevRecord,
1433            'new' => $newRevRecord
1434        ];
1435    }
1436
1437    /**
1438     * Is a diff from $oldRev to $newRev a diff-to-stable?
1439     */
1440    private static function isDiffToStable(
1441        ?FlaggedRevision $srev,
1442        ?RevisionRecord $oldRevRecord,
1443        ?RevisionRecord $newRevRecord
1444    ): bool {
1445        return ( $srev
1446            && $oldRevRecord
1447            && $newRevRecord
1448            && $oldRevRecord->getPageId() === $newRevRecord->getPageId() // no multipage diffs
1449            && $oldRevRecord->getId() == $srev->getRevId()
1450            && $newRevRecord->getTimestamp() >= $oldRevRecord->getTimestamp() // no backwards diffs
1451        );
1452    }
1453
1454    /**
1455     * Redirect users out to review the changes to the stable version.
1456     * Only for people who can review and for pages that have a stable version.
1457     */
1458    public function injectPostEditURLParams( string &$sectionAnchor, string &$extraQuery ): void {
1459        $reqUser = $this->getUser();
1460        $this->article->loadPageData( IDBAccessObject::READ_LATEST );
1461        # Get the stable version from the primary DB
1462        $frev = $this->article->getStableRev();
1463        if ( !$frev ) {
1464            // Only for pages with stable versions
1465            return;
1466        }
1467
1468        $params = [];
1469        $pm = MediaWikiServices::getInstance()->getPermissionManager();
1470        // If the edit was not autoreviewed, and the user can actually make a
1471        // new stable version, then go to the diff...
1472        if ( $this->article->revsArePending() && $frev->userCanSetTag( $reqUser ) ) {
1473            $params += [ 'oldid' => $frev->getRevId(), 'diff' => 'cur', 'shownotice' => 1 ];
1474        // ...otherwise, go to the draft revision after completing an edit.
1475        // This allows for users to immediately see their changes. Even if the stable
1476        // and draft page match, we can avoid a parse due to FR_INCLUDES_STABLE.
1477        } else {
1478            $params += [ 'stable' => 0 ];
1479            // Show a notice at the top of the page for non-reviewers...
1480            if ( $this->article->revsArePending()
1481                && $this->article->isStableShownByDefault()
1482                && !$pm->userHasRight( $reqUser, 'review' )
1483            ) {
1484                $params += [ 'shownotice' => 1 ];
1485                if ( $sectionAnchor ) {
1486                    // Pass a section parameter in the URL as needed to add a link to
1487                    // the "your changes are pending" box on the top of the page...
1488                    $params += [ 'fromsection' => substr( $sectionAnchor, 1 ) ]; // strip #
1489                    $sectionAnchor = ''; // go to the top of the page to see notice
1490                }
1491            }
1492        }
1493        if ( $extraQuery !== '' ) {
1494            $extraQuery .= '&';
1495        }
1496        $extraQuery .= wfArrayToCgi( $params ); // note: EditPage will add initial "&"
1497    }
1498
1499    /**
1500     * If submitting the edit will leave it pending, then change the button text
1501     * Note: interacts with 'review pending changes' checkbox
1502     * @param EditPage $editPage
1503     * @param ButtonInputWidget[] $buttons
1504     */
1505    public function changeSaveButton( EditPage $editPage, array $buttons ): void {
1506        if ( !$this->editWillRequireReview( $editPage->getArticle(), $editPage->isConflict ) ) {
1507            // Edit will go live or be reviewed on save
1508            return;
1509        }
1510        if ( isset( $buttons['save'] ) ) {
1511            $buttonLabel = $this->msg( 'revreview-submitedit' )->text();
1512            $buttons['save']->setLabel( $buttonLabel );
1513            $buttonTitle = $this->msg( 'revreview-submitedit-title' )->text();
1514            $buttons['save']->setTitle( $buttonTitle );
1515        }
1516    }
1517
1518    /**
1519     * If this edit will not go live on submit (accounting for wpReviewEdit)
1520     */
1521    private function editWillRequireReview( Article $article, bool $isConflict ): bool {
1522        $request = $this->getRequest(); // convenience
1523        $title = $this->article->getTitle(); // convenience
1524        if ( !$this->article->editsRequireReview() || $this->editWillBeAutoreviewed( $article, $isConflict ) ) {
1525            return false; // edit will go live immediately
1526        } elseif ( $request->getCheck( 'wpReviewEdit' ) &&
1527            MediaWikiServices::getInstance()->getPermissionManager()
1528                ->userCan( 'review', $this->getUser(), $title )
1529        ) {
1530            return false; // edit checked off to be reviewed on save
1531        }
1532        return true; // edit needs review
1533    }
1534
1535    /**
1536     * If this edit will be auto-reviewed on submit
1537     * Note: checking wpReviewEdit does not count as auto-reviewed
1538     */
1539    private function editWillBeAutoreviewed( Article $article, bool $isConflict ): bool {
1540        $title = $this->article->getTitle(); // convenience
1541        if ( !$this->article->isReviewable() ) {
1542            return false;
1543        }
1544        if ( MediaWikiServices::getInstance()->getPermissionManager()
1545            ->quickUserCan( 'autoreview', $this->getUser(), $title )
1546        ) {
1547            if ( FlaggedRevs::autoReviewNewPages() && !$this->article->exists() ) {
1548                return true; // edit will be autoreviewed
1549            }
1550
1551            $baseRevId = self::getBaseRevId( $article, $isConflict, $this->getRequest() );
1552            $baseRevId2 = self::getAltBaseRevId( $article, $isConflict, $this->getRequest() );
1553            $baseFRev = FlaggedRevision::newFromTitle( $title, $baseRevId );
1554            if ( !$baseFRev && $baseRevId2 ) {
1555                $baseFRev = FlaggedRevision::newFromTitle( $title, $baseRevId2 );
1556            }
1557
1558            if ( $baseFRev ) {
1559                return true; // edit will be autoreviewed
1560            }
1561        }
1562        return false; // edit won't be autoreviewed
1563    }
1564
1565    /**
1566     * Add a "review pending changes" checkbox to the edit form iff:
1567     * (a) there are currently any revisions pending (bug 16713)
1568     * (b) this is an unreviewed page (bug 23970)
1569     */
1570    public function addReviewCheck( EditPage $editPage, array &$checkboxes ): void {
1571        $request = $this->getRequest();
1572        $title = $this->article->getTitle(); // convenience
1573        if ( !$this->article->isReviewable() ||
1574            !MediaWikiServices::getInstance()->getPermissionManager()
1575                ->userCan( 'review', $this->getUser(), $title )
1576        ) {
1577            // Not needed
1578            return;
1579        } elseif ( $this->editWillBeAutoreviewed( $editPage->getArticle(), $editPage->isConflict ) ) {
1580            // Edit will be auto-reviewed
1581            return;
1582        }
1583        if ( self::getBaseRevId( $editPage->getArticle(), $editPage->isConflict, $request ) ==
1584            $this->article->getLatest() ) {
1585            # For pages with either no stable version, or an outdated one, let
1586            # the user decide if he/she wants it reviewed on the spot. One might
1587            # do this if he/she just saw the diff-to-stable and *then* decided to edit.
1588            # Note: check not shown when editing old revisions, which is confusing.
1589            $name = 'wpReviewEdit';
1590            $options = [
1591                'id' => $name,
1592                'default' => $request->getCheck( $name ),
1593                'legacy-name' => 'reviewed',
1594            ];
1595            // For reviewed pages...
1596            if ( $this->article->getStable() ) {
1597                // For pending changes...
1598                if ( $this->article->revsArePending() ) {
1599                    $n = $this->article->getPendingRevCount();
1600                    $options['title-message'] = 'revreview-check-flag-p-title';
1601                    $options['label-message'] = $this->msg( 'revreview-check-flag-p' )
1602                        ->numParams( $n );
1603                // For just the user's changes...
1604                } else {
1605                    $options['title-message'] = 'revreview-check-flag-y-title';
1606                    $options['label-message'] = 'revreview-check-flag-y';
1607                }
1608            // For unreviewed pages...
1609            } else {
1610                $options['title-message'] = 'revreview-check-flag-u-title';
1611                $options['label-message'] = 'revreview-check-flag-u';
1612            }
1613            $checkboxes[$name] = $options;
1614        }
1615    }
1616
1617    /**
1618     * Guess the rev ID the text of this form is based off
1619     */
1620    private static function getBaseRevId( Article $article, bool $isConflict, WebRequest $request ): int {
1621        if ( $isConflict ) {
1622            return 0; // throw away these values (bug 33481)
1623        }
1624
1625        $latestId = $article->getPage()->getLatest(); // current rev
1626        # Undoing edits...
1627        if ( $request->getIntOrNull( 'wpUndidRevision' ) ?? $request->getIntOrNull( 'undo' ) ) {
1628            $revId = $latestId; // current rev is the base rev
1629            # Other edits...
1630        } else {
1631            # If we are editing via oldid=X, then use that rev ID.
1632            $revId = $article->getOldID();
1633        }
1634        # Zero oldid => draft revision
1635        return $revId ?: $latestId;
1636    }
1637
1638    /**
1639     * Guess the alternative rev ID the text of this form is based off.
1640     * When undoing the top X edits, the base can be though of as either
1641     * the current or the edit X edits prior to the latest.
1642     */
1643    private static function getAltBaseRevId( Article $article, bool $isConflict, WebRequest $request ): int {
1644        if ( $isConflict ) {
1645            return 0; // throw away these values (bug 33481)
1646        }
1647
1648        $latestId = $article->getPage()->getLatest(); // current rev
1649        $undo = $request->getIntOrNull( 'wpUndidRevision' ) ?? $request->getIntOrNull( 'undo' );
1650        # Undoing consecutive top edits...
1651        if ( $undo && $undo === $latestId ) {
1652            # Treat this like a revert to a base revision.
1653            # We are undoing all edits *after* some rev ID (undoafter).
1654            # If undoafter is not given, then it is the previous rev ID.
1655            $revisionLookup = MediaWikiServices::getInstance()->getRevisionLookup();
1656            $revision = $revisionLookup->getRevisionById( $latestId );
1657            $previousRevision = $revision ? $revisionLookup->getPreviousRevision( $revision ) : null;
1658            $altBaseRevId = $request->getInt( 'wpUndoAfter', $request->getInt( 'undoafter',
1659                $previousRevision ? $previousRevision->getId() : 0
1660            ) );
1661        } else {
1662            $altBaseRevId = 0;
1663        }
1664
1665        return $altBaseRevId;
1666    }
1667}