Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
64.33% covered (warning)
64.33%
110 / 171
22.22% covered (danger)
22.22%
2 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
Hooks
64.33% covered (warning)
64.33%
110 / 171
22.22% covered (danger)
22.22%
2 / 9
180.51
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getUserCounts
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 onSaveUserOptions
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
72
 onGetPreferences
80.34% covered (warning)
80.34%
94 / 117
0.00% covered (danger)
0.00%
0 / 1
41.27
 onPreferencesGetIcon
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 onUserGetDefaultOptions
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
2.50
 onMakeGlobalVariablesScript
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 onSkinTemplateNavigation__Universal
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 onExtensionTypes
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * This file is part of the MediaWiki extension BetaFeatures.
4 *
5 * BetaFeatures is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * BetaFeatures is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with BetaFeatures.  If not, see <http://www.gnu.org/licenses/>.
17 *
18 * BetaFeatures extension hooks
19 *
20 * @file
21 * @ingroup Extensions
22 * @copyright 2013 Mark Holmquist and others; see AUTHORS
23 * @license GPL-2.0-or-later
24 */
25
26namespace MediaWiki\Extension\BetaFeatures;
27
28use Exception;
29use MediaWiki\Config\Config;
30use MediaWiki\Context\RequestContext;
31use MediaWiki\Deferred\DeferredUpdates;
32use MediaWiki\Extension\BetaFeatures\Hooks\HookRunner;
33use MediaWiki\Hook\PreferencesGetIconHook;
34use MediaWiki\HookContainer\HookContainer;
35use MediaWiki\JobQueue\JobQueueGroupFactory;
36use MediaWiki\ObjectCache\ObjectCacheFactory;
37use MediaWiki\Output\Hook\MakeGlobalVariablesScriptHook;
38use MediaWiki\Output\OutputPage;
39use MediaWiki\Preferences\Hook\GetPreferencesHook;
40use MediaWiki\Skin\Hook\SkinTemplateNavigation__UniversalHook;
41use MediaWiki\Skin\SkinFactory;
42use MediaWiki\Skin\SkinTemplate;
43use MediaWiki\SpecialPage\SpecialPage;
44use MediaWiki\Specials\Hook\ExtensionTypesHook;
45use MediaWiki\User\Hook\UserGetDefaultOptionsHook;
46use MediaWiki\User\Options\Hook\SaveUserOptionsHook;
47use MediaWiki\User\Options\UserOptionsManager;
48use MediaWiki\User\User;
49use MediaWiki\User\UserFactory;
50use MediaWiki\User\UserIdentity;
51use MediaWiki\User\UserIdentityUtils;
52use Wikimedia\ArrayUtils\ArrayUtils;
53use Wikimedia\Rdbms\IConnectionProvider;
54
55class Hooks implements
56    ExtensionTypesHook,
57    GetPreferencesHook,
58    MakeGlobalVariablesScriptHook,
59    PreferencesGetIconHook,
60    SaveUserOptionsHook,
61    SkinTemplateNavigation__UniversalHook,
62    UserGetDefaultOptionsHook
63{
64
65    /**
66     * @var array An array of each of the available Beta Features, with their requirements, if any.
67     * It is passed client-side for JavaScript rendering/responsiveness.
68     */
69    private static array $features = [];
70
71    public function __construct(
72        private readonly Config $config,
73        private readonly IConnectionProvider $dbProvider,
74        private readonly HookContainer $hookContainer,
75        private readonly JobQueueGroupFactory $jobQueueGroupFactory,
76        private readonly SkinFactory $skinFactory,
77        private readonly UserFactory $userFactory,
78        private readonly UserIdentityUtils $userIdentityUtils,
79        private readonly UserOptionsManager $userOptionsManager,
80        private readonly ObjectCacheFactory $objectCacheFactory,
81    ) {
82    }
83
84    /**
85     * @param string[] $prefs
86     * @param IConnectionProvider $dbProvider
87     * @return int[]
88     */
89    public static function getUserCounts( array $prefs, IConnectionProvider $dbProvider ) {
90        $counts = [];
91        if ( !$prefs ) {
92            return $counts;
93        }
94
95        $dbr = $dbProvider->getReplicaDatabase();
96        $res = $dbr->newSelectQueryBuilder()
97            ->select( [ 'feature', 'number' ] )
98            ->from( 'betafeatures_user_counts' )
99            ->where( [ 'feature' => $prefs ] )
100            ->caller( __METHOD__ )->fetchResultSet();
101
102        foreach ( $res as $row ) {
103            $counts[$row->feature] = $row->number;
104        }
105
106        return $counts;
107    }
108
109    /**
110     * @see https://www.mediawiki.org/wiki/Manual:Hooks/SaveUserOptions
111     *
112     * @param UserIdentity $user User who's just saved their preferences
113     * @param array &$modifiedOptions List of modified options
114     * @param array $originalOptions List of original user options
115     * @throws Exception
116     */
117    public function onSaveUserOptions(
118        UserIdentity $user,
119        array &$modifiedOptions,
120        array $originalOptions
121    ) {
122        if ( !$user->isRegistered() || $this->userIdentityUtils->isTemp( $user ) ) {
123            // Anonymous and temporary users do not have options, shorten out.
124            return;
125        }
126
127        if ( !$modifiedOptions ) {
128            // Nothing was modified, no beta feature counts to update.
129            return;
130        }
131
132        $betaFeatures = $this->config->get( 'BetaFeatures' );
133        $user = $this->userFactory->newFromUserIdentity( $user );
134        ( new HookRunner( $this->hookContainer ) )->onGetBetaFeaturePreferences( $user, $betaFeatures );
135
136        $jobs = [];
137        foreach ( $betaFeatures as $name => $option ) {
138            if ( !array_key_exists( $name, $modifiedOptions ) ) {
139                continue;
140            }
141            $newVal = $modifiedOptions[$name];
142            $oldVal = $originalOptions[$name] ?? null;
143            // Check if this preference meaningfully changed
144            if ( $oldVal == $newVal ) {
145                // unchanged
146                continue;
147            }
148            // Enqueue a job to update the count for this preference
149            $jobs[] = new UpdateBetaFeatureUserCountsJob(
150                [ 'prefs' => [ $name ] ],
151                $this->dbProvider
152            );
153        }
154        if ( $jobs !== [] ) {
155            $this->jobQueueGroupFactory->makeJobQueueGroup()->push( $jobs );
156        }
157    }
158
159    /**
160     * @param User $user
161     * @param array[] &$prefs
162     * @throws BetaFeaturesMissingFieldException
163     */
164    public function onGetPreferences( $user, &$prefs ) {
165        $betaPrefs = $this->config->get( 'BetaFeatures' );
166        $depHooks = [];
167
168        $hookRunner = new HookRunner( $this->hookContainer );
169        $hookRunner->onGetBetaFeaturePreferences( $user, $betaPrefs );
170
171        // The following messages are generated upstream by the 'section' value
172        // * prefs-betafeatures
173        // * prefs-description-betafeatures
174        $count = count( $betaPrefs );
175        $prefs['betafeatures-section-desc'] = [
176            'type' => 'info',
177            'default' => static function () use ( $count ) {
178                return wfMessage( 'betafeatures-section-desc' )
179                    ->numParams( $count )
180                    ->parseAsBlock();
181            },
182            'section' => 'betafeatures',
183            'raw' => true,
184        ];
185
186        $prefs['betafeatures-auto-enroll'] = [
187            'type' => 'check',
188            'label-message' => 'betafeatures-auto-enroll',
189            'help-message' => 'betafeatures-auto-enroll-help',
190            'section' => 'betafeatures',
191        ];
192
193        // Purely visual field.
194        $prefs['betafeatures-breaking-hr'] = [
195            'class' => HTMLHorizontalRuleField::class,
196            'section' => 'betafeatures',
197        ];
198
199        $counts = self::getUserCounts( array_keys( $betaPrefs ), $this->dbProvider );
200
201        // Set up dependency hooks array
202        // This complex structure brought to you by Per-Wiki Configuration,
203        // coming soon to a wiki very near you.
204        $hookRunner->onGetBetaFeatureDependencyHooks( $depHooks );
205
206        $autoEnrollSaveSettings = [];
207        $autoEnrollAll = $this->userOptionsManager->getBoolOption( $user, 'betafeatures-auto-enroll' );
208
209        $autoEnroll = [];
210
211        foreach ( $betaPrefs as $key => $info ) {
212            if ( isset( $info['auto-enrollment'] ) ) {
213                $autoEnroll[$info['auto-enrollment']] = $key;
214            }
215        }
216
217        $hiddenPrefs = $this->config->get( 'HiddenPrefs' );
218        $allowlist = $this->config->get( 'BetaFeaturesAllowList' );
219
220        foreach ( $betaPrefs as $key => $info ) {
221            // Check if feature should be skipped
222            if (
223                // Check if feature is hidden
224                in_array( $key, $hiddenPrefs ) ||
225                // Check if feature is in the allow list
226                ( is_array( $allowlist ) && !in_array( $key, $allowlist ) ) ||
227                // Check if dependencies are set but not met
228                (
229                    isset( $info['dependent'] ) &&
230                    $info['dependent'] === true &&
231                    isset( $depHooks[$key] ) &&
232                    !$this->hookContainer->run( $depHooks[$key] )
233                )
234            ) {
235                continue;
236            }
237
238            $opt = [
239                'class' => HTMLFeatureField::class,
240                'section' => 'betafeatures',
241                'disable-if' => [ '===', 'betafeatures-auto-enroll', '1' ],
242            ];
243
244            $requiredFields = [
245                'label-message' => true,
246                'desc-message' => true,
247                'screenshot' => false,
248                'requirements' => false,
249                'info-link' => false,
250                'info-message' => false,
251                'discussion-link' => false,
252                'discussion-message' => false,
253                'disabled' => false,
254            ];
255
256            foreach ( $requiredFields as $field => $required ) {
257                if ( isset( $info[$field] ) ) {
258                    $opt[$field] = $info[$field];
259                } elseif ( $required ) {
260                    // A required field isn't present in the info array
261                    // we got from the GetBetaFeaturePreferences hook.
262                    // Don't add this feature to the form.
263                    throw new BetaFeaturesMissingFieldException(
264                        "The field {$field} was missing from the beta feature {$key}."
265                    );
266                }
267            }
268
269            if ( isset( $counts[$key] ) ) {
270                $opt['user-count'] = $counts[$key];
271            }
272
273            // Set the beta feature in the standard preferences array
274            // Just before, unset the key to resort it in the array, in the case the key was already set
275            unset( $prefs[$key] );
276            $prefs[$key] = $opt;
277
278            $autoEnrollForThisPref = false;
279
280            if ( isset( $info['group'] ) && isset( $autoEnroll[$info['group']] ) ) {
281                $autoEnrollForThisPref = $this->userOptionsManager
282                    ->getBoolOption( $user, $autoEnroll[$info['group']] );
283            }
284
285            $exemptAutoEnroll = ( $info['exempt-from-auto-enrollment'] ?? false )
286                || ( $info['disabled'] ?? false );
287            $autoEnrollHere = !$exemptAutoEnroll && ( $autoEnrollAll || $autoEnrollForThisPref );
288
289            // Use raw value for existence test
290            $currentValue = $this->userOptionsManager->getOption( $user, $key );
291
292            // Keep it break now... The tests applied are against the comments below.
293            // Fixing all the tests is not worthwhile, the auto-enroll logic should be refactored later.
294            if ( $autoEnrollHere && $currentValue !== '1' ) {
295                // We haven't seen this before, and the user has auto-enroll enabled!
296                // Set the option to true and make it visible for the current user object
297                $this->userOptionsManager->setOption( $user, $key, true );
298                // Also put it aside for saving the settings later
299                $autoEnrollSaveSettings[$key] = true;
300            }
301
302            self::$features[$key] = [];
303            self::$features[$key]['__skip-auto-enroll'] = $exemptAutoEnroll;
304        }
305
306        foreach ( $betaPrefs as $key => $info ) {
307            if ( isset( $prefs[$key]['requirements'] ) ) {
308                // Check which other beta features are required, and fetch their labels
309                if ( isset( $prefs[$key]['requirements']['betafeatures'] ) ) {
310                    $requiredPrefs = [];
311                    foreach ( $prefs[$key]['requirements']['betafeatures'] as $preference ) {
312                        if ( !$this->userOptionsManager->getBoolOption( $user, $preference ) ) {
313                            $requiredPrefs[] = $prefs[$preference]['label-message'];
314                        }
315                    }
316                    if ( count( $requiredPrefs ) ) {
317                        $prefs[$key]['requirements']['betafeatures-messages'] = $requiredPrefs;
318                    }
319                }
320
321                // Test skin support
322                if ( isset( $prefs[$key]['requirements']['skins'] ) ) {
323                    // Remove any skins that aren't installed or users can't choose
324                    $prefs[$key]['requirements']['skins'] = array_intersect(
325                        /** @phan-suppress-next-line PhanTypeInvalidDimOffset,PhanTypeMismatchArgumentInternal */
326                        $prefs[$key]['requirements']['skins'],
327                        array_keys( $this->skinFactory->getAllowedSkins() )
328                    );
329
330                    if ( empty( $prefs[$key]['requirements']['skins'] ) ) {
331                        // If there are no valid skins, don't show the preference
332                        wfDebugLog( 'BetaFeatures', "The $key BetaFeature has no valid skins installed." );
333                        continue;
334                    }
335                    // Also check if the user's current skin is supported
336                    $prefs[$key]['requirements']['skin-not-supported'] = !in_array(
337                        RequestContext::getMain()->getSkin()->getSkinName(),
338                        $prefs[$key]['requirements']['skins']
339                    );
340                }
341            }
342
343            // If a unsupported browsers list is supplied, store so it can be passed as JSON
344            self::$features[$key]['unsupportedList'] = $prefs[$key]['requirements']['unsupportedList'] ?? null;
345        }
346
347        if ( $autoEnrollSaveSettings !== [] ) {
348            // Save the preferences to the DB post-send
349            DeferredUpdates::addCallableUpdate(
350                function () use ( $user, $autoEnrollSaveSettings ) {
351                    $cache = $this->objectCacheFactory->getLocalClusterInstance();
352                    $key = $cache->makeKey( __CLASS__, 'prefs-update', $user->getId() );
353                    // T95839: If concurrent requests pile on (e.g. multiple tabs), only let one
354                    // thread bother doing these updates. This avoids pointless error log spam.
355                    if ( $cache->lock( $key, 0, $cache::TTL_MINUTE ) ) {
356                        // Apply the settings and save
357                        foreach ( $autoEnrollSaveSettings as $key => $option ) {
358                            $this->userOptionsManager->setOption( $user, $key, $option );
359                        }
360                        $this->userOptionsManager->saveOptions( $user );
361                        $cache->unlock( $key );
362                    }
363                }
364            );
365        }
366    }
367
368    /**
369     * Add icon for Special:Preferences mobile layout
370     *
371     * @param array &$iconNames Array of icon names for their respective sections.
372     */
373    public function onPreferencesGetIcon( &$iconNames ) {
374        $iconNames[ 'betafeatures' ] = 'labFlask';
375    }
376
377    /**
378     * Add default preferences values
379     *
380     * @param array &$defaultOptions Array of preference keys and their default values.
381     */
382    public function onUserGetDefaultOptions( &$defaultOptions ) {
383        foreach ( $this->config->get( 'BetaFeatures' ) as $key => $info ) {
384            $defaultOptions[$key] = false;
385        }
386    }
387
388    /**
389     * @param array &$vars
390     * @param OutputPage $out
391     */
392    public function onMakeGlobalVariablesScript( &$vars, $out ): void {
393        if ( self::$features ) {
394            // This is added to page view HTML on all articles.
395            // FIXME: Move this to the preferences page somehow, or
396            // bundle with the module that loads betafeatures.js.
397            $vars['wgBetaFeaturesFeatures'] = self::$features;
398        }
399    }
400
401    /**
402     * @param SkinTemplate $skintemplate
403     * @param array[] &$links
404     */
405    public function onSkinTemplateNavigation__Universal(
406        $skintemplate,
407        &$links
408    ): void {
409        $user = $skintemplate->getUser();
410        if ( $user->isNamed() ) {
411            $personalUrls = $links['user-menu'] ?? [];
412            $personalUrls = ArrayUtils::insertAfter( $personalUrls, [
413                // The following messages are generated upstream
414                // * tooltip-pt-betafeatures
415                'betafeatures' => [
416                    'text' => wfMessage( 'betafeatures-toplink' )->text(),
417                    'href' => SpecialPage::getTitleFor(
418                        'Preferences', false, 'mw-prefsection-betafeatures'
419                    )->getLinkURL(),
420                    'active' => $skintemplate->getTitle()->isSpecial( 'Preferences' ),
421                    'icon' => 'labFlask'
422                ],
423            ], 'preferences' );
424            $links['user-menu'] = $personalUrls;
425        }
426    }
427
428    /**
429     * @param string[] &$extTypes
430     */
431    public function onExtensionTypes( &$extTypes ) {
432        $extTypes['betafeatures'] = wfMessage( 'betafeatures-extension-type' )->text();
433    }
434
435}