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