MediaWiki REL1_41
ForeignAPIRepo.php
Go to the documentation of this file.
1<?php
27
45 /* This version string is used in the user agent for requests and will help
46 * server maintainers in identify ForeignAPI usage.
47 * Update the version every time you make breaking or significant changes. */
48 private const VERSION = "2.1";
49
53 private const IMAGE_INFO_PROPS = [
54 'url',
55 'timestamp',
56 ];
57
58 protected $fileFactory = [ ForeignAPIFile::class, 'newFromTitle' ];
60 protected $apiThumbCacheExpiry = 86400; // 1 day (24*3600)
61
63 protected $fileCacheExpiry = 2592000; // 1 month (30*24*3600)
64
76 protected $apiMetadataExpiry = 14400; // 4 hours
77
79 protected $mFileExists = [];
80
82 private $mApiBase;
83
87 public function __construct( $info ) {
88 $localFileRepo = MediaWikiServices::getInstance()->getMainConfig()
89 ->get( MainConfigNames::LocalFileRepo );
90 parent::__construct( $info );
91
92 // https://commons.wikimedia.org/w/api.php
93 $this->mApiBase = $info['apibase'] ?? null;
94
95 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
96 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
97 }
98 if ( isset( $info['fileCacheExpiry'] ) ) {
99 $this->fileCacheExpiry = $info['fileCacheExpiry'];
100 }
101 if ( isset( $info['apiMetadataExpiry'] ) ) {
102 $this->apiMetadataExpiry = $info['apiMetadataExpiry'];
103 }
104 if ( !$this->scriptDirUrl ) {
105 // hack for description fetches
106 $this->scriptDirUrl = dirname( $this->mApiBase );
107 }
108 // If we can cache thumbs we can guess sensible defaults for these
109 if ( $this->canCacheThumbs() && !$this->url ) {
110 $this->url = $localFileRepo['url'];
111 }
112 if ( $this->canCacheThumbs() && !$this->thumbUrl ) {
113 $this->thumbUrl = $this->url . '/thumb';
114 }
115 }
116
120 private function getApiUrl() {
121 return $this->mApiBase;
122 }
123
132 public function newFile( $title, $time = false ) {
133 if ( $time ) {
134 return false;
135 }
136
137 return parent::newFile( $title, $time );
138 }
139
144 public function fileExistsBatch( array $files ) {
145 $results = [];
146 foreach ( $files as $k => $f ) {
147 if ( isset( $this->mFileExists[$f] ) ) {
148 $results[$k] = $this->mFileExists[$f];
149 unset( $files[$k] );
150 } elseif ( self::isVirtualUrl( $f ) ) {
151 # @todo FIXME: We need to be able to handle virtual
152 # URLs better, at least when we know they refer to the
153 # same repo.
154 $results[$k] = false;
155 unset( $files[$k] );
156 } elseif ( FileBackend::isStoragePath( $f ) ) {
157 $results[$k] = false;
158 unset( $files[$k] );
159 wfWarn( "Got mwstore:// path '$f'." );
160 }
161 }
162
163 $data = $this->fetchImageQuery( [
164 'titles' => implode( '|', $files ),
165 'prop' => 'imageinfo' ]
166 );
167
168 if ( isset( $data['query']['pages'] ) ) {
169 # First, get results from the query. Note we only care whether the image exists,
170 # not whether it has a description page.
171 foreach ( $data['query']['pages'] as $p ) {
172 $this->mFileExists[$p['title']] = ( $p['imagerepository'] !== '' );
173 }
174 # Second, copy the results to any redirects that were queried
175 if ( isset( $data['query']['redirects'] ) ) {
176 foreach ( $data['query']['redirects'] as $r ) {
177 $this->mFileExists[$r['from']] = $this->mFileExists[$r['to']];
178 }
179 }
180 # Third, copy the results to any non-normalized titles that were queried
181 if ( isset( $data['query']['normalized'] ) ) {
182 foreach ( $data['query']['normalized'] as $n ) {
183 $this->mFileExists[$n['from']] = $this->mFileExists[$n['to']];
184 }
185 }
186 # Finally, copy the results to the output
187 foreach ( $files as $key => $file ) {
188 $results[$key] = $this->mFileExists[$file];
189 }
190 }
191
192 return $results;
193 }
194
199 public function getFileProps( $virtualUrl ) {
200 return [];
201 }
202
209 public function fetchImageQuery( $query ) {
210 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
211 ->get( MainConfigNames::LanguageCode );
212
213 $query = array_merge( $query,
214 [
215 'format' => 'json',
216 'action' => 'query',
217 'redirects' => 'true'
218 ] );
219
220 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
221 $query['uselang'] = $languageCode;
222 }
223
224 $data = $this->httpGetCached( 'Metadata', $query, $this->apiMetadataExpiry );
225
226 if ( $data ) {
227 return FormatJson::decode( $data, true );
228 } else {
229 return null;
230 }
231 }
232
237 public function getImageInfo( $data ) {
238 if ( $data && isset( $data['query']['pages'] ) ) {
239 foreach ( $data['query']['pages'] as $info ) {
240 if ( isset( $info['imageinfo'][0] ) ) {
241 $return = $info['imageinfo'][0];
242 if ( isset( $info['pageid'] ) ) {
243 $return['pageid'] = $info['pageid'];
244 }
245 return $return;
246 }
247 }
248 }
249
250 return false;
251 }
252
257 public function findBySha1( $hash ) {
258 $results = $this->fetchImageQuery( [
259 'aisha1base36' => $hash,
260 'aiprop' => ForeignAPIFile::getProps(),
261 'list' => 'allimages',
262 ] );
263 $ret = [];
264 if ( isset( $results['query']['allimages'] ) ) {
265 foreach ( $results['query']['allimages'] as $img ) {
266 // 1.14 was broken, doesn't return name attribute
267 if ( !isset( $img['name'] ) ) {
268 continue;
269 }
270 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
271 }
272 }
273
274 return $ret;
275 }
276
286 private function getThumbUrl(
287 $name, $width = -1, $height = -1, &$result = null, $otherParams = ''
288 ) {
289 $data = $this->fetchImageQuery( [
290 'titles' => 'File:' . $name,
291 'iiprop' => self::getIIProps(),
292 'iiurlwidth' => $width,
293 'iiurlheight' => $height,
294 'iiurlparam' => $otherParams,
295 'prop' => 'imageinfo' ] );
296 $info = $this->getImageInfo( $data );
297
298 if ( $data && $info && isset( $info['thumburl'] ) ) {
299 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] );
300 $result = $info;
301
302 return $info['thumburl'];
303 } else {
304 return false;
305 }
306 }
307
317 public function getThumbError(
318 $name, $width = -1, $height = -1, $otherParams = '', $lang = null
319 ) {
320 $data = $this->fetchImageQuery( [
321 'titles' => 'File:' . $name,
322 'iiprop' => self::getIIProps(),
323 'iiurlwidth' => $width,
324 'iiurlheight' => $height,
325 'iiurlparam' => $otherParams,
326 'prop' => 'imageinfo',
327 'uselang' => $lang,
328 ] );
329 $info = $this->getImageInfo( $data );
330
331 if ( $data && $info && isset( $info['thumberror'] ) ) {
332 wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] );
333
334 return new MediaTransformError(
335 'thumbnail_error_remote',
336 $width,
337 $height,
338 $this->getDisplayName(),
339 $info['thumberror'] // already parsed message from foreign repo
340 );
341 } else {
342 return false;
343 }
344 }
345
359 public function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
360 // We can't check the local cache using FileRepo functions because
361 // we override fileExistsBatch(). We have to use the FileBackend directly.
362 $backend = $this->getBackend(); // convenience
363
364 if ( !$this->canCacheThumbs() ) {
365 $result = null; // can't pass "null" by reference, but it's ok as default value
366
367 return $this->getThumbUrl( $name, $width, $height, $result, $params );
368 }
369
370 $key = $this->getLocalCacheKey( 'file-thumb-url', sha1( $name ) );
371 $sizekey = "$width:$height:$params";
372
373 /* Get the array of urls that we already know */
374 $knownThumbUrls = $this->wanCache->get( $key );
375 if ( !$knownThumbUrls ) {
376 /* No knownThumbUrls for this file */
377 $knownThumbUrls = [];
378 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
379 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
380 "{$knownThumbUrls[$sizekey]}" );
381
382 return $knownThumbUrls[$sizekey];
383 }
384
385 $metadata = null;
386 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
387
388 if ( !$foreignUrl ) {
389 wfDebug( __METHOD__ . " Could not find thumburl" );
390
391 return false;
392 }
393
394 // We need the same filename as the remote one :)
395 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
396 if ( !$this->validateFilename( $fileName ) ) {
397 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe" );
398
399 return false;
400 }
401 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
402 $localFilename = $localPath . "/" . $fileName;
403 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) .
404 rawurlencode( $name ) . "/" . rawurlencode( $fileName );
405
406 if ( $backend->fileExists( [ 'src' => $localFilename ] )
407 && isset( $metadata['timestamp'] )
408 ) {
409 wfDebug( __METHOD__ . " Thumbnail was already downloaded before" );
410 $modified = (int)wfTimestamp( TS_UNIX, $backend->getFileTimestamp( [ 'src' => $localFilename ] ) );
411 $remoteModified = (int)wfTimestamp( TS_UNIX, $metadata['timestamp'] );
412 $current = (int)wfTimestamp( TS_UNIX );
413 $diff = abs( $modified - $current );
414 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
415 /* Use our current and already downloaded thumbnail */
416 $knownThumbUrls[$sizekey] = $localUrl;
417 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
418
419 return $localUrl;
420 }
421 /* There is a new Commons file, or existing thumbnail older than a month */
422 }
423
424 $thumb = self::httpGet( $foreignUrl, 'default', [], $mtime );
425 if ( !$thumb ) {
426 wfDebug( __METHOD__ . " Could not download thumb" );
427
428 return false;
429 }
430
431 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
432 $backend->prepare( [ 'dir' => dirname( $localFilename ) ] );
433 $params = [ 'dst' => $localFilename, 'content' => $thumb ];
434 if ( !$backend->quickCreate( $params )->isOK() ) {
435 wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'" );
436
437 return $foreignUrl;
438 }
439 $knownThumbUrls[$sizekey] = $localUrl;
440
441 $ttl = $mtime
442 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
444 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
445 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache" );
446
447 return $localUrl;
448 }
449
456 public function getZoneUrl( $zone, $ext = null ) {
457 switch ( $zone ) {
458 case 'public':
459 return $this->url;
460 case 'thumb':
461 return $this->thumbUrl;
462 default:
463 return parent::getZoneUrl( $zone, $ext );
464 }
465 }
466
472 public function getZonePath( $zone ) {
473 $supported = [ 'public', 'thumb' ];
474 if ( in_array( $zone, $supported ) ) {
475 return parent::getZonePath( $zone );
476 }
477
478 return false;
479 }
480
485 public function canCacheThumbs() {
486 return ( $this->apiThumbCacheExpiry > 0 );
487 }
488
493 public static function getUserAgent() {
494 return MediaWikiServices::getInstance()->getHttpRequestFactory()->getUserAgent() .
495 " ForeignAPIRepo/" . self::VERSION;
496 }
497
504 public function getInfo() {
505 $info = parent::getInfo();
506 $info['apiurl'] = $this->getApiUrl();
507
508 $query = [
509 'format' => 'json',
510 'action' => 'query',
511 'meta' => 'siteinfo',
512 'siprop' => 'general',
513 ];
514
515 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
516
517 if ( $data ) {
518 $siteInfo = FormatJson::decode( $data, true );
519 $general = $siteInfo['query']['general'];
520
521 $info['articlepath'] = $general['articlepath'];
522 $info['server'] = $general['server'];
523 if ( !isset( $info['favicon'] ) && isset( $general['favicon'] ) ) {
524 $info['favicon'] = $general['favicon'];
525 }
526 }
527
528 return $info;
529 }
530
538 public static function httpGet(
539 $url, $timeout = 'default', $options = [], &$mtime = false
540 ) {
541 $options['timeout'] = $timeout;
542 $url = MediaWikiServices::getInstance()->getUrlUtils()
543 ->expand( $url, PROTO_HTTP );
544 wfDebug( "ForeignAPIRepo: HTTP GET: $url" );
545 if ( !$url ) {
546 return false;
547 }
548 $options['method'] = "GET";
549
550 if ( !isset( $options['timeout'] ) ) {
551 $options['timeout'] = 'default';
552 }
553
554 $options['userAgent'] = self::getUserAgent();
555
556 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()
557 ->create( $url, $options, __METHOD__ );
558 $status = $req->execute();
559
560 if ( $status->isOK() ) {
561 $lmod = $req->getResponseHeader( 'Last-Modified' );
562 $mtime = $lmod ? (int)wfTimestamp( TS_UNIX, $lmod ) : false;
563
564 return $req->getContent();
565 } else {
566 $logger = LoggerFactory::getInstance( 'http' );
567 $logger->warning(
568 $status->getWikiText( false, false, 'en' ),
569 [ 'caller' => 'ForeignAPIRepo::httpGet' ]
570 );
571
572 return false;
573 }
574 }
575
580 protected static function getIIProps() {
581 return implode( '|', self::IMAGE_INFO_PROPS );
582 }
583
591 public function httpGetCached( $attribute, $query, $cacheTTL = 3600 ) {
592 if ( $this->mApiBase ) {
593 $url = wfAppendQuery( $this->mApiBase, $query );
594 } else {
595 $url = $this->makeUrl( $query, 'api' );
596 }
597
598 return $this->wanCache->getWithSetCallback(
599 // Allow reusing the same cached data across wikis (T285271).
600 // This does not use getSharedCacheKey() because caching here
601 // is transparent to client wikis (which are not expected to issue purges).
602 $this->wanCache->makeGlobalKey( "filerepo-$attribute", sha1( $url ) ),
603 $cacheTTL,
604 function ( $curValue, &$ttl ) use ( $url ) {
605 $html = self::httpGet( $url, 'default', [], $mtime );
606 // FIXME: This should use the mtime from the api response body
607 // not the mtime from the last-modified header which usually is not set.
608 if ( $html !== false ) {
609 $ttl = $mtime ? $this->wanCache->adaptiveTTL( $mtime, $ttl ) : $ttl;
610 } else {
611 $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
612 $html = null; // caches negatives
613 }
614
615 return $html;
616 },
617 [ 'pcGroup' => 'http-get:3', 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
618 );
619 }
620
624 public function enumFiles( $callback ) {
625 // @phan-suppress-previous-line PhanPluginNeverReturnMethod
626 throw new RuntimeException( 'enumFiles is not supported by ' . static::class );
627 }
628
629 protected function assertWritableRepo() {
630 // @phan-suppress-previous-line PhanPluginNeverReturnMethod
631 throw new MWException( static::class . ': write operations are not supported.' );
632 }
633}
const NS_FILE
Definition Defines.php:70
const PROTO_HTTP
Definition Defines.php:191
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
quickCreate(array $params, array $opts=[])
Performs a single quick create operation.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getFileTimestamp(array $params)
Get the last-modified timestamp of the file at a storage path.
prepare(array $params)
Prepare a storage directory for usage.
Base class for file repositories.
Definition FileRepo.php:50
getDisplayName()
Get the human-readable name of the repo.
getLocalCacheKey( $kClassSuffix,... $components)
Get a site-local, repository-qualified, WAN cache key.
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition FileRepo.php:809
FileBackend $backend
Definition FileRepo.php:73
string false $url
Public zone URL.
Definition FileRepo.php:114
validateFilename( $filename)
Determine if a relative path is valid, i.e.
string $name
Definition FileRepo.php:164
string false $thumbUrl
The base thumbnail URL.
Definition FileRepo.php:117
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:748
getBackend()
Get the file backend instance.
Definition FileRepo.php:253
Foreign file accessible through api.php requests.
static getProps()
Get the property string for iiprop and aiprop.
A foreign repository for a remote MediaWiki accessible through api.php requests.
int $fileCacheExpiry
Redownload thumbnail files after this expiry.
newFile( $title, $time=false)
Per docs in FileRepo, this needs to return false if we don't support versioned files.
int $apiMetadataExpiry
API metadata cache time.
static httpGet( $url, $timeout='default', $options=[], &$mtime=false)
enumFiles( $callback)
getInfo()
Get information about the repo - overrides/extends the parent class's information.
static getUserAgent()
The user agent the ForeignAPIRepo will use.
fetchImageQuery( $query)
Make an API query in the foreign repo, caching results.
getThumbError( $name, $width=-1, $height=-1, $otherParams='', $lang=null)
assertWritableRepo()
Throw an exception if this repo is read-only by design.
canCacheThumbs()
Are we locally caching the thumbnails?
int $apiThumbCacheExpiry
Check back with Commons after this expiry.
getFileProps( $virtualUrl)
getThumbUrlFromCache( $name, $width, $height, $params="")
Return the imageurl from cache if possible.
fileExistsBatch(array $files)
getZoneUrl( $zone, $ext=null)
getZonePath( $zone)
Get the local directory corresponding to one of the basic zones.
httpGetCached( $attribute, $query, $cacheTTL=3600)
HTTP GET request to a mediawiki API (with caching)
MediaWiki exception.
Basic media transform error class.
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Represents a title within MediaWiki.
Definition Title.php:76
A foreign repo that implement support for API queries.
Represents the target of a wiki link.
Interface for objects (potentially) representing an editable wiki page.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42
if(!is_readable( $file)) $ext
Definition router.php:48