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
21 namespace MediaWiki\Interwiki
;
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
;
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.
48 class ClassicInterwikiLookup
implements InterwikiLookup
{
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
,
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;
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 */
80 private string $wikiId;
81 private ?
string $thisSite = null;
82 private array $virtualDomainsMapping;
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,
95 WANObjectCache
$wanCache,
96 HookContainer
$hookContainer,
97 IConnectionProvider
$dbProvider,
98 LanguageNameUtils
$languageNameUtils
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
) ??
[];
120 * @param string $prefix
123 public function isValidInterwiki( $prefix ) {
124 $iw = $this->fetch( $prefix );
130 * @param string|null $prefix
131 * @return Interwiki|null|false
133 public function fetch( $prefix ) {
134 if ( $prefix === null ||
$prefix === '' ) {
138 $prefix = $this->contLang
->lc( $prefix );
140 return $this->instances
->getWithSetCallback(
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;
179 if ( $value === false && $this->interwikiScopes
>= 3 ) {
180 $value = $this->data
["_{$this->thisSite}:{$prefix}"] ??
false;
183 if ( $value === false && $this->interwikiScopes
>= 2 ) {
184 $value = $this->data
["__global:{$prefix}"] ??
false;
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;
206 $abort = !$this->hookRunner
->onInterwikiLoadPrefix( $prefix, $iwData );
207 if ( isset( $iwData['iw_url'] ) ) {
208 // Hook provided data
209 return $this->makeFromRow( $iwData );
212 // Hook indicated no other source may be considered
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' );
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();
262 * @param array $row Row from the interwiki table, possibly via memcached
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
280 private function makeFromPregen( string $prefix, string $value ) {
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
302 if ( $this->interwikiScopes
>= 2 ) {
303 $sources[] = '__global';
306 if ( $this->interwikiScopes
>= 3 ) {
307 $sources[] = '_' . $this->thisSite
;
309 $sources[] = $this->wikiId
;
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;
320 [ $iw_local, $iw_url ] = explode( ' ', $row );
322 if ( $local !== null && $local != $iw_local ) {
326 $data[$iw_prefix] = [
327 'iw_prefix' => $iw_prefix,
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.
352 public static function buildCdbHash(
353 array $allPrefixes, int $scope = 1, ?
string $thisSite = null
356 $wikiId = WikiMap
::getCurrentWikiId();
357 $keyPrefix = ( $scope >= 2 ) ?
'__global' : $wikiId;
358 if ( $scope >= 3 && $thisSite ) {
359 $result[ "__sites:$wikiId" ] = $thisSite;
360 $keyPrefix = "_$thisSite";
363 foreach ( $allPrefixes as $iwInfo ) {
364 $prefix = $iwInfo['iw_prefix'];
365 $result["$keyPrefix:$prefix"] = implode( ' ', [
366 $iwInfo['iw_local'] ??
0, $iwInfo['iw_url']
370 $result["__list:$keyPrefix"] = implode( ' ', $list );
371 $result["__list:__sites"] = $wikiId;
376 * Fetch all interwiki prefixes from DB
378 * @param bool|null $local
379 * @return array[] Database rows
381 private function getAllPrefixesDB( $local ) {
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' )
392 ->orderBy( 'iw_prefix' )
393 ->caller( __METHOD__
)->fetchResultSet();
396 foreach ( $res as $row ) {
397 $retval[] = (array)$row;
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 );
412 return $this->getAllPrefixesDB( $local );
417 * List of interwiki table fields to select.
421 private static function selectFields() {