Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.24% covered (warning)
88.24%
120 / 136
65.85% covered (warning)
65.85%
27 / 41
CRAP
0.00% covered (danger)
0.00%
0 / 1
Gadget
88.24% covered (warning)
88.24%
120 / 136
65.85% covered (warning)
65.85%
27 / 41
76.75
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
1
 serializeDefinition
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
1
 toArray
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
1
 newEmptyGadget
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isValidGadgetID
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getDescriptionMessageKey
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getDescription
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRawDescription
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getSection
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getModuleName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isEnabled
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 isAllowed
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 isOnByDefault
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isHidden
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isPackaged
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 isActionSupported
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 isNamespaceSupported
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 isCategorySupported
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 isSkinSupported
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 isContentModelSupported
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 supportsUrlLoad
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 hasModule
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getDefinition
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getScripts
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getStyles
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getJSONs
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getVues
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getCodexIcons
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getScriptsAndStyles
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getDependencies
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getPeers
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getMessages
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRequiredRights
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRequiredActions
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRequiredNamespaces
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRequiredCategories
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRequiredSkins
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRequiredContentModels
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getType
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
6
 getValidationWarnings
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
12.42
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\Extension\Gadgets;
22
23use MediaWiki\MediaWikiServices;
24use MediaWiki\Permissions\Authority;
25use MediaWiki\ResourceLoader\ResourceLoader;
26use MediaWiki\Skin\Skin;
27use MediaWiki\User\UserIdentity;
28
29/**
30 * Represents one gadget definition.
31 *
32 * @copyright 2007 Daniel Kinzler
33 */
34class Gadget {
35    /**
36     * Increment this when changing class structure
37     */
38    public const GADGET_CLASS_VERSION = 23;
39
40    /** @var string[] */
41    private array $dependencies;
42    /** @var string[] */
43    private array $pages;
44    /** @var string[] */
45    private array $peers;
46    /** @var string[] */
47    private array $messages;
48    /** @var string|null */
49    private ?string $name;
50    /** @var string|null */
51    private ?string $definition;
52    /** @var string[] */
53    private array $requiredRights;
54    /** @var string[] */
55    private array $requiredActions;
56    /** @var string[] */
57    private array $requiredSkins;
58    /** @var int[]|string[] */
59    private array $requiredNamespaces;
60    /** @var string[] */
61    private array $requiredCategories;
62    /** @var string[] */
63    private array $requiredContentModels;
64    private bool $onByDefault;
65    private bool $hidden;
66    private bool $package;
67    private string $type;
68    private string $section;
69    private bool $supportsUrlLoad;
70    /** @var string[] */
71    private array $codexIcons;
72
73    public function __construct( array $options ) {
74        $this->section = $options['section'] ?? '';
75        $this->codexIcons = $options['codexIcons'] ?? [];
76        $this->definition = $options['definition'] ?? null;
77        $this->dependencies = $options['dependencies'] ?? [];
78        $this->hidden = $options['hidden'] ?? false;
79        $this->messages = $options['messages'] ?? [];
80        $this->name = $options['name'] ?? null;
81        $this->onByDefault = $options['onByDefault'] ?? false;
82        $this->package = $options['package'] ?? false;
83        $this->pages = $options['pages'] ?? [];
84        $this->peers = $options['peers'] ?? [];
85        $this->requiredActions = $options['requiredActions'] ?? [];
86        $this->requiredCategories = $options['requiredCategories'] ?? [];
87        $this->requiredContentModels = $options['requiredContentModels'] ?? [];
88        $this->requiredNamespaces = $options['requiredNamespaces'] ?? [];
89        $this->requiredRights = $options['requiredRights'] ?? [];
90        $this->requiredSkins = $options['requiredSkins'] ?? [];
91        $this->supportsUrlLoad = $options['supportsUrlLoad'] ?? false;
92        $this->type = $options['type'] ?? '';
93    }
94
95    /**
96     * Create a serialized array based on the metadata in a GadgetDefinitionContent object,
97     * from which a Gadget object can be constructed.
98     *
99     * @param string $id
100     * @param array $data
101     * @return array
102     */
103    public static function serializeDefinition( string $id, array $data ): array {
104        $prefixGadgetNs = static function ( $page ) {
105            return GadgetRepo::RESOURCE_TITLE_PREFIX . $page;
106        };
107        return [
108            'section' => $data['settings']['section'],
109            'codexIcons' => $data['module']['codexIcons'],
110            'dependencies' => $data['module']['dependencies'],
111            'hidden' => $data['settings']['hidden'],
112            'messages' => $data['module']['messages'],
113            'name' => $id,
114            'onByDefault' => $data['settings']['default'],
115            'package' => $data['settings']['package'],
116            'pages' => array_map( $prefixGadgetNs, $data['module']['pages'] ),
117            'peers' => $data['module']['peers'],
118            'requiredActions' => $data['settings']['actions'],
119            'requiredCategories' => $data['settings']['categories'],
120            'requiredContentModels' => $data['settings']['contentModels'],
121            'requiredNamespaces' => $data['settings']['namespaces'],
122            'requiredRights' => $data['settings']['rights'],
123            'requiredSkins' => $data['settings']['skins'],
124            'supportsUrlLoad' => $data['settings']['supportsUrlLoad'],
125            'type' => $data['module']['type'],
126        ];
127    }
128
129    /**
130     * Serialize to an array
131     */
132    public function toArray(): array {
133        return [
134            'section' => $this->section,
135            'codexIcons' => $this->codexIcons,
136            'dependencies' => $this->dependencies,
137            'hidden' => $this->hidden,
138            'messages' => $this->messages,
139            'name' => $this->name,
140            'onByDefault' => $this->onByDefault,
141            'package' => $this->package,
142            'pages' => $this->pages,
143            'peers' => $this->peers,
144            'requiredActions' => $this->requiredActions,
145            'requiredCategories' => $this->requiredCategories,
146            'requiredContentModels' => $this->requiredContentModels,
147            'requiredNamespaces' => $this->requiredNamespaces,
148            'requiredRights' => $this->requiredRights,
149            'requiredSkins' => $this->requiredSkins,
150            'supportsUrlLoad' => $this->supportsUrlLoad,
151            'type' => $this->type,
152            // Legacy  (specific to MediaWikiGadgetsDefinitionRepo)
153            'definition' => $this->definition,
154        ];
155    }
156
157    /**
158     * Get a placeholder object to use if a gadget doesn't exist
159     *
160     * @param string $id name
161     * @return self
162     */
163    public static function newEmptyGadget( $id ) {
164        return new self( [ 'name' => $id ] );
165    }
166
167    /**
168     * Whether the provided gadget id is valid
169     *
170     * @param string $id
171     * @return bool
172     */
173    public static function isValidGadgetID( $id ) {
174        return $id !== '' && ResourceLoader::isValidModuleName( self::getModuleName( $id ) );
175    }
176
177    /**
178     * @return string Gadget name
179     */
180    public function getName() {
181        return $this->name;
182    }
183
184    /**
185     * @return string Message key
186     */
187    public function getDescriptionMessageKey() {
188        return 'gadget-' . $this->name;
189    }
190
191    /**
192     * @return string Gadget description parsed into HTML
193     */
194    public function getDescription() {
195        return wfMessage( $this->getDescriptionMessageKey() )->parse();
196    }
197
198    /**
199     * @return string Wikitext of gadget description
200     */
201    public function getRawDescription() {
202        return wfMessage( $this->getDescriptionMessageKey() )->plain();
203    }
204
205    /**
206     * @return string Name of section our gadget belongs to. Empty string if none.
207     */
208    public function getSection(): string {
209        return $this->section;
210    }
211
212    /**
213     * @param string $id Name of gadget
214     * @return string Name of ResourceLoader module for the gadget
215     */
216    public static function getModuleName( $id ) {
217        return "ext.gadget.{$id}";
218    }
219
220    /**
221     * Checks whether this gadget is enabled for given user
222     *
223     * @param UserIdentity $user user to check against
224     * @return bool
225     */
226    public function isEnabled( UserIdentity $user ) {
227        $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
228        return (bool)$userOptionsLookup->getOption( $user, "gadget-{$this->name}", $this->onByDefault );
229    }
230
231    /**
232     * Checks whether a given user may enable this gadget
233     *
234     * @param Authority $user The user to check against
235     * @return bool
236     */
237    public function isAllowed( Authority $user ) {
238        return !$this->requiredRights || $user->isAllowedAll( ...$this->requiredRights );
239    }
240
241    /**
242     * @return bool Whether this gadget is on by default for everyone
243     *  (but can be disabled in preferences)
244     */
245    public function isOnByDefault() {
246        return $this->onByDefault;
247    }
248
249    /**
250     * @return bool
251     */
252    public function isHidden() {
253        return $this->hidden;
254    }
255
256    public function isPackaged(): bool {
257        // A packaged gadget needs to have a main script, so there must be at least one script
258        return $this->package && $this->getScripts();
259    }
260
261    /**
262     * Whether to load the gadget on a given page action.
263     *
264     * @param string $action Action name
265     * @return bool
266     */
267    public function isActionSupported( string $action ): bool {
268        if ( !$this->requiredActions ) {
269            return true;
270        }
271        // Don't require specifying 'submit' action in addition to 'edit'
272        if ( $action === 'submit' ) {
273            $action = 'edit';
274        }
275        return in_array( $action, $this->requiredActions, true );
276    }
277
278    /**
279     * Whether to load the gadget on pages in a given namespace ID.
280     *
281     * @param int $namespace Namespace ID
282     * @return bool
283     */
284    public function isNamespaceSupported( int $namespace ): bool {
285        // This is intentionally a non-strict in_array() because
286        // MediaWikiGadgetsDefinitionRepo sets numerical strings.
287        return !$this->requiredNamespaces || in_array( $namespace, $this->requiredNamespaces );
288    }
289
290    /**
291     * Whether to load the gadget on pages in any of the given categories
292     *
293     * @param array<string,int> $categories Associative array with keys as category names (category title text,
294     * no namespace prefix, no dbkey-underscores) and with value as 1 for all keys.
295     * @return bool
296     */
297    public function isCategorySupported( array $categories ): bool {
298        if ( !$this->requiredCategories ) {
299            return true;
300        }
301        foreach ( $this->requiredCategories as $category ) {
302            if ( isset( $categories[$category] ) ) {
303                return true;
304            }
305        }
306        return false;
307    }
308
309    /**
310     * Check if this gadget is compatible with a skin
311     *
312     * @param Skin $skin
313     * @return bool
314     */
315    public function isSkinSupported( Skin $skin ) {
316        return !$this->requiredSkins || in_array( $skin->getSkinName(), $this->requiredSkins, true );
317    }
318
319    /**
320     * Check if this gadget is compatible with the given content model
321     *
322     * @param string $contentModel The content model ID
323     * @return bool
324     */
325    public function isContentModelSupported( string $contentModel ) {
326        return !$this->requiredContentModels || in_array( $contentModel, $this->requiredContentModels );
327    }
328
329    /**
330     * @return bool Whether the gadget can be loaded with `?withgadget` query parameter.
331     */
332    public function supportsUrlLoad() {
333        return $this->supportsUrlLoad;
334    }
335
336    /**
337     * @return bool Whether this gadget has resources that can be loaded via ResourceLoader
338     */
339    public function hasModule() {
340        return $this->getStyles() || $this->getScripts();
341    }
342
343    /**
344     * @return string|null Definition for this gadget from MediaWiki:Gadgets-definition,
345     *  or null if MediaWikiGadgetsJsonRepo is used.
346     */
347    public function getDefinition() {
348        return $this->definition;
349    }
350
351    /**
352     * @return string[] JS page names (including namespace)
353     */
354    public function getScripts() {
355        return array_values( array_filter( $this->pages, static function ( $page ) {
356            return str_ends_with( $page, '.js' );
357        } ) );
358    }
359
360    /**
361     * @return string[] CSS page names (including namespace)
362     */
363    public function getStyles() {
364        return array_values( array_filter( $this->pages, static function ( $page ) {
365            return str_ends_with( $page, '.css' );
366        } ) );
367    }
368
369    /**
370     * @return string[] JSON page names (including namespace)
371     */
372    public function getJSONs(): array {
373        return array_values( array_filter( $this->pages, static function ( $page ) {
374            return str_ends_with( $page, '.json' );
375        } ) );
376    }
377
378    /**
379     * @return string[] Vue page names (including namespace)
380     */
381    public function getVues(): array {
382        return array_values( array_filter( $this->pages, static function ( $page ) {
383            return str_ends_with( $page, '.vue' );
384        } ) );
385    }
386
387    /**
388     * @return string[] Codex icons to include in the gadget module
389     */
390    public function getCodexIcons(): array {
391        return $this->codexIcons;
392    }
393
394    /**
395     * @return string[] All page names for this gadget's resources
396     */
397    public function getScriptsAndStyles() {
398        return array_merge( $this->getScripts(), $this->getStyles(), $this->getJSONs(), $this->getVues() );
399    }
400
401    /**
402     * Returns names of resources this gadget depends on
403     * @return string[]
404     */
405    public function getDependencies() {
406        return $this->dependencies;
407    }
408
409    /**
410     * Get list of extra modules that should be loaded when this gadget is enabled
411     *
412     * Primary use case is to allow a Gadget that includes JavaScript to also load
413     * a (usually, hidden) styles-type module to be applied to the page. Dependencies
414     * don't work for this use case as those would not be part of page rendering.
415     *
416     * @return string[]
417     */
418    public function getPeers(): array {
419        return $this->peers;
420    }
421
422    /**
423     * @return string[]
424     */
425    public function getMessages(): array {
426        return $this->messages;
427    }
428
429    /**
430     * Get user rights required to enable this gadget
431     * @return string[]
432     */
433    public function getRequiredRights(): array {
434        return $this->requiredRights;
435    }
436
437    /**
438     * Get page actions on which the gadget loads
439     * @return string[]
440     */
441    public function getRequiredActions(): array {
442        return $this->requiredActions;
443    }
444
445    /**
446     * Get page namespaces in which this gadget loads
447     *
448     * Use isNamespaceSupported() instead for basic checks, as
449     * namespace IDs may be returned as numerical strings.
450     *
451     * Unknown namespaces and non-numerical values result in warnings
452     * on Special:Gadgets, via GadgetRepo::checkInvalidLoadConditions.
453     *
454     * @return int[]|string[]
455     */
456    public function getRequiredNamespaces(): array {
457        return $this->requiredNamespaces;
458    }
459
460    /**
461     * Returns categories in which this gadget loads
462     * @return string[]
463     */
464    public function getRequiredCategories(): array {
465        return $this->requiredCategories;
466    }
467
468    /**
469     * Get skins in which this gadget loads
470     * @return string[]
471     */
472    public function getRequiredSkins(): array {
473        return $this->requiredSkins;
474    }
475
476    /**
477     * Get page content models for which this gadget loads
478     * @return string[]
479     */
480    public function getRequiredContentModels(): array {
481        return $this->requiredContentModels;
482    }
483
484    /**
485     * Returns the load type of this Gadget's ResourceLoader module
486     * @return string 'styles' or 'general'
487     */
488    public function getType(): string {
489        if ( $this->type === 'styles' || $this->type === 'general' ) {
490            return $this->type;
491        }
492        // Similar to ResourceLoaderWikiModule default
493        if ( $this->getStyles() && !$this->getScripts() && !$this->dependencies ) {
494            return 'styles';
495        }
496
497        return 'general';
498    }
499
500    /**
501     * Get validation warnings
502     * @return string[]
503     */
504    public function getValidationWarnings(): array {
505        $warnings = [];
506
507        // Gadget containing files with uncrecognised suffixes
508        if ( array_diff( $this->pages, $this->getScriptsAndStyles() ) ) {
509            $warnings[] = "gadgets-validate-unknownpages";
510        }
511
512        // Non-package gadget containing JSON files
513        if ( !$this->package && $this->getJSONs() ) {
514            $warnings[] = "gadgets-validate-json";
515        }
516
517        // Non-package gadget containing Codex icons
518        if ( !$this->package && count( $this->getCodexIcons() ) > 0 ) {
519            $warnings[] = "gadgets-validate-icons";
520        }
521
522        // Package gadget without a script file in it (to serve as entry point)
523        if ( $this->package && !$this->getScripts() ) {
524            $warnings[] = "gadgets-validate-noentrypoint";
525        }
526
527        // Gadget with type=styles having non-CSS files
528        if ( $this->type === 'styles' && $this->getScripts() ) {
529            $warnings[] = "gadgets-validate-scriptsnotallowed";
530        }
531
532        // Style-only gadgets having peers
533        if ( $this->getType() === 'styles' && $this->peers ) {
534            $warnings[] = "gadgets-validate-stylepeers";
535        }
536
537        return $warnings;
538    }
539}