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