Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 65
0.00% covered (danger)
0.00%
0 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
Hooks
0.00% covered (danger)
0.00%
0 / 65
0.00% covered (danger)
0.00%
0 / 11
756
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 onResourceLoaderRegisterModules
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 onGetPreferences
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 onPreferencesGetLayout
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 onFetchChangesList
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 onSpecialPageBeforeExecute
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
30
 onUserLogoutComplete
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 onResourceLoaderGetConfigVars
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 onOutputPageBodyAttributes
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
42
 onSkinPageReadyConfig
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 onDifferenceEngineViewHeader
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21namespace MediaWiki\Minerva;
22
23use MediaWiki\Config\Config;
24use MediaWiki\Diff\DifferenceEngine;
25use MediaWiki\Diff\Hook\DifferenceEngineViewHeaderHook;
26use MediaWiki\Hook\PreferencesGetLayoutHook;
27use MediaWiki\Html\Html;
28use MediaWiki\Minerva\Skins\SkinMinerva;
29use MediaWiki\Output\Hook\OutputPageBodyAttributesHook;
30use MediaWiki\Output\OutputPage;
31use MediaWiki\Preferences\Hook\GetPreferencesHook;
32use MediaWiki\RecentChanges\Hook\FetchChangesListHook;
33use MediaWiki\RecentChanges\OldChangesList;
34use MediaWiki\Registration\ExtensionRegistry;
35use MediaWiki\ResourceLoader\Context;
36use MediaWiki\ResourceLoader\Hook\ResourceLoaderGetConfigVarsHook;
37use MediaWiki\ResourceLoader\Hook\ResourceLoaderRegisterModulesHook;
38use MediaWiki\ResourceLoader\ResourceLoader;
39use MediaWiki\Skin\Hook\SkinPageReadyConfigHook;
40use MediaWiki\Skin\Skin;
41use MediaWiki\SpecialPage\Hook\SpecialPageBeforeExecuteHook;
42use MediaWiki\SpecialPage\SpecialPage;
43use MediaWiki\Specials\Helpers\LoginHelper;
44use MediaWiki\Specials\Hook\UserLogoutCompleteHook;
45use MediaWiki\User\Options\UserOptionsLookup;
46use MediaWiki\User\User;
47use MobileContext;
48use Wikimedia\Rdbms\ConfiguredReadOnlyMode;
49
50/**
51 * Hook handlers for Minerva skin.
52 *
53 * Hook handler method names should be in the form of:
54 *    on<HookName>()
55 */
56class Hooks implements
57    DifferenceEngineViewHeaderHook,
58    FetchChangesListHook,
59    GetPreferencesHook,
60    OutputPageBodyAttributesHook,
61    PreferencesGetLayoutHook,
62    ResourceLoaderGetConfigVarsHook,
63    ResourceLoaderRegisterModulesHook,
64    SkinPageReadyConfigHook,
65    SpecialPageBeforeExecuteHook,
66    UserLogoutCompleteHook
67{
68    public const FEATURE_OVERFLOW_PAGE_ACTIONS = 'MinervaOverflowInPageActions';
69
70    public function __construct(
71        private readonly ConfiguredReadOnlyMode $configuredReadOnlyMode,
72        private readonly SkinOptions $skinOptions,
73        private readonly UserOptionsLookup $userOptionsLookup,
74        private readonly ?MobileContext $mobileContext,
75    ) {
76    }
77
78    /**
79     * ResourceLoaderRegisterModules hook handler.
80     *
81     * Registers:
82     *
83     * * EventLogging schema modules, if the EventLogging extension is loaded;
84     * * Modules for the Visual Editor overlay, if the VisualEditor extension is loaded; and
85     * * Modules for the notifications overlay, if the Echo extension is loaded.
86     *
87     * @see https://www.mediawiki.org/wiki/Manual:Hooks/ResourceLoaderRegisterModules
88     *
89     * @param ResourceLoader $resourceLoader
90     */
91    public function onResourceLoaderRegisterModules( ResourceLoader $resourceLoader ): void {
92        if ( !ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' ) ) {
93            $resourceLoader->register( [
94                'mobile.startup' => [
95                    'dependencies' => [ 'mediawiki.searchSuggest' ],
96                    'localBasePath' => dirname( __DIR__ ),
97                    'remoteExtPath' => 'Minerva',
98                    'scripts' => 'resources/mobile.startup.stub.js',
99                ]
100            ] );
101        }
102    }
103
104    /**
105     * Adds Minerva-specific user preferences that can only be accessed via API
106     *
107     * @param User $user user whose preferences are being modified
108     * @param array[] &$prefs preferences description array, to be fed to a HTMLForm object
109     */
110    public function onGetPreferences( $user, &$prefs ): void {
111        $minervaPrefs = [
112            'minerva-theme' => [
113                'type' => 'api'
114            ],
115        ];
116
117        $prefs += $minervaPrefs;
118    }
119
120    /**
121     * PreferencesGetLayout hook handler.
122     *
123     * Use mobile layout in Special:Preferences
124     * @see https://www.mediawiki.org/wiki/Manual:Hooks/PreferencesGetLayout
125     *
126     * @param bool &$useMobileLayout
127     * @param string $skinName
128     * @param array $skinProperties
129     */
130    public function onPreferencesGetLayout( &$useMobileLayout, $skinName, $skinProperties = [] ) {
131        if ( $skinName === 'minerva' ) {
132            $useMobileLayout = true;
133        }
134    }
135
136    /**
137     * Disable recent changes enhanced mode (table mode)
138     * @see https://www.mediawiki.org/wiki/Manual:Hooks/FetchChangesList
139     *
140     * @inheritDoc
141     * @return false|void False to stop others from interacting with the hook
142     */
143    public function onFetchChangesList( $user, $skin, &$list, $groups ) {
144        if ( $skin->getSkinName() === 'minerva' ) {
145            // The new changes list (table-based) does not work with Minerva
146            $list = new OldChangesList( $skin->getContext(), $groups );
147            // returning false makes sure $list is used instead.
148            return false;
149        }
150    }
151
152    /**
153     * Invocation of hook SpecialPageBeforeExecute
154     *
155     * We use this hook to ensure that login/account creation pages
156     * are redirected to HTTPS if they are not accessed via HTTPS and
157     * $wgSecureLogin == true - but only when using the
158     * mobile site.
159     *
160     * @param SpecialPage $special
161     * @param string $subpage
162     */
163    public function onSpecialPageBeforeExecute( $special, $subpage ) {
164        $name = $special->getName();
165        $loginHelper = new LoginHelper( $special->getContext() );
166        if ( !in_array( $name, [ 'Recentchanges', 'Userlogin', 'CreateAccount' ] ) ) {
167            return;
168        }
169        $skin = $special->getSkin();
170        if ( !$skin instanceof SkinMinerva ) {
171            return;
172        }
173        $request = $special->getRequest();
174        if ( $name === 'Recentchanges' ) {
175            $isEnhancedDefaultForUser = $this->userOptionsLookup
176                ->getBoolOption( $special->getUser(), 'usenewrc' );
177            $enhanced = $request->getBool( 'enhanced', $isEnhancedDefaultForUser );
178            if ( $enhanced ) {
179                $out = $special->getOutput();
180                $out->addModuleStyles( 'mediawiki.codex.messagebox.styles' );
181                $out->addHTML( Html::warningBox(
182                    $special->msg( 'skin-minerva-recentchanges-warning-enhanced-not-supported' )->parse()
183                ) );
184            }
185        }
186    }
187
188    /**
189     * UserLogoutComplete hook handler.
190     * Resets skin options if a user logout occurs - this is necessary as the
191     * RequestContextCreateSkinMobile hook runs before the UserLogout hook.
192     *
193     * @param User $user
194     * @param string &$inject_html
195     * @param string $oldName
196     */
197    public function onUserLogoutComplete( $user, &$inject_html, $oldName ) {
198        if ( $this->mobileContext ) {
199            $this->skinOptions->setMinervaSkinOptions( $this->mobileContext, $this->mobileContext->getSkin() );
200        }
201    }
202
203    /**
204     * ResourceLoaderGetConfigVars hook handler.
205     * Used for setting JS variables which are pulled in dynamically with RL
206     * instead of embedded directly on the page with a script tag.
207     * These vars have a shorter cache-life than those in `getJsConfigVars`.
208     *
209     * @param array &$vars Array of variables to be added into the output of the RL startup module.
210     * @param string $skin
211     * @param Config $config
212     */
213    public function onResourceLoaderGetConfigVars( array &$vars, $skin, Config $config ): void {
214        if ( $skin === 'minerva' ) {
215            // This is to let the UI adjust itself to a wiki that is always read-only.
216            // Ignore temporary read-only on live wikis, requires heavy DB check (T233458).
217            $vars += [
218                'wgMinervaABSamplingRate' => $config->get( 'MinervaABSamplingRate' ),
219                'wgMinervaReadOnly' => $this->configuredReadOnlyMode->isReadOnly(),
220                // The lead section's truncation feature is client-side,
221                // so expose the config flag to the client.
222                'wgMinervaTruncateLeadSection' => $config->get( 'MinervaTruncateLeadSection' ),
223            ];
224        }
225    }
226
227    /**
228     * Modifies the `<body>` element's attributes.
229     *
230     * By default, the `class` attribute is set to the output's "bodyClassName"
231     * property.
232     *
233     * @param OutputPage $out
234     * @param Skin $skin
235     * @param string[] &$bodyAttrs
236     */
237    public function onOutputPageBodyAttributes( $out, $skin, &$bodyAttrs ): void {
238        $classes = $out->getProperty( 'bodyClassName' );
239        $isMinerva = $skin instanceof SkinMinerva;
240
241        if ( $isMinerva && $this->skinOptions->get( SkinOptions::HISTORY_IN_PAGE_ACTIONS ) ) {
242            // Class is used when page actions is modified to contain more elements
243            $classes .= ' minerva--history-page-action-enabled';
244        }
245
246        if ( $isMinerva && $this->skinOptions->get( SkinOptions::MINIMAL ) ) {
247            // Class is used when page actions is modified to contain more elements
248            $classes .= ' minerva--minimal';
249        }
250
251        if ( $isMinerva ) {
252            $bodyAttrs['class'] .= ' ' . $classes;
253        }
254    }
255
256    /**
257     * SkinPageReadyConfig hook handler
258     *
259     * @param Context $context
260     * @param mixed[] &$config Associative array of configurable options
261     */
262    public function onSkinPageReadyConfig(
263        Context $context,
264        array &$config
265    ): void {
266        if ( $context->getSkin() === 'minerva' ) {
267            $config['searchModule'] = 'skins.minerva.search';
268            // Enable collapsible styles on Minerva. Projects are already doing this via gadgets
269            // which creates an unpredictable testing environment so it is better to match production.
270            // NOTE: This is enabled despite the well documented problems with the current design on T111565.
271            $config['collapsible'] = true;
272            $config['selectorLogoutLink'] = 'a.menu__item--logout[data-mw-interface]';
273        }
274    }
275
276    /**
277     * Force inline diffs on mobile site.
278     *
279     * @param DifferenceEngine $differenceEngine
280     */
281    public function onDifferenceEngineViewHeader( $differenceEngine ) {
282        $skin = $differenceEngine->getSkin();
283        if ( $skin->getSkinName() !== 'minerva' ) {
284            return;
285        }
286        $differenceEngine->setSlotDiffOptions( [
287            'diff-type' => 'inline',
288        ] );
289    }
290}