Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.57% covered (warning)
78.57%
77 / 98
12.50% covered (danger)
12.50%
1 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
GadgetRepo
78.57% covered (warning)
78.57%
77 / 98
12.50% covered (danger)
12.50%
1 / 8
34.17
0.00% covered (danger)
0.00%
0 / 1
 getGadgetIds
n/a
0 / 0
n/a
0 / 0
0
 getGadget
n/a
0 / 0
n/a
0 / 0
0
 handlePageUpdate
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getGadgetDefinitionTitle
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getStructuredList
42.86% covered (danger)
42.86%
3 / 7
0.00% covered (danger)
0.00%
0 / 1
4.68
 titleWithoutPrefix
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 validationWarnings
76.00% covered (warning)
76.00%
19 / 25
0.00% covered (danger)
0.00%
0 / 1
4.22
 checkTitles
76.92% covered (warning)
76.92%
10 / 13
0.00% covered (danger)
0.00%
0 / 1
5.31
 checkProperty
88.10% covered (warning)
88.10%
37 / 42
0.00% covered (danger)
0.00%
0 / 1
8.11
 maybeAddWarnings
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3namespace MediaWiki\Extension\Gadgets;
4
5use InvalidArgumentException;
6use MediaWiki\Linker\LinkTarget;
7use MediaWiki\MediaWikiServices;
8use MediaWiki\Message\Message;
9use MediaWiki\Title\Title;
10use Wikimedia\Message\ListType;
11
12abstract class GadgetRepo {
13
14    /** @internal */
15    public const RESOURCE_TITLE_PREFIX = 'MediaWiki:Gadget-';
16
17    /**
18     * Get the ids of the gadgets provided by this repository
19     *
20     * It's possible this could be out of sync with what
21     * getGadget() will return due to caching
22     *
23     * @return string[]
24     */
25    abstract public function getGadgetIds(): array;
26
27    /**
28     * Get the Gadget object for a given gadget ID
29     *
30     * @param string $id
31     * @return Gadget
32     * @throws InvalidArgumentException For unregistered ID, used by getStructuredList()
33     */
34    abstract public function getGadget( string $id ): Gadget;
35
36    /**
37     * Invalidate any caches based on the provided page (after create, edit, or delete).
38     *
39     * This must be called on create and delete as well (T39228).
40     */
41    public function handlePageUpdate( LinkTarget $target ): void {
42    }
43
44    /**
45     * Given a gadget ID, return the title of the page where the gadget is
46     * defined (or null if the given repo does not have per-gadget definition
47     * pages).
48     */
49    public function getGadgetDefinitionTitle( string $id ): ?Title {
50        return null;
51    }
52
53    /**
54     * Get a lists of Gadget objects by section
55     *
56     * @return array<string,Gadget[]> `[ 'section' => [ 'name' => $gadget ] ]`
57     */
58    public function getStructuredList(): array {
59        $list = [];
60        foreach ( $this->getGadgetIds() as $id ) {
61            try {
62                $gadget = $this->getGadget( $id );
63            } catch ( InvalidArgumentException ) {
64                continue;
65            }
66            $list[$gadget->getSection()][$gadget->getName()] = $gadget;
67        }
68
69        return $list;
70    }
71
72    /**
73     * Get the page name without "MediaWiki:Gadget-" prefix.
74     *
75     * This name is used by `mw.loader.require()` so that `require("./example.json")` resolves
76     * to `MediaWiki:Gadget-example.json`.
77     */
78    public function titleWithoutPrefix( string $titleText, string $gadgetId ): string {
79        return str_replace( self::RESOURCE_TITLE_PREFIX, '', $titleText );
80    }
81
82    /**
83     * @param Gadget $gadget
84     * @return Message[]
85     */
86    public function validationWarnings( Gadget $gadget ): array {
87        // Basic checks local to the gadget definition
88        $warningMsgKeys = $gadget->getValidationWarnings();
89        $warnings = array_map( static function ( $warningMsgKey ) {
90            return wfMessage( $warningMsgKey );
91        }, $warningMsgKeys );
92
93        // Check for invalid values in skins, rights, namespaces, contentModels, and dependencies
94        $this->checkProperty( $gadget, 'skins', $warnings );
95        $this->checkProperty( $gadget, 'rights', $warnings );
96        $this->checkProperty( $gadget, 'namespaces', $warnings );
97        $this->checkProperty( $gadget, 'contentModels', $warnings );
98        $this->checkProperty( $gadget, 'dependencies', $warnings );
99
100        // Peer gadgets not being styles-only gadgets, or not being defined at all
101        foreach ( $gadget->getPeers() as $peer ) {
102            try {
103                $peerGadget = $this->getGadget( $peer );
104                if ( $peerGadget->getType() !== 'styles' ) {
105                    $warnings[] = wfMessage( "gadgets-validate-invalidpeer", $peer );
106                }
107            } catch ( InvalidArgumentException ) {
108                $warnings[] = wfMessage( "gadgets-validate-nopeer", $peer );
109            }
110        }
111
112        // Check that the gadget pages exist and are of the right content model
113        $warnings = array_merge(
114            $warnings,
115            $this->checkTitles( $gadget->getScripts(), CONTENT_MODEL_JAVASCRIPT,
116                "gadgets-validate-invalidjs" ),
117            $this->checkTitles( $gadget->getStyles(), CONTENT_MODEL_CSS,
118                "gadgets-validate-invalidcss" ),
119            $this->checkTitles( $gadget->getJSONs(), CONTENT_MODEL_JSON,
120                "gadgets-validate-invalidjson" )
121        );
122
123        return $warnings;
124    }
125
126    /**
127     * Verify gadget resource pages exist and use the correct content model.
128     *
129     * @param string[] $pages Full page names
130     * @param string $expectedContentModel
131     * @param string $msg Interface message key
132     * @return Message[]
133     */
134    private function checkTitles( array $pages, string $expectedContentModel, string $msg ): array {
135        $warnings = [];
136        foreach ( $pages as $pageName ) {
137            $title = Title::newFromText( $pageName );
138            if ( !$title ) {
139                $warnings[] = wfMessage( "gadgets-validate-invalidtitle", $pageName );
140                continue;
141            }
142            if ( !$title->exists() ) {
143                $warnings[] = wfMessage( "gadgets-validate-nopage", $pageName );
144                continue;
145            }
146            $contentModel = $title->getContentModel();
147            if ( $contentModel !== $expectedContentModel ) {
148                $warnings[] = wfMessage( $msg, $pageName, $contentModel );
149            }
150        }
151        return $warnings;
152    }
153
154    /**
155     * @param Gadget $gadget
156     * @param string $property
157     * @param Message[] &$warnings
158     */
159    private function checkProperty( Gadget $gadget, string $property, array &$warnings ) {
160        switch ( $property ) {
161            case 'dependencies':
162                $rl = MediaWikiServices::getInstance()->getResourceLoader();
163                $this->maybeAddWarnings( $gadget->getDependencies(),
164                    static function ( $dep ) use ( $rl ) {
165                        return $rl->getModule( $dep ) === null;
166                    }, $warnings, "gadgets-validate-invaliddependencies" );
167                $this->maybeAddWarnings( $gadget->getDependencies(),
168                    static function ( $dep ) use ( $rl ) {
169                        $depModule = $rl->getModule( $dep );
170                        return $depModule !== null && $depModule->getDeprecationWarning() !== null;
171                    }, $warnings, "gadgets-validate-deprecateddependencies" );
172                break;
173
174            case 'skins':
175                $allSkins = array_keys( MediaWikiServices::getInstance()->getSkinFactory()->getInstalledSkins() );
176                $this->maybeAddWarnings( $gadget->getRequiredSkins(),
177                    static function ( $skin ) use ( $allSkins ) {
178                        return !in_array( $skin, $allSkins, true );
179                    }, $warnings, "gadgets-validate-invalidskins" );
180                break;
181
182            case 'rights':
183                $allPerms = MediaWikiServices::getInstance()->getPermissionManager()->getAllPermissions();
184                $this->maybeAddWarnings( $gadget->getRequiredRights(),
185                    static function ( $right ) use ( $allPerms ) {
186                        return !in_array( $right, $allPerms, true );
187                    }, $warnings, "gadgets-validate-invalidrights" );
188                break;
189
190            case 'namespaces':
191                $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
192                $this->maybeAddWarnings( $gadget->getRequiredNamespaces(),
193                    static function ( $ns ) use ( $nsInfo ) {
194                        return !$nsInfo->exists( $ns );
195                    }, $warnings, "gadgets-validate-invalidnamespaces"
196                );
197                break;
198
199            case 'contentModels':
200                $contentHandlerFactory = MediaWikiServices::getInstance()->getContentHandlerFactory();
201                $this->maybeAddWarnings( $gadget->getRequiredContentModels(),
202                    static function ( $model ) use ( $contentHandlerFactory ) {
203                        return !$contentHandlerFactory->isDefinedModel( $model );
204                    }, $warnings, "gadgets-validate-invalidcontentmodels"
205                );
206                break;
207            default:
208        }
209    }
210
211    /**
212     * Iterate over the given $entries, for each check if it is invalid using $isInvalid predicate,
213     * and if so add the $message to $warnings.
214     *
215     * @param array $entries
216     * @param callable $isInvalid
217     * @param array &$warnings
218     * @param string $message
219     */
220    private function maybeAddWarnings( array $entries, callable $isInvalid, array &$warnings, string $message ) {
221        $invalidEntries = [];
222        foreach ( $entries as $entry ) {
223            if ( $isInvalid( $entry ) ) {
224                $invalidEntries[] = $entry;
225            }
226        }
227        if ( $invalidEntries ) {
228            $warnings[] = wfMessage( $message,
229                Message::listParam( $invalidEntries, ListType::COMMA ),
230                count( $invalidEntries ) );
231        }
232    }
233}