Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / interwiki / ClassicInterwikiLookup.php
blob13be7333f1571c55a3784f8819655cfe5414df3e
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.
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.
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
18 * @file
21 namespace MediaWiki\Interwiki;
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\Languages\LanguageNameUtils;
30 use MediaWiki\MainConfigNames;
31 use MediaWiki\WikiMap\WikiMap;
32 use Wikimedia\ObjectCache\WANObjectCache;
33 use Wikimedia\Rdbms\IConnectionProvider;
35 /**
36 * InterwikiLookup backed by the `interwiki` database table or $wgInterwikiCache.
38 * By default this uses the SQL backend (`interwiki` database table) and includes
39 * two levels of caching. When parsing a wiki page, many interwiki lookups may
40 * be required and thus there is in-class caching for repeat lookups. To reduce
41 * database pressure, there is also WANObjectCache for each prefix.
43 * Optionally, a pregenerated dataset can be statically set via $wgInterwikiCache,
44 * in which case there are no calls to either database or WANObjectCache.
46 * @since 1.28
48 class ClassicInterwikiLookup implements InterwikiLookup {
49 /**
50 * @internal For use by ServiceWiring
52 public const CONSTRUCTOR_OPTIONS = [
53 MainConfigNames::InterwikiExpiry,
54 MainConfigNames::InterwikiCache,
55 MainConfigNames::InterwikiScopes,
56 MainConfigNames::InterwikiFallbackSite,
57 MainConfigNames::InterwikiMagic,
58 MainConfigNames::VirtualDomainsMapping,
59 'wikiId',
62 private ServiceOptions $options;
63 private Language $contLang;
64 private WANObjectCache $wanCache;
65 private HookRunner $hookRunner;
66 private IConnectionProvider $dbProvider;
67 private LanguageNameUtils $languageNameUtils;
69 /** @var MapCacheLRU<Interwiki|false> */
70 private MapCacheLRU $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
77 private int $interwikiScopes;
78 /** Complete pregenerated data if available */
79 private ?array $data;
80 private string $wikiId;
81 private ?string $thisSite = null;
82 private array $virtualDomainsMapping;
84 /**
85 * @param ServiceOptions $options
86 * @param Language $contLang Language object used to convert prefixes to lower case
87 * @param WANObjectCache $wanCache Cache for interwiki info retrieved from the database
88 * @param HookContainer $hookContainer
89 * @param IConnectionProvider $dbProvider
90 * @param LanguageNameUtils $languageNameUtils
92 public function __construct(
93 ServiceOptions $options,
94 Language $contLang,
95 WANObjectCache $wanCache,
96 HookContainer $hookContainer,
97 IConnectionProvider $dbProvider,
98 LanguageNameUtils $languageNameUtils
99 ) {
100 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
101 $this->options = $options;
103 $this->contLang = $contLang;
104 $this->wanCache = $wanCache;
105 $this->hookRunner = new HookRunner( $hookContainer );
106 $this->dbProvider = $dbProvider;
107 $this->languageNameUtils = $languageNameUtils;
109 $this->instances = new MapCacheLRU( 1000 );
110 $this->interwikiScopes = $options->get( MainConfigNames::InterwikiScopes );
112 $interwikiData = $options->get( MainConfigNames::InterwikiCache );
113 $this->data = is_array( $interwikiData ) ? $interwikiData : null;
114 $this->wikiId = $options->get( 'wikiId' );
115 $this->virtualDomainsMapping = $options->get( MainConfigNames::VirtualDomainsMapping ) ?? [];
119 * @inheritDoc
120 * @param string $prefix
121 * @return bool
123 public function isValidInterwiki( $prefix ) {
124 $iw = $this->fetch( $prefix );
125 return (bool)$iw;
129 * @inheritDoc
130 * @param string|null $prefix
131 * @return Interwiki|null|false
133 public function fetch( $prefix ) {
134 if ( $prefix === null || $prefix === '' ) {
135 return null;
138 $prefix = $this->contLang->lc( $prefix );
140 return $this->instances->getWithSetCallback(
141 $prefix,
142 function () use ( $prefix ) {
143 return $this->load( $prefix );
149 * Purge the instance cache and memcached for an interwiki prefix
151 * Note that memcached is not used when $wgInterwikiCache
152 * is enabled, as the pregenerated data will be used statically
153 * without need for memcached.
155 * @param string $prefix
157 public function invalidateCache( $prefix ) {
158 $this->instances->clear( $prefix );
160 $key = $this->wanCache->makeKey( 'interwiki', $prefix );
161 $this->wanCache->delete( $key );
165 * Get value from pregenerated data
167 * @param string $prefix
168 * @return string|false The pregen value or false if prefix is not known
170 private function getPregenValue( string $prefix ) {
171 // Lazily resolve site name
172 if ( $this->interwikiScopes >= 3 && !$this->thisSite ) {
173 $this->thisSite = $this->data['__sites:' . $this->wikiId]
174 ?? $this->options->get( MainConfigNames::InterwikiFallbackSite );
177 $value = $this->data[$this->wikiId . ':' . $prefix] ?? false;
178 // Site level
179 if ( $value === false && $this->interwikiScopes >= 3 ) {
180 $value = $this->data["_{$this->thisSite}:{$prefix}"] ?? false;
182 // Global level
183 if ( $value === false && $this->interwikiScopes >= 2 ) {
184 $value = $this->data["__global:{$prefix}"] ?? false;
187 return $value;
191 * Fetch interwiki data and create an Interwiki object.
193 * Use pregenerated data if enabled. Otherwise try memcached first
194 * and fallback to a DB query.
196 * @param string $prefix The interwiki prefix
197 * @return Interwiki|false False is prefix is invalid
199 private function load( $prefix ) {
200 if ( $this->data !== null ) {
201 $value = $this->getPregenValue( $prefix );
202 return $value ? $this->makeFromPregen( $prefix, $value ) : false;
205 $iwData = [];
206 $abort = !$this->hookRunner->onInterwikiLoadPrefix( $prefix, $iwData );
207 if ( isset( $iwData['iw_url'] ) ) {
208 // Hook provided data
209 return $this->makeFromRow( $iwData );
211 if ( $abort ) {
212 // Hook indicated no other source may be considered
213 return false;
216 $iwData = $this->wanCache->getWithSetCallback(
217 $this->wanCache->makeKey( 'interwiki', $prefix ),
218 $this->options->get( MainConfigNames::InterwikiExpiry ),
219 function ( $oldValue, &$ttl, array &$setOpts ) use ( $prefix ) {
220 // Global interlanguage link
221 if ( $this->options->get( MainConfigNames::InterwikiMagic )
222 && $this->languageNameUtils->getLanguageName( $prefix )
224 $row = $this->loadFromDB( $prefix, 'virtual-interwiki-interlanguage' );
225 } else {
226 // Local interwiki link
227 $row = $this->loadFromDB( $prefix );
229 // Global interwiki link (not interlanguage)
230 if ( !$row && isset( $this->virtualDomainsMapping['virtual-interwiki'] ) ) {
231 $row = $this->loadFromDB( $prefix, 'virtual-interwiki' );
235 return $row ? (array)$row : '!NONEXISTENT';
239 // Handle non-existent case
240 return is_array( $iwData ) ? $this->makeFromRow( $iwData ) : false;
244 * Fetch interwiki data from a DB query.
246 * @param string $prefix The interwiki prefix
247 * @param string|false $domain Domain ID, or false for the current domain
248 * @return stdClass|false interwiki data
250 private function loadFromDB( $prefix, $domain = false ) {
251 $dbr = $this->dbProvider->getReplicaDatabase( $domain );
252 $row = $dbr->newSelectQueryBuilder()
253 ->select( self::selectFields() )
254 ->from( 'interwiki' )
255 ->where( [ 'iw_prefix' => $prefix ] )
256 ->caller( __METHOD__ )->fetchRow();
258 return $row;
262 * @param array $row Row from the interwiki table, possibly via memcached
263 * @return Interwiki
265 private function makeFromRow( array $row ) {
266 $url = $row['iw_url'];
267 $local = $row['iw_local'] ?? 0;
268 $trans = $row['iw_trans'] ?? 0;
269 $api = $row['iw_api'] ?? '';
270 $wikiId = $row['iw_wikiid'] ?? '';
272 return new Interwiki( null, $url, $api, $wikiId, $local, $trans );
276 * @param string $prefix
277 * @param string $value
278 * @return Interwiki
280 private function makeFromPregen( string $prefix, string $value ) {
281 // Split values
282 [ $local, $url ] = explode( ' ', $value, 2 );
283 return new Interwiki( $prefix, $url, '', '', (int)$local );
287 * Fetch all interwiki prefixes from pregenerated data
289 * @param null|string $local
290 * @return array Database-like rows
292 private function getAllPrefixesPregenerated( $local ) {
293 // Lazily resolve site name
294 if ( $this->interwikiScopes >= 3 && !$this->thisSite ) {
295 $this->thisSite = $this->data['__sites:' . $this->wikiId]
296 ?? $this->options->get( MainConfigNames::InterwikiFallbackSite );
299 // List of interwiki sources
300 $sources = [];
301 // Global level
302 if ( $this->interwikiScopes >= 2 ) {
303 $sources[] = '__global';
305 // Site level
306 if ( $this->interwikiScopes >= 3 ) {
307 $sources[] = '_' . $this->thisSite;
309 $sources[] = $this->wikiId;
311 $data = [];
312 foreach ( $sources as $source ) {
313 $list = $this->data['__list:' . $source] ?? '';
314 foreach ( explode( ' ', $list ) as $iw_prefix ) {
315 $row = $this->data["{$source}:{$iw_prefix}"] ?? null;
316 if ( !$row ) {
317 continue;
320 [ $iw_local, $iw_url ] = explode( ' ', $row );
322 if ( $local !== null && $local != $iw_local ) {
323 continue;
326 $data[$iw_prefix] = [
327 'iw_prefix' => $iw_prefix,
328 'iw_url' => $iw_url,
329 'iw_local' => $iw_local,
334 return array_values( $data );
338 * Build an array in the format accepted by $wgInterwikiCache.
340 * Given the array returned by getAllPrefixes(), build a PHP array which
341 * can be given to self::__construct() as $interwikiData, i.e. as the
342 * value of $wgInterwikiCache. This is used to construct mock
343 * interwiki lookup services for testing (in particular, parsertests).
345 * @param array $allPrefixes An array of interwiki information such as
346 * would be returned by ::getAllPrefixes()
347 * @param int $scope The scope at which to insert interwiki prefixes.
348 * See the $interwikiScopes parameter to ::__construct().
349 * @param ?string $thisSite The value of $thisSite, if $scope is 3.
350 * @return array
352 public static function buildCdbHash(
353 array $allPrefixes, int $scope = 1, ?string $thisSite = null
354 ): array {
355 $result = [];
356 $wikiId = WikiMap::getCurrentWikiId();
357 $keyPrefix = ( $scope >= 2 ) ? '__global' : $wikiId;
358 if ( $scope >= 3 && $thisSite ) {
359 $result[ "__sites:$wikiId" ] = $thisSite;
360 $keyPrefix = "_$thisSite";
362 $list = [];
363 foreach ( $allPrefixes as $iwInfo ) {
364 $prefix = $iwInfo['iw_prefix'];
365 $result["$keyPrefix:$prefix"] = implode( ' ', [
366 $iwInfo['iw_local'] ?? 0, $iwInfo['iw_url']
367 ] );
368 $list[] = $prefix;
370 $result["__list:$keyPrefix"] = implode( ' ', $list );
371 $result["__list:__sites"] = $wikiId;
372 return $result;
376 * Fetch all interwiki prefixes from DB
378 * @param bool|null $local
379 * @return array[] Database rows
381 private function getAllPrefixesDB( $local ) {
382 $where = [];
383 if ( $local !== null ) {
384 $where['iw_local'] = (int)$local;
387 $dbr = $this->dbProvider->getReplicaDatabase();
388 $res = $dbr->newSelectQueryBuilder()
389 ->select( self::selectFields() )
390 ->from( 'interwiki' )
391 ->where( $where )
392 ->orderBy( 'iw_prefix' )
393 ->caller( __METHOD__ )->fetchResultSet();
395 $retval = [];
396 foreach ( $res as $row ) {
397 $retval[] = (array)$row;
399 return $retval;
403 * Fetch all interwiki data
405 * @param string|null $local If set, limit returned data to local or non-local interwikis
406 * @return array[] Database-like interwiki rows
408 public function getAllPrefixes( $local = null ) {
409 if ( $this->data !== null ) {
410 return $this->getAllPrefixesPregenerated( $local );
411 } else {
412 return $this->getAllPrefixesDB( $local );
417 * List of interwiki table fields to select.
419 * @return string[]
421 private static function selectFields() {
422 return [
423 'iw_prefix',
424 'iw_url',
425 'iw_api',
426 'iw_wikiid',
427 'iw_local',
428 'iw_trans'