Merge "collation: Refactor getFirstLetterData() cache handling"
[lhc/web/wiklou.git] / includes / interwiki / Interwiki.php
1 <?php
2 /**
3 * Interwiki table entry.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22 use \Cdb\Exception as CdbException;
23 use \Cdb\Reader as CdbReader;
24
25 /**
26 * The interwiki class
27 * All information is loaded on creation when called by Interwiki::fetch( $prefix ).
28 * All work is done on slave, because this should *never* change (except during
29 * schema updates etc, which aren't wiki-related)
30 */
31 class Interwiki {
32 // Cache - removes oldest entry when it hits limit
33 protected static $smCache = [];
34 const CACHE_LIMIT = 100; // 0 means unlimited, any other value is max number of entries.
35
36 /** @var string The interwiki prefix, (e.g. "Meatball", or the language prefix "de") */
37 protected $mPrefix;
38
39 /** @var string The URL of the wiki, with "$1" as a placeholder for an article name. */
40 protected $mURL;
41
42 /** @var string The URL of the file api.php */
43 protected $mAPI;
44
45 /** @var string The name of the database (for a connection to be established
46 * with wfGetLB( 'wikiid' ))
47 */
48 protected $mWikiID;
49
50 /** @var bool Whether the wiki is in this project */
51 protected $mLocal;
52
53 /** @var bool Whether interwiki transclusions are allowed */
54 protected $mTrans;
55
56 public function __construct( $prefix = null, $url = '', $api = '', $wikiId = '', $local = 0,
57 $trans = 0
58 ) {
59 $this->mPrefix = $prefix;
60 $this->mURL = $url;
61 $this->mAPI = $api;
62 $this->mWikiID = $wikiId;
63 $this->mLocal = (bool)$local;
64 $this->mTrans = (bool)$trans;
65 }
66
67 /**
68 * Check whether an interwiki prefix exists
69 *
70 * @param string $prefix Interwiki prefix to use
71 * @return bool Whether it exists
72 */
73 public static function isValidInterwiki( $prefix ) {
74 $result = self::fetch( $prefix );
75
76 return (bool)$result;
77 }
78
79 /**
80 * Fetch an Interwiki object
81 *
82 * @param string $prefix Interwiki prefix to use
83 * @return Interwiki|null|bool
84 */
85 public static function fetch( $prefix ) {
86 global $wgContLang;
87
88 if ( $prefix == '' ) {
89 return null;
90 }
91
92 $prefix = $wgContLang->lc( $prefix );
93 if ( isset( self::$smCache[$prefix] ) ) {
94 return self::$smCache[$prefix];
95 }
96
97 global $wgInterwikiCache;
98 if ( $wgInterwikiCache ) {
99 $iw = Interwiki::getInterwikiCached( $prefix );
100 } else {
101 $iw = Interwiki::load( $prefix );
102 if ( !$iw ) {
103 $iw = false;
104 }
105 }
106
107 if ( self::CACHE_LIMIT && count( self::$smCache ) >= self::CACHE_LIMIT ) {
108 reset( self::$smCache );
109 unset( self::$smCache[key( self::$smCache )] );
110 }
111
112 self::$smCache[$prefix] = $iw;
113
114 return $iw;
115 }
116
117 /**
118 * Resets locally cached Interwiki objects. This is intended for use during testing only.
119 * This does not invalidate entries in the persistent cache, as invalidateCache() does.
120 * @since 1.27
121 */
122 public static function resetLocalCache() {
123 static::$smCache = [];
124 }
125
126 /**
127 * Purge the cache (local and persistent) for an interwiki prefix.
128 * @param string $prefix
129 * @since 1.26
130 */
131 public static function invalidateCache( $prefix ) {
132 $cache = ObjectCache::getMainWANInstance();
133 $key = wfMemcKey( 'interwiki', $prefix );
134 $cache->delete( $key );
135 unset( static::$smCache[$prefix] );
136 }
137
138 /**
139 * Fetch interwiki prefix data from local cache in constant database.
140 *
141 * @note More logic is explained in DefaultSettings.
142 *
143 * @param string $prefix Interwiki prefix
144 * @return Interwiki
145 */
146 protected static function getInterwikiCached( $prefix ) {
147 $value = self::getInterwikiCacheEntry( $prefix );
148
149 $s = new Interwiki( $prefix );
150 if ( $value ) {
151 // Split values
152 list( $local, $url ) = explode( ' ', $value, 2 );
153 $s->mURL = $url;
154 $s->mLocal = (bool)$local;
155 } else {
156 $s = false;
157 }
158
159 return $s;
160 }
161
162 /**
163 * Get entry from interwiki cache
164 *
165 * @note More logic is explained in DefaultSettings.
166 *
167 * @param string $prefix Database key
168 * @return bool|string The interwiki entry or false if not found
169 */
170 protected static function getInterwikiCacheEntry( $prefix ) {
171 global $wgInterwikiScopes, $wgInterwikiFallbackSite;
172 static $site;
173
174 $value = false;
175 try {
176 // Resolve site name
177 if ( $wgInterwikiScopes >= 3 && !$site ) {
178 $site = self::getCacheValue( '__sites:' . wfWikiID() );
179 if ( $site == '' ) {
180 $site = $wgInterwikiFallbackSite;
181 }
182 }
183
184 $value = self::getCacheValue( wfMemcKey( $prefix ) );
185 // Site level
186 if ( $value == '' && $wgInterwikiScopes >= 3 ) {
187 $value = self::getCacheValue( "_{$site}:{$prefix}" );
188 }
189 // Global Level
190 if ( $value == '' && $wgInterwikiScopes >= 2 ) {
191 $value = self::getCacheValue( "__global:{$prefix}" );
192 }
193 if ( $value == 'undef' ) {
194 $value = '';
195 }
196 } catch ( CdbException $e ) {
197 wfDebug( __METHOD__ . ": CdbException caught, error message was "
198 . $e->getMessage() );
199 }
200
201 return $value;
202 }
203
204 private static function getCacheValue( $key ) {
205 global $wgInterwikiCache;
206 static $reader;
207 if ( $reader === null ) {
208 $reader = is_array( $wgInterwikiCache ) ? false : CdbReader::open( $wgInterwikiCache );
209 }
210 if ( $reader ) {
211 return $reader->get( $key );
212 } else {
213 return isset( $wgInterwikiCache[$key] ) ? $wgInterwikiCache[$key] : false;
214 }
215 }
216
217 /**
218 * Load the interwiki, trying first memcached then the DB
219 *
220 * @param string $prefix The interwiki prefix
221 * @return Interwiki|bool Interwiki if $prefix is valid, otherwise false
222 */
223 protected static function load( $prefix ) {
224 global $wgInterwikiExpiry;
225
226 $iwData = [];
227 if ( !Hooks::run( 'InterwikiLoadPrefix', [ $prefix, &$iwData ] ) ) {
228 return Interwiki::loadFromArray( $iwData );
229 }
230
231 if ( is_array( $iwData ) ) {
232 $iw = Interwiki::loadFromArray( $iwData );
233 if ( $iw ) {
234 return $iw; // handled by hook
235 }
236 }
237
238 $iwData = ObjectCache::getMainWANInstance()->getWithSetCallback(
239 wfMemcKey( 'interwiki', $prefix ),
240 $wgInterwikiExpiry,
241 function ( $oldValue, &$ttl, array &$setOpts ) use ( $prefix ) {
242 $dbr = wfGetDB( DB_SLAVE );
243
244 $setOpts += Database::getCacheSetOptions( $dbr );
245
246 $row = $dbr->selectRow(
247 'interwiki',
248 Interwiki::selectFields(),
249 [ 'iw_prefix' => $prefix ],
250 __METHOD__
251 );
252
253 return $row ? (array)$row : '!NONEXISTENT';
254 }
255 );
256
257 if ( is_array( $iwData ) ) {
258 return Interwiki::loadFromArray( $iwData ) ?: false;
259 }
260
261 return false;
262 }
263
264 /**
265 * Fill in member variables from an array (e.g. memcached result, Database::fetchRow, etc)
266 *
267 * @param array $mc Associative array: row from the interwiki table
268 * @return Interwiki|bool Interwiki object or false if $mc['iw_url'] is not set
269 */
270 protected static function loadFromArray( $mc ) {
271 if ( isset( $mc['iw_url'] ) ) {
272 $iw = new Interwiki();
273 $iw->mURL = $mc['iw_url'];
274 $iw->mLocal = isset( $mc['iw_local'] ) ? (bool)$mc['iw_local'] : false;
275 $iw->mTrans = isset( $mc['iw_trans'] ) ? (bool)$mc['iw_trans'] : false;
276 $iw->mAPI = isset( $mc['iw_api'] ) ? $mc['iw_api'] : '';
277 $iw->mWikiID = isset( $mc['iw_wikiid'] ) ? $mc['iw_wikiid'] : '';
278
279 return $iw;
280 }
281
282 return false;
283 }
284
285 /**
286 * Fetch all interwiki prefixes from interwiki cache
287 *
288 * @param null|string $local If not null, limits output to local/non-local interwikis
289 * @return array List of prefixes
290 * @since 1.19
291 */
292 protected static function getAllPrefixesCached( $local ) {
293 global $wgInterwikiScopes, $wgInterwikiFallbackSite;
294 static $site;
295
296 wfDebug( __METHOD__ . "()\n" );
297 $data = [];
298 try {
299 /* Resolve site name */
300 if ( $wgInterwikiScopes >= 3 && !$site ) {
301 $site = self::getCacheValue( '__sites:' . wfWikiID() );
302
303 if ( $site == '' ) {
304 $site = $wgInterwikiFallbackSite;
305 }
306 }
307
308 // List of interwiki sources
309 $sources = [];
310 // Global Level
311 if ( $wgInterwikiScopes >= 2 ) {
312 $sources[] = '__global';
313 }
314 // Site level
315 if ( $wgInterwikiScopes >= 3 ) {
316 $sources[] = '_' . $site;
317 }
318 $sources[] = wfWikiID();
319
320 foreach ( $sources as $source ) {
321 $list = self::getCacheValue( '__list:' . $source );
322 foreach ( explode( ' ', $list ) as $iw_prefix ) {
323 $row = self::getCacheValue( "{$source}:{$iw_prefix}" );
324 if ( !$row ) {
325 continue;
326 }
327
328 list( $iw_local, $iw_url ) = explode( ' ', $row );
329
330 if ( $local !== null && $local != $iw_local ) {
331 continue;
332 }
333
334 $data[$iw_prefix] = [
335 'iw_prefix' => $iw_prefix,
336 'iw_url' => $iw_url,
337 'iw_local' => $iw_local,
338 ];
339 }
340 }
341 } catch ( CdbException $e ) {
342 wfDebug( __METHOD__ . ": CdbException caught, error message was "
343 . $e->getMessage() );
344 }
345
346 ksort( $data );
347
348 return array_values( $data );
349 }
350
351 /**
352 * Fetch all interwiki prefixes from DB
353 *
354 * @param string|null $local If not null, limits output to local/non-local interwikis
355 * @return array List of prefixes
356 * @since 1.19
357 */
358 protected static function getAllPrefixesDB( $local ) {
359 $db = wfGetDB( DB_SLAVE );
360
361 $where = [];
362
363 if ( $local !== null ) {
364 if ( $local == 1 ) {
365 $where['iw_local'] = 1;
366 } elseif ( $local == 0 ) {
367 $where['iw_local'] = 0;
368 }
369 }
370
371 $res = $db->select( 'interwiki',
372 self::selectFields(),
373 $where, __METHOD__, [ 'ORDER BY' => 'iw_prefix' ]
374 );
375
376 $retval = [];
377 foreach ( $res as $row ) {
378 $retval[] = (array)$row;
379 }
380
381 return $retval;
382 }
383
384 /**
385 * Returns all interwiki prefixes
386 *
387 * @param string|null $local If set, limits output to local/non-local interwikis
388 * @return array List of prefixes
389 * @since 1.19
390 */
391 public static function getAllPrefixes( $local = null ) {
392 global $wgInterwikiCache;
393
394 if ( $wgInterwikiCache ) {
395 return self::getAllPrefixesCached( $local );
396 }
397
398 return self::getAllPrefixesDB( $local );
399 }
400
401 /**
402 * Get the URL for a particular title (or with $1 if no title given)
403 *
404 * @param string $title What text to put for the article name
405 * @return string The URL
406 * @note Prior to 1.19 The getURL with an argument was broken.
407 * If you if you use this arg in an extension that supports MW earlier
408 * than 1.19 please wfUrlencode and substitute $1 on your own.
409 */
410 public function getURL( $title = null ) {
411 $url = $this->mURL;
412 if ( $title !== null ) {
413 $url = str_replace( "$1", wfUrlencode( $title ), $url );
414 }
415
416 return $url;
417 }
418
419 /**
420 * Get the API URL for this wiki
421 *
422 * @return string The URL
423 */
424 public function getAPI() {
425 return $this->mAPI;
426 }
427
428 /**
429 * Get the DB name for this wiki
430 *
431 * @return string The DB name
432 */
433 public function getWikiID() {
434 return $this->mWikiID;
435 }
436
437 /**
438 * Is this a local link from a sister project, or is
439 * it something outside, like Google
440 *
441 * @return bool
442 */
443 public function isLocal() {
444 return $this->mLocal;
445 }
446
447 /**
448 * Can pages from this wiki be transcluded?
449 * Still requires $wgEnableScaryTransclusion
450 *
451 * @return bool
452 */
453 public function isTranscludable() {
454 return $this->mTrans;
455 }
456
457 /**
458 * Get the name for the interwiki site
459 *
460 * @return string
461 */
462 public function getName() {
463 $msg = wfMessage( 'interwiki-name-' . $this->mPrefix )->inContentLanguage();
464
465 return !$msg->exists() ? '' : $msg->text();
466 }
467
468 /**
469 * Get a description for this interwiki
470 *
471 * @return string
472 */
473 public function getDescription() {
474 $msg = wfMessage( 'interwiki-desc-' . $this->mPrefix )->inContentLanguage();
475
476 return !$msg->exists() ? '' : $msg->text();
477 }
478
479 /**
480 * Return the list of interwiki fields that should be selected to create
481 * a new Interwiki object.
482 * @return string[]
483 */
484 public static function selectFields() {
485 return [
486 'iw_prefix',
487 'iw_url',
488 'iw_api',
489 'iw_wikiid',
490 'iw_local',
491 'iw_trans'
492 ];
493 }
494 }