Merge "Http::getProxy() method to get proxy configuration"
[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 = $local;
64 $this->mTrans = $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 * Purge the cache for an interwiki prefix
119 * @param string $prefix
120 * @since 1.26
121 */
122 public static function invalidateCache( $prefix ) {
123 $cache = ObjectCache::getMainWANInstance();
124 $key = wfMemcKey( 'interwiki', $prefix );
125 $cache->delete( $key );
126 }
127
128 /**
129 * Fetch interwiki prefix data from local cache in constant database.
130 *
131 * @note More logic is explained in DefaultSettings.
132 *
133 * @param string $prefix Interwiki prefix
134 * @return Interwiki
135 */
136 protected static function getInterwikiCached( $prefix ) {
137 $value = self::getInterwikiCacheEntry( $prefix );
138
139 $s = new Interwiki( $prefix );
140 if ( $value ) {
141 // Split values
142 list( $local, $url ) = explode( ' ', $value, 2 );
143 $s->mURL = $url;
144 $s->mLocal = (int)$local;
145 } else {
146 $s = false;
147 }
148
149 return $s;
150 }
151
152 /**
153 * Get entry from interwiki cache
154 *
155 * @note More logic is explained in DefaultSettings.
156 *
157 * @param string $prefix Database key
158 * @return bool|string The interwiki entry or false if not found
159 */
160 protected static function getInterwikiCacheEntry( $prefix ) {
161 global $wgInterwikiScopes, $wgInterwikiFallbackSite;
162 static $site;
163
164 wfDebug( __METHOD__ . "( $prefix )\n" );
165 $value = false;
166 try {
167 // Resolve site name
168 if ( $wgInterwikiScopes >= 3 && !$site ) {
169 $site = self::getCacheValue( '__sites:' . wfWikiID() );
170 if ( $site == '' ) {
171 $site = $wgInterwikiFallbackSite;
172 }
173 }
174
175 $value = self::getCacheValue( wfMemcKey( $prefix ) );
176 // Site level
177 if ( $value == '' && $wgInterwikiScopes >= 3 ) {
178 $value = self::getCacheValue( "_{$site}:{$prefix}" );
179 }
180 // Global Level
181 if ( $value == '' && $wgInterwikiScopes >= 2 ) {
182 $value = self::getCacheValue( "__global:{$prefix}" );
183 }
184 if ( $value == 'undef' ) {
185 $value = '';
186 }
187 } catch ( CdbException $e ) {
188 wfDebug( __METHOD__ . ": CdbException caught, error message was "
189 . $e->getMessage() );
190 }
191
192 return $value;
193 }
194
195 private static function getCacheValue( $key ) {
196 global $wgInterwikiCache;
197 static $reader;
198 if ( $reader === null ) {
199 $reader = is_array( $wgInterwikiCache ) ? false : CdbReader::open( $wgInterwikiCache );
200 }
201 if ( $reader ) {
202 return $reader->get( $key );
203 } else {
204 return isset( $wgInterwikiCache[$key] ) ? $wgInterwikiCache[$key] : false;
205 }
206 }
207
208 /**
209 * Load the interwiki, trying first memcached then the DB
210 *
211 * @param string $prefix The interwiki prefix
212 * @return Interwiki|bool Interwiki if $prefix is valid, otherwise false
213 */
214 protected static function load( $prefix ) {
215 global $wgInterwikiExpiry;
216
217 $iwData = [];
218 if ( !Hooks::run( 'InterwikiLoadPrefix', [ $prefix, &$iwData ] ) ) {
219 return Interwiki::loadFromArray( $iwData );
220 }
221
222 if ( is_array( $iwData ) ) {
223 $iw = Interwiki::loadFromArray( $iwData );
224 if ( $iw ) {
225 return $iw; // handled by hook
226 }
227 }
228
229 $iwData = ObjectCache::getMainWANInstance()->getWithSetCallback(
230 wfMemcKey( 'interwiki', $prefix ),
231 $wgInterwikiExpiry,
232 function ( $oldValue, &$ttl, array &$setOpts ) use ( $prefix ) {
233 $dbr = wfGetDB( DB_SLAVE );
234
235 $setOpts += Database::getCacheSetOptions( $dbr );
236
237 $row = $dbr->selectRow(
238 'interwiki',
239 Interwiki::selectFields(),
240 [ 'iw_prefix' => $prefix ],
241 __METHOD__
242 );
243
244 return $row ? (array)$row : '!NONEXISTENT';
245 }
246 );
247
248 if ( is_array( $iwData ) ) {
249 return Interwiki::loadFromArray( $iwData ) ?: false;
250 }
251
252 return false;
253 }
254
255 /**
256 * Fill in member variables from an array (e.g. memcached result, Database::fetchRow, etc)
257 *
258 * @param array $mc Associative array: row from the interwiki table
259 * @return Interwiki|bool Interwiki object or false if $mc['iw_url'] is not set
260 */
261 protected static function loadFromArray( $mc ) {
262 if ( isset( $mc['iw_url'] ) ) {
263 $iw = new Interwiki();
264 $iw->mURL = $mc['iw_url'];
265 $iw->mLocal = isset( $mc['iw_local'] ) ? $mc['iw_local'] : 0;
266 $iw->mTrans = isset( $mc['iw_trans'] ) ? $mc['iw_trans'] : 0;
267 $iw->mAPI = isset( $mc['iw_api'] ) ? $mc['iw_api'] : '';
268 $iw->mWikiID = isset( $mc['iw_wikiid'] ) ? $mc['iw_wikiid'] : '';
269
270 return $iw;
271 }
272
273 return false;
274 }
275
276 /**
277 * Fetch all interwiki prefixes from interwiki cache
278 *
279 * @param null|string $local If not null, limits output to local/non-local interwikis
280 * @return array List of prefixes
281 * @since 1.19
282 */
283 protected static function getAllPrefixesCached( $local ) {
284 global $wgInterwikiScopes, $wgInterwikiFallbackSite;
285 static $site;
286
287 wfDebug( __METHOD__ . "()\n" );
288 $data = [];
289 try {
290 /* Resolve site name */
291 if ( $wgInterwikiScopes >= 3 && !$site ) {
292 $site = self::getCacheValue( '__sites:' . wfWikiID() );
293
294 if ( $site == '' ) {
295 $site = $wgInterwikiFallbackSite;
296 }
297 }
298
299 // List of interwiki sources
300 $sources = [];
301 // Global Level
302 if ( $wgInterwikiScopes >= 2 ) {
303 $sources[] = '__global';
304 }
305 // Site level
306 if ( $wgInterwikiScopes >= 3 ) {
307 $sources[] = '_' . $site;
308 }
309 $sources[] = wfWikiID();
310
311 foreach ( $sources as $source ) {
312 $list = self::getCacheValue( '__list:' . $source );
313 foreach ( explode( ' ', $list ) as $iw_prefix ) {
314 $row = self::getCacheValue( "{$source}:{$iw_prefix}" );
315 if ( !$row ) {
316 continue;
317 }
318
319 list( $iw_local, $iw_url ) = explode( ' ', $row );
320
321 if ( $local !== null && $local != $iw_local ) {
322 continue;
323 }
324
325 $data[$iw_prefix] = [
326 'iw_prefix' => $iw_prefix,
327 'iw_url' => $iw_url,
328 'iw_local' => $iw_local,
329 ];
330 }
331 }
332 } catch ( CdbException $e ) {
333 wfDebug( __METHOD__ . ": CdbException caught, error message was "
334 . $e->getMessage() );
335 }
336
337 ksort( $data );
338
339 return array_values( $data );
340 }
341
342 /**
343 * Fetch all interwiki prefixes from DB
344 *
345 * @param string|null $local If not null, limits output to local/non-local interwikis
346 * @return array List of prefixes
347 * @since 1.19
348 */
349 protected static function getAllPrefixesDB( $local ) {
350 $db = wfGetDB( DB_SLAVE );
351
352 $where = [];
353
354 if ( $local !== null ) {
355 if ( $local == 1 ) {
356 $where['iw_local'] = 1;
357 } elseif ( $local == 0 ) {
358 $where['iw_local'] = 0;
359 }
360 }
361
362 $res = $db->select( 'interwiki',
363 self::selectFields(),
364 $where, __METHOD__, [ 'ORDER BY' => 'iw_prefix' ]
365 );
366
367 $retval = [];
368 foreach ( $res as $row ) {
369 $retval[] = (array)$row;
370 }
371
372 return $retval;
373 }
374
375 /**
376 * Returns all interwiki prefixes
377 *
378 * @param string|null $local If set, limits output to local/non-local interwikis
379 * @return array List of prefixes
380 * @since 1.19
381 */
382 public static function getAllPrefixes( $local = null ) {
383 global $wgInterwikiCache;
384
385 if ( $wgInterwikiCache ) {
386 return self::getAllPrefixesCached( $local );
387 }
388
389 return self::getAllPrefixesDB( $local );
390 }
391
392 /**
393 * Get the URL for a particular title (or with $1 if no title given)
394 *
395 * @param string $title What text to put for the article name
396 * @return string The URL
397 * @note Prior to 1.19 The getURL with an argument was broken.
398 * If you if you use this arg in an extension that supports MW earlier
399 * than 1.19 please wfUrlencode and substitute $1 on your own.
400 */
401 public function getURL( $title = null ) {
402 $url = $this->mURL;
403 if ( $title !== null ) {
404 $url = str_replace( "$1", wfUrlencode( $title ), $url );
405 }
406
407 return $url;
408 }
409
410 /**
411 * Get the API URL for this wiki
412 *
413 * @return string The URL
414 */
415 public function getAPI() {
416 return $this->mAPI;
417 }
418
419 /**
420 * Get the DB name for this wiki
421 *
422 * @return string The DB name
423 */
424 public function getWikiID() {
425 return $this->mWikiID;
426 }
427
428 /**
429 * Is this a local link from a sister project, or is
430 * it something outside, like Google
431 *
432 * @return bool
433 */
434 public function isLocal() {
435 return $this->mLocal;
436 }
437
438 /**
439 * Can pages from this wiki be transcluded?
440 * Still requires $wgEnableScaryTransclusion
441 *
442 * @return bool
443 */
444 public function isTranscludable() {
445 return $this->mTrans;
446 }
447
448 /**
449 * Get the name for the interwiki site
450 *
451 * @return string
452 */
453 public function getName() {
454 $msg = wfMessage( 'interwiki-name-' . $this->mPrefix )->inContentLanguage();
455
456 return !$msg->exists() ? '' : $msg;
457 }
458
459 /**
460 * Get a description for this interwiki
461 *
462 * @return string
463 */
464 public function getDescription() {
465 $msg = wfMessage( 'interwiki-desc-' . $this->mPrefix )->inContentLanguage();
466
467 return !$msg->exists() ? '' : $msg;
468 }
469
470 /**
471 * Return the list of interwiki fields that should be selected to create
472 * a new Interwiki object.
473 * @return string[]
474 */
475 public static function selectFields() {
476 return [
477 'iw_prefix',
478 'iw_url',
479 'iw_api',
480 'iw_wikiid',
481 'iw_local',
482 'iw_trans'
483 ];
484 }
485 }