Debian Codegraph @

includes/interwiki/ClassicInterwikiLookup.php

raw symbols SCIP
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
21 namespace MediaWiki\Interwiki;
22
23 use Interwiki;
24 use MapCacheLRU;
25 use MediaWiki\Config\ServiceOptions;
26 use MediaWiki\HookContainer\HookContainer;
27 use MediaWiki\HookContainer\HookRunner;
28 use MediaWiki\Language\Language;
29 use MediaWiki\MainConfigNames;
30 use MediaWiki\WikiMap\WikiMap;
31 use Wikimedia\ObjectCache\WANObjectCache;
32 use Wikimedia\Rdbms\IConnectionProvider;
33
34 /**
35 * InterwikiLookup backed by the `interwiki` database table or $wgInterwikiCache.
36 *
37 * By default this uses the SQL backend (`interwiki` database table) and includes
38 * two levels of caching. When parsing a wiki page, many interwiki lookups may
39 * be required and thus there is in-class caching for repeat lookups. To reduce
40 * database pressure, there is also WANObjectCache for each prefix.
41 *
42 * Optionally, a pregenerated dataset can be statically set via $wgInterwikiCache,
43 * in which case there are no calls to either database or WANObjectCache.
44 *
45 * @since 1.28
46 */
47 class ClassicInterwikiLookup implements InterwikiLookup {
48 /**
49 * @internal For use by ServiceWiring
50 */
51 public const CONSTRUCTOR_OPTIONS = [
52 MainConfigNames::InterwikiExpiry,
53 MainConfigNames::InterwikiCache,
54 MainConfigNames::InterwikiScopes,
55 MainConfigNames::InterwikiFallbackSite,
56 'wikiId',
57 ];
58
59 private ServiceOptions $options;
60 /** @var Language */
61 private $contLang;
62 /** @var WANObjectCache */
63 private $wanCache;
64 /** @var HookRunner */
65 private $hookRunner;
66 /** @var IConnectionProvider */
67 private $dbProvider;
68
69 /** @var MapCacheLRU<Interwiki|false> */
70 private $instances;
71 /**
72 * Specify number of domains to check for messages:
73 * - 1: Just local wiki level
74 * - 2: wiki and global levels
75 * - 3: site level as well as wiki and global levels
76 * @var int
77 */
78 private $interwikiScopes;
79 /** @var array|null Complete pregenerated data if available */
80 private $data;
81 /** @var string */
82 private $wikiId;
83 /** @var string|null */
84 private $thisSite = null;
85
86 /**
87 * @param ServiceOptions $options
88 * @param Language $contLang Language object used to convert prefixes to lower case
89 * @param WANObjectCache $wanCache Cache for interwiki info retrieved from the database
90 * @param HookContainer $hookContainer
91 * @param IConnectionProvider $dbProvider
92 */
93 public function __construct(
94 ServiceOptions $options,
95 Language $contLang,
96 WANObjectCache $wanCache,
97 HookContainer $hookContainer,
98 IConnectionProvider $dbProvider
99 ) {
100 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
101 $this->options = $options;
102
103 $this->contLang = $contLang;
104 $this->wanCache = $wanCache;
105 $this->hookRunner = new HookRunner( $hookContainer );
106 $this->dbProvider = $dbProvider;
107
108 $this->instances = new MapCacheLRU( 1000 );
109 $this->interwikiScopes = $options->get( MainConfigNames::InterwikiScopes );
110
111 $interwikiData = $options->get( MainConfigNames::InterwikiCache );
112 $this->data = is_array( $interwikiData ) ? $interwikiData : null;
113 $this->wikiId = $options->get( 'wikiId' );
114 }
115
116 /**
117 * @inheritDoc
118 * @param string $prefix
119 * @return bool
120 */
121 public function isValidInterwiki( $prefix ) {
122 $iw = $this->fetch( $prefix );
123 return (bool)$iw;
124 }
125
126 /**
127 * @inheritDoc
128 * @param string|null $prefix
129 * @return Interwiki|null|false
130 */
131 public function fetch( $prefix ) {
132 if ( $prefix === null || $prefix === '' ) {
133 return null;
134 }
135
136 $prefix = $this->contLang->lc( $prefix );
137
138 return $this->instances->getWithSetCallback(
139 $prefix,
140 function () use ( $prefix ) {
141 return $this->load( $prefix );
142 }
143 );
144 }
145
146 /**
147 * Purge the instance cache and memcached for an interwiki prefix
148 *
149 * Note that memcached is not used when $wgInterwikiCache
150 * is enabled, as the pregenerated data will be used statically
151 * without need for memcached.
152 *
153 * @param string $prefix
154 */
155 public function invalidateCache( $prefix ) {
156 $this->instances->clear( $prefix );
157
158 $key = $this->wanCache->makeKey( 'interwiki', $prefix );
159 $this->wanCache->delete( $key );
160 }
161
162 /**
163 * Get value from pregenerated data
164 *
165 * @param string $prefix
166 * @return string|false The pregen value or false if prefix is not known
167 */
168 private function getPregenValue( string $prefix ) {
169 // Lazily resolve site name
170 if ( $this->interwikiScopes >= 3 && !$this->thisSite ) {
171 $this->thisSite = $this->data['__sites:' . $this->wikiId]
172 ?? $this->options->get( MainConfigNames::InterwikiFallbackSite );
173 }
174
175 $value = $this->data[$this->wikiId . ':' . $prefix] ?? false;
176 // Site level
177 if ( $value === false && $this->interwikiScopes >= 3 ) {
178 $value = $this->data["_{$this->thisSite}:{$prefix}"] ?? false;
179 }
180 // Global level
181 if ( $value === false && $this->interwikiScopes >= 2 ) {
182 $value = $this->data["__global:{$prefix}"] ?? false;
183 }
184
185 return $value;
186 }
187
188 /**
189 * Fetch interwiki data and create an Interwiki object.
190 *
191 * Use pregenerated data if enabled. Otherwise try memcached first
192 * and fallback to a DB query.
193 *
194 * @param string $prefix The interwiki prefix
195 * @return Interwiki|false False is prefix is invalid
196 */
197 private function load( $prefix ) {
198 if ( $this->data !== null ) {
199 $value = $this->getPregenValue( $prefix );
200 return $value ? $this->makeFromPregen( $prefix, $value ) : false;
201 }
202
203 $iwData = [];
204 $abort = !$this->hookRunner->onInterwikiLoadPrefix( $prefix, $iwData );
205 if ( isset( $iwData['iw_url'] ) ) {
206 // Hook provided data
207 return $this->makeFromRow( $iwData );
208 }
209 if ( $abort ) {
210 // Hook indicated no other source may be considered
211 return false;
212 }
213
214 $fname = __METHOD__;
215 $iwData = $this->wanCache->getWithSetCallback(
216 $this->wanCache->makeKey( 'interwiki', $prefix ),
217 $this->options->get( MainConfigNames::InterwikiExpiry ),
218 function ( $oldValue, &$ttl, array &$setOpts ) use ( $prefix, $fname ) {
219 $dbr = $this->dbProvider->getReplicaDatabase();
220 $row = $dbr->newSelectQueryBuilder()
221 ->select( self::selectFields() )
222 ->from( 'interwiki' )
223 ->where( [ 'iw_prefix' => $prefix ] )
224 ->caller( $fname )->fetchRow();
225
226 return $row ? (array)$row : '!NONEXISTENT';
227 }
228 );
229
230 // Handle non-existent case
231 return is_array( $iwData ) ? $this->makeFromRow( $iwData ) : false;
232 }
233
234 /**
235 * @param array $row Row from the interwiki table, possibly via memcached
236 * @return Interwiki
237 */
238 private function makeFromRow( array $row ) {
239 $url = $row['iw_url'];
240 $local = $row['iw_local'] ?? 0;
241 $trans = $row['iw_trans'] ?? 0;
242 $api = $row['iw_api'] ?? '';
243 $wikiId = $row['iw_wikiid'] ?? '';
244
245 return new Interwiki( null, $url, $api, $wikiId, $local, $trans );
246 }
247
248 /**
249 * @param string $prefix
250 * @param string $value
251 * @return Interwiki
252 */
253 private function makeFromPregen( string $prefix, string $value ) {
254 // Split values
255 [ $local, $url ] = explode( ' ', $value, 2 );
256 return new Interwiki( $prefix, $url, '', '', (int)$local );
257 }
258
259 /**
260 * Fetch all interwiki prefixes from pregenerated data
261 *
262 * @param null|string $local
263 * @return array Database-like rows
264 */
265 private function getAllPrefixesPregenerated( $local ) {
266 // Lazily resolve site name
267 if ( $this->interwikiScopes >= 3 && !$this->thisSite ) {
268 $this->thisSite = $this->data['__sites:' . $this->wikiId]
269 ?? $this->options->get( MainConfigNames::InterwikiFallbackSite );
270 }
271
272 // List of interwiki sources
273 $sources = [];
274 // Global level
275 if ( $this->interwikiScopes >= 2 ) {
276 $sources[] = '__global';
277 }
278 // Site level
279 if ( $this->interwikiScopes >= 3 ) {
280 $sources[] = '_' . $this->thisSite;
281 }
282 $sources[] = $this->wikiId;
283
284 $data = [];
285 foreach ( $sources as $source ) {
286 $list = $this->data['__list:' . $source] ?? '';
287 foreach ( explode( ' ', $list ) as $iw_prefix ) {
288 $row = $this->data["{$source}:{$iw_prefix}"] ?? null;
289 if ( !$row ) {
290 continue;
291 }
292
293 [ $iw_local, $iw_url ] = explode( ' ', $row );
294
295 if ( $local !== null && $local != $iw_local ) {
296 continue;
297 }
298
299 $data[$iw_prefix] = [
300 'iw_prefix' => $iw_prefix,
301 'iw_url' => $iw_url,
302 'iw_local' => $iw_local,
303 ];
304 }
305 }
306
307 return array_values( $data );
308 }
309
310 /**
311 * Build an array in the format accepted by $wgInterwikiCache.
312 *
313 * Given the array returned by getAllPrefixes(), build a PHP array which
314 * can be given to self::__construct() as $interwikiData, i.e. as the
315 * value of $wgInterwikiCache. This is used to construct mock
316 * interwiki lookup services for testing (in particular, parsertests).
317 *
318 * @param array $allPrefixes An array of interwiki information such as
319 * would be returned by ::getAllPrefixes()
320 * @param int $scope The scope at which to insert interwiki prefixes.
321 * See the $interwikiScopes parameter to ::__construct().
322 * @param ?string $thisSite The value of $thisSite, if $scope is 3.
323 * @return array
324 */
325 public static function buildCdbHash(
326 array $allPrefixes, int $scope = 1, ?string $thisSite = null
327 ): array {
328 $result = [];
329 $wikiId = WikiMap::getCurrentWikiId();
330 $keyPrefix = ( $scope >= 2 ) ? '__global' : $wikiId;
331 if ( $scope >= 3 && $thisSite ) {
332 $result[ "__sites:$wikiId" ] = $thisSite;
333 $keyPrefix = "_$thisSite";
334 }
335 $list = [];
336 foreach ( $allPrefixes as $iwInfo ) {
337 $prefix = $iwInfo['iw_prefix'];
338 $result["$keyPrefix:$prefix"] = implode( ' ', [
339 $iwInfo['iw_local'] ?? 0, $iwInfo['iw_url']
340 ] );
341 $list[] = $prefix;
342 }
343 $result["__list:$keyPrefix"] = implode( ' ', $list );
344 $result["__list:__sites"] = $wikiId;
345 return $result;
346 }
347
348 /**
349 * Fetch all interwiki prefixes from DB
350 *
351 * @param bool|null $local
352 * @return array[] Database rows
353 */
354 private function getAllPrefixesDB( $local ) {
355 $where = [];
356 if ( $local !== null ) {
357 $where['iw_local'] = (int)$local;
358 }
359
360 $dbr = $this->dbProvider->getReplicaDatabase();
361 $res = $dbr->newSelectQueryBuilder()
362 ->select( self::selectFields() )
363 ->from( 'interwiki' )
364 ->where( $where )
365 ->orderBy( 'iw_prefix' )
366 ->caller( __METHOD__ )->fetchResultSet();
367
368 $retval = [];
369 foreach ( $res as $row ) {
370 $retval[] = (array)$row;
371 }
372 return $retval;
373 }
374
375 /**
376 * Fetch all interwiki data
377 *
378 * @param string|null $local If set, limit returned data to local or non-local interwikis
379 * @return array[] Database-like interwiki rows
380 */
381 public function getAllPrefixes( $local = null ) {
382 if ( $this->data !== null ) {
383 return $this->getAllPrefixesPregenerated( $local );
384 } else {
385 return $this->getAllPrefixesDB( $local );
386 }
387 }
388
389 /**
390 * List of interwiki table fields to select.
391 *
392 * @return string[]
393 */
394 private static function selectFields() {
395 return [
396 'iw_prefix',
397 'iw_url',
398 'iw_api',
399 'iw_wikiid',
400 'iw_local',
401 'iw_trans'
402 ];
403 }
404
405 }