Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
81.18% covered (warning)
81.18%
69 / 85
45.45% covered (danger)
45.45%
5 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
MediaWikiGadgetsJsonRepo
81.18% covered (warning)
81.18%
69 / 85
45.45% covered (danger)
45.45%
5 / 11
25.23
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
 getGadgetIds
100.00% covered (success)
100.00%
35 / 35
100.00% covered (success)
100.00%
1 / 1
3
 handlePageUpdate
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 purgeGadgetIdsList
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getGadgetId
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 isGadgetDefinitionTitle
57.14% covered (warning)
57.14%
4 / 7
0.00% covered (danger)
0.00%
0 / 1
3.71
 getGadgetDefinitionTitle
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getGadget
77.42% covered (warning)
77.42%
24 / 31
0.00% covered (danger)
0.00%
0 / 1
5.29
 purgeGadgetEntry
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getGadgetIdsKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getGadgetCacheKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace MediaWiki\Extension\Gadgets;
4
5use InvalidArgumentException;
6use MediaWiki\Extension\Gadgets\Content\GadgetDefinitionContent;
7use MediaWiki\Linker\LinkTarget;
8use MediaWiki\Revision\RevisionLookup;
9use MediaWiki\Revision\SlotRecord;
10use MediaWiki\Title\Title;
11use Wikimedia\ArrayUtils\ArrayUtils;
12use Wikimedia\ObjectCache\WANObjectCache;
13use Wikimedia\Rdbms\IConnectionProvider;
14use Wikimedia\Rdbms\IExpression;
15use Wikimedia\Rdbms\LikeValue;
16
17/**
18 * Gadgets repo powered by `MediaWiki:Gadgets/<id>.json` pages.
19 *
20 * Each gadget has its own gadget definition page, using GadgetDefinitionContent.
21 */
22class MediaWikiGadgetsJsonRepo extends GadgetRepo {
23    public const DEF_PREFIX = 'Gadgets/';
24    public const DEF_SUFFIX = '.json';
25
26    public function __construct(
27        private readonly IConnectionProvider $dbProvider,
28        private readonly WANObjectCache $wanCache,
29        private readonly RevisionLookup $revLookup,
30    ) {
31    }
32
33    /**
34     * Get a list of gadget ids from cache/database
35     *
36     * @return string[]
37     */
38    public function getGadgetIds(): array {
39        $key = $this->getGadgetIdsKey();
40
41        $fname = __METHOD__;
42        $dbr = $this->dbProvider->getReplicaDatabase();
43        $titles = $this->wanCache->getWithSetCallback(
44            $key,
45            WANObjectCache::TTL_DAY,
46            static function () use ( $fname, $dbr ) {
47                return $dbr->newSelectQueryBuilder()
48                    ->select( 'page_title' )
49                    ->from( 'page' )
50                    ->where( [
51                        'page_namespace' => NS_MEDIAWIKI,
52                        'page_content_model' => 'GadgetDefinition',
53                        $dbr->expr(
54                            'page_title',
55                            IExpression::LIKE,
56                            new LikeValue( self::DEF_PREFIX, $dbr->anyString(), self::DEF_SUFFIX )
57                        )
58                    ] )
59                    ->caller( $fname )
60                    ->fetchFieldValues();
61            },
62            [
63                // Bump when changing the database query
64                'version' => 2,
65                'checkKeys' => [ $key ],
66                'pcTTL' => WANObjectCache::TTL_PROC_LONG,
67                'lockTSE' => 30
68            ]
69        );
70
71        $ids = [];
72        foreach ( $titles as $title ) {
73            $id = self::getGadgetId( $title );
74            if ( $id !== '' ) {
75                $ids[] = $id;
76            }
77        }
78        return $ids;
79    }
80
81    /**
82     * @inheritDoc
83     */
84    public function handlePageUpdate( LinkTarget $target ): void {
85        if ( $this->isGadgetDefinitionTitle( $target ) ) {
86            $this->purgeGadgetIdsList();
87            $this->purgeGadgetEntry( self::getGadgetId( $target->getText() ) );
88        }
89    }
90
91    /**
92     * Purge the list of gadget ids when a page is deleted or if a new page is created
93     */
94    public function purgeGadgetIdsList(): void {
95        $this->wanCache->touchCheckKey( $this->getGadgetIdsKey() );
96    }
97
98    /**
99     * @param string $title Gadget definition page title
100     * @return string Gadget ID
101     */
102    private static function getGadgetId( string $title ): string {
103        if ( !str_starts_with( $title, self::DEF_PREFIX ) || !str_ends_with( $title, self::DEF_SUFFIX ) ) {
104            throw new InvalidArgumentException( 'Invalid definition page title' );
105        }
106        return substr( $title, strlen( self::DEF_PREFIX ), -strlen( self::DEF_SUFFIX ) );
107    }
108
109    public static function isGadgetDefinitionTitle( LinkTarget $target ): bool {
110        if ( !$target->inNamespace( NS_MEDIAWIKI ) ) {
111            return false;
112        }
113        $title = $target->getText();
114        try {
115            self::getGadgetId( $title );
116            return true;
117        } catch ( InvalidArgumentException ) {
118            return false;
119        }
120    }
121
122    /**
123     * @inheritDoc
124     */
125    public function getGadgetDefinitionTitle( string $id ): ?Title {
126        return Title::makeTitleSafe( NS_MEDIAWIKI, self::DEF_PREFIX . $id . self::DEF_SUFFIX );
127    }
128
129    /**
130     * @param string $id
131     * @throws InvalidArgumentException
132     * @return Gadget
133     */
134    public function getGadget( string $id ): Gadget {
135        $key = $this->getGadgetCacheKey( $id );
136        $gadget = $this->wanCache->getWithSetCallback(
137            $key,
138            WANObjectCache::TTL_DAY,
139            function ( $old, &$ttl ) use ( $id ) {
140                $title = $this->getGadgetDefinitionTitle( $id );
141                if ( !$title ) {
142                    $ttl = WANObjectCache::TTL_UNCACHEABLE;
143                    return null;
144                }
145
146                $revRecord = $this->revLookup->getRevisionByTitle( $title );
147                if ( !$revRecord ) {
148                    $ttl = WANObjectCache::TTL_UNCACHEABLE;
149                    return null;
150                }
151
152                $content = $revRecord->getContent( SlotRecord::MAIN );
153                if ( !$content instanceof GadgetDefinitionContent ) {
154                    // Uhm...
155                    $ttl = WANObjectCache::TTL_UNCACHEABLE;
156                    return null;
157                }
158
159                $handler = $content->getContentHandler();
160                '@phan-var \MediaWiki\Extension\Gadgets\Content\GadgetDefinitionContentHandler $handler';
161                $data = ArrayUtils::arrayPlus2d( $content->getAssocArray(), $handler->getDefaultMetadata() );
162                return Gadget::serializeDefinition( $id, $data );
163            },
164            [
165                'checkKeys' => [ $key ],
166                'pcTTL' => WANObjectCache::TTL_PROC_SHORT,
167                'lockTSE' => 30,
168                'version' => 2,
169            ]
170        );
171
172        if ( $gadget === null ) {
173            throw new InvalidArgumentException( "Unknown gadget $id" );
174        }
175
176        return new Gadget( $gadget );
177    }
178
179    /**
180     * Update the cache for a specific Gadget whenever it is updated
181     *
182     * @param string $id
183     */
184    public function purgeGadgetEntry( $id ) {
185        $this->wanCache->touchCheckKey( $this->getGadgetCacheKey( $id ) );
186    }
187
188    /**
189     * @return string
190     */
191    private function getGadgetIdsKey() {
192        return $this->wanCache->makeKey( 'gadgets-jsonrepo-ids' );
193    }
194
195    /**
196     * @param string $id
197     * @return string
198     */
199    private function getGadgetCacheKey( $id ) {
200        return $this->wanCache->makeKey( 'gadgets-object', $id, Gadget::GADGET_CLASS_VERSION );
201    }
202}