51 private const VERSION =
"2.1";
56 private const IMAGE_INFO_PROPS = [
62 protected $fileFactory = [ ForeignAPIFile::class,
'newFromTitle' ];
92 $localFileRepo = MediaWikiServices::getInstance()->getMainConfig()
93 ->get( MainConfigNames::LocalFileRepo );
94 parent::__construct( $info );
97 $this->mApiBase = $info[
'apibase'] ??
null;
99 if ( isset( $info[
'apiThumbCacheExpiry'] ) ) {
100 $this->apiThumbCacheExpiry = $info[
'apiThumbCacheExpiry'];
102 if ( isset( $info[
'fileCacheExpiry'] ) ) {
103 $this->fileCacheExpiry = $info[
'fileCacheExpiry'];
105 if ( isset( $info[
'apiMetadataExpiry'] ) ) {
106 $this->apiMetadataExpiry = $info[
'apiMetadataExpiry'];
108 if ( !$this->scriptDirUrl ) {
110 $this->scriptDirUrl = dirname( $this->mApiBase );
114 $this->url = $localFileRepo[
'url'];
117 $this->thumbUrl = $this->url .
'/thumb';
129 public function newFile( $title, $time =
false ) {
134 return parent::newFile( $title, $time );
143 foreach ( $files as $k => $f ) {
144 if ( isset( $this->mFileExists[$f] ) ) {
145 $results[$k] = $this->mFileExists[$f];
147 } elseif ( self::isVirtualUrl( $f ) ) {
148 # @todo FIXME: We need to be able to handle virtual
149 # URLs better, at least when we know they refer to the
151 $results[$k] =
false;
153 } elseif ( FileBackend::isStoragePath( $f ) ) {
154 $results[$k] =
false;
156 wfWarn(
"Got mwstore:// path '$f'." );
161 'titles' => implode(
'|', $files ),
162 'prop' =>
'imageinfo' ]
165 if ( isset( $data[
'query'][
'pages'] ) ) {
166 # First, get results from the query. Note we only care whether the image exists,
167 # not whether it has a description page.
168 foreach ( $data[
'query'][
'pages'] as $p ) {
169 $this->mFileExists[$p[
'title']] = ( $p[
'imagerepository'] !==
'' );
171 # Second, copy the results to any redirects that were queried
172 if ( isset( $data[
'query'][
'redirects'] ) ) {
173 foreach ( $data[
'query'][
'redirects'] as $r ) {
174 $this->mFileExists[$r[
'from']] = $this->mFileExists[$r[
'to']];
177 # Third, copy the results to any non-normalized titles that were queried
178 if ( isset( $data[
'query'][
'normalized'] ) ) {
179 foreach ( $data[
'query'][
'normalized'] as $n ) {
180 $this->mFileExists[$n[
'from']] = $this->mFileExists[$n[
'to']];
183 # Finally, copy the results to the output
184 foreach ( $files as $key => $file ) {
185 $results[$key] = $this->mFileExists[$file];
207 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
208 ->get( MainConfigNames::LanguageCode );
210 $query = array_merge( $query,
214 'redirects' =>
'true'
217 if ( !isset( $query[
'uselang'] ) ) {
218 $query[
'uselang'] = $languageCode;
221 $data = $this->
httpGetCached(
'Metadata', $query, $this->apiMetadataExpiry );
224 return FormatJson::decode( $data,
true );
235 if ( $data && isset( $data[
'query'][
'pages'] ) ) {
236 foreach ( $data[
'query'][
'pages'] as $info ) {
237 if ( isset( $info[
'imageinfo'][0] ) ) {
238 $return = $info[
'imageinfo'][0];
239 if ( isset( $info[
'pageid'] ) ) {
240 $return[
'pageid'] = $info[
'pageid'];
256 'aisha1base36' => $hash,
258 'list' =>
'allimages',
261 if ( isset( $results[
'query'][
'allimages'] ) ) {
262 foreach ( $results[
'query'][
'allimages'] as $img ) {
264 if ( !isset( $img[
'name'] ) ) {
283 private function getThumbUrl(
284 $name, $width = -1, $height = -1, &$result =
null, $otherParams =
''
287 'titles' =>
'File:' .
$name,
288 'iiprop' => self::getIIProps(),
289 'iiurlwidth' => $width,
290 'iiurlheight' => $height,
291 'iiurlparam' => $otherParams,
292 'prop' =>
'imageinfo' ] );
295 if ( $data && $info && isset( $info[
'thumburl'] ) ) {
296 wfDebug( __METHOD__ .
" got remote thumb " . $info[
'thumburl'] );
299 return $info[
'thumburl'];
315 $name, $width = -1, $height = -1, $otherParams =
'', $lang =
null
318 'titles' =>
'File:' .
$name,
319 'iiprop' => self::getIIProps(),
320 'iiurlwidth' => $width,
321 'iiurlheight' => $height,
322 'iiurlparam' => $otherParams,
323 'prop' =>
'imageinfo',
328 if ( $data && $info && isset( $info[
'thumberror'] ) ) {
329 wfDebug( __METHOD__ .
" got remote thumb error " . $info[
'thumberror'] );
332 'thumbnail_error_remote',
364 return $this->getThumbUrl(
$name, $width, $height, $result,
$params );
368 $sizekey =
"$width:$height:$params";
371 $knownThumbUrls = $this->wanCache->get( $key );
372 if ( !$knownThumbUrls ) {
374 $knownThumbUrls = [];
375 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
376 wfDebug( __METHOD__ .
': Got thumburl from local cache: ' .
377 "{$knownThumbUrls[$sizekey]}" );
379 return $knownThumbUrls[$sizekey];
383 $foreignUrl = $this->getThumbUrl(
$name, $width, $height, $metadata,
$params );
385 if ( !$foreignUrl ) {
386 wfDebug( __METHOD__ .
" Could not find thumburl" );
392 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
394 wfDebug( __METHOD__ .
" The deduced filename $fileName is not safe" );
399 $localFilename = $localPath .
"/" . $fileName;
401 rawurlencode(
$name ) .
"/" . rawurlencode( $fileName );
404 && isset( $metadata[
'timestamp'] )
406 wfDebug( __METHOD__ .
" Thumbnail was already downloaded before" );
408 $remoteModified = (int)
wfTimestamp( TS_UNIX, $metadata[
'timestamp'] );
410 $diff = abs( $modified - $current );
411 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
413 $knownThumbUrls[$sizekey] = $localUrl;
414 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
421 $thumb =
self::httpGet( $foreignUrl,
'default', [], $mtime );
423 wfDebug( __METHOD__ .
" Could not download thumb" );
428 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
430 $params = [
'dst' => $localFilename,
'content' => $thumb ];
432 wfDebug( __METHOD__ .
" could not write to thumb path '$localFilename'" );
436 $knownThumbUrls[$sizekey] = $localUrl;
439 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
441 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
442 wfDebug( __METHOD__ .
" got local thumb $localUrl, saving to cache" );
460 return parent::getZoneUrl( $zone, $ext );
470 $supported = [
'public',
'thumb' ];
471 if ( in_array( $zone, $supported ) ) {
472 return parent::getZonePath( $zone );
483 return ( $this->apiThumbCacheExpiry > 0 );
491 return MediaWikiServices::getInstance()->getHttpRequestFactory()->getUserAgent() .
492 " ForeignAPIRepo/" . self::VERSION;
502 $info = parent::getInfo();
503 $info[
'apiurl'] = $this->mApiBase;
508 'meta' =>
'siteinfo',
509 'siprop' =>
'general',
515 $siteInfo = FormatJson::decode( $data,
true );
516 $general = $siteInfo[
'query'][
'general'];
518 $info[
'articlepath'] = $general[
'articlepath'];
519 $info[
'server'] = $general[
'server'];
520 if ( !isset( $info[
'favicon'] ) && isset( $general[
'favicon'] ) ) {
521 $info[
'favicon'] = $general[
'favicon'];
536 $url, $timeout =
'default', $options = [], &$mtime =
false
538 $options[
'timeout'] = $timeout;
539 $url = MediaWikiServices::getInstance()->getUrlUtils()
541 wfDebug(
"ForeignAPIRepo: HTTP GET: $url" );
545 $options[
'method'] =
"GET";
547 if ( !isset( $options[
'timeout'] ) ) {
548 $options[
'timeout'] =
'default';
553 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()
554 ->create(
$url, $options, __METHOD__ );
555 $status = $req->execute();
557 if ( $status->isOK() ) {
558 $lmod = $req->getResponseHeader(
'Last-Modified' );
559 $mtime = $lmod ? (int)
wfTimestamp( TS_UNIX, $lmod ) :
false;
561 return $req->getContent();
563 $logger = LoggerFactory::getInstance(
'http' );
565 $status->getWikiText(
false,
false,
'en' ),
566 [
'caller' =>
'ForeignAPIRepo::httpGet' ]
578 return implode(
'|', self::IMAGE_INFO_PROPS );
589 if ( $this->mApiBase ) {
595 return $this->wanCache->getWithSetCallback(
599 $this->wanCache->makeGlobalKey(
"filerepo-$attribute", sha1(
$url ) ),
601 function ( $curValue, &$ttl ) use (
$url ) {
605 if ( $html !==
false ) {
606 $ttl = $mtime ? $this->wanCache->adaptiveTTL( $mtime, $ttl ) : $ttl;
608 $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
614 [
'pcGroup' =>
'http-get:3',
'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
623 throw new RuntimeException(
'enumFiles is not supported by ' . static::class );
630 throw new LogicException( static::class .
': write operations are not supported.' );
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.
array $params
The job parameters.
Base class for file repositories.
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.
string false $url
Public zone URL.
validateFilename( $filename)
Determine if a relative path is valid, i.e.
string false $thumbUrl
The base thumbnail URL.
getHashPath( $name)
Get a relative path including trailing slash, e.g.
getBackend()
Get the file backend instance.
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)
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)
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)
A class containing constants representing the names of configuration variables.
A foreign repo that implement support for API queries.
Interface for objects (potentially) representing an editable wiki page.