47 private const VERSION =
"2.1";
52 private const IMAGE_INFO_PROPS = [
57 protected $fileFactory = [ ForeignAPIFile::class,
'newFromTitle' ];
87 $localFileRepo = MediaWikiServices::getInstance()->getMainConfig()
88 ->get( MainConfigNames::LocalFileRepo );
89 parent::__construct( $info );
92 $this->mApiBase = $info[
'apibase'] ??
null;
94 if ( isset( $info[
'apiThumbCacheExpiry'] ) ) {
95 $this->apiThumbCacheExpiry = $info[
'apiThumbCacheExpiry'];
97 if ( isset( $info[
'fileCacheExpiry'] ) ) {
98 $this->fileCacheExpiry = $info[
'fileCacheExpiry'];
100 if ( isset( $info[
'apiMetadataExpiry'] ) ) {
101 $this->apiMetadataExpiry = $info[
'apiMetadataExpiry'];
103 if ( !$this->scriptDirUrl ) {
105 $this->scriptDirUrl = dirname( $this->mApiBase );
109 $this->url = $localFileRepo[
'url'];
112 $this->thumbUrl = $this->url .
'/thumb';
119 private function getApiUrl() {
120 return $this->mApiBase;
136 return parent::newFile(
$title, $time );
145 foreach ( $files as $k => $f ) {
146 if ( isset( $this->mFileExists[$f] ) ) {
147 $results[$k] = $this->mFileExists[$f];
149 } elseif ( self::isVirtualUrl( $f ) ) {
150 # @todo FIXME: We need to be able to handle virtual
151 # URLs better, at least when we know they refer to the
153 $results[$k] =
false;
156 $results[$k] =
false;
158 wfWarn(
"Got mwstore:// path '$f'." );
163 'titles' => implode(
'|', $files ),
164 'prop' =>
'imageinfo' ]
167 if ( isset( $data[
'query'][
'pages'] ) ) {
168 # First, get results from the query. Note we only care whether the image exists,
169 # not whether it has a description page.
170 foreach ( $data[
'query'][
'pages'] as $p ) {
171 $this->mFileExists[$p[
'title']] = ( $p[
'imagerepository'] !==
'' );
173 # Second, copy the results to any redirects that were queried
174 if ( isset( $data[
'query'][
'redirects'] ) ) {
175 foreach ( $data[
'query'][
'redirects'] as $r ) {
176 $this->mFileExists[$r[
'from']] = $this->mFileExists[$r[
'to']];
179 # Third, copy the results to any non-normalized titles that were queried
180 if ( isset( $data[
'query'][
'normalized'] ) ) {
181 foreach ( $data[
'query'][
'normalized'] as $n ) {
182 $this->mFileExists[$n[
'from']] = $this->mFileExists[$n[
'to']];
185 # Finally, copy the results to the output
186 foreach ( $files as $key =>
$file ) {
187 $results[$key] = $this->mFileExists[
$file];
209 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
210 ->get( MainConfigNames::LanguageCode );
212 $query = array_merge( $query,
216 'redirects' =>
'true'
219 if ( !isset( $query[
'uselang'] ) ) {
220 $query[
'uselang'] = $languageCode;
223 $data = $this->
httpGetCached(
'Metadata', $query, $this->apiMetadataExpiry );
226 return FormatJson::decode( $data,
true );
237 if ( $data && isset( $data[
'query'][
'pages'] ) ) {
238 foreach ( $data[
'query'][
'pages'] as $info ) {
239 if ( isset( $info[
'imageinfo'][0] ) ) {
240 $return = $info[
'imageinfo'][0];
241 if ( isset( $info[
'pageid'] ) ) {
242 $return[
'pageid'] = $info[
'pageid'];
258 'aisha1base36' => $hash,
260 'list' =>
'allimages',
263 if ( isset( $results[
'query'][
'allimages'] ) ) {
264 foreach ( $results[
'query'][
'allimages'] as $img ) {
266 if ( !isset( $img[
'name'] ) ) {
285 private function getThumbUrl(
286 $name, $width = -1, $height = -1, &$result =
null, $otherParams =
''
289 'titles' =>
'File:' .
$name,
290 'iiprop' => self::getIIProps(),
291 'iiurlwidth' => $width,
292 'iiurlheight' => $height,
293 'iiurlparam' => $otherParams,
294 'prop' =>
'imageinfo' ] );
297 if ( $data && $info && isset( $info[
'thumburl'] ) ) {
298 wfDebug( __METHOD__ .
" got remote thumb " . $info[
'thumburl'] );
301 return $info[
'thumburl'];
317 $name, $width = -1, $height = -1, $otherParams =
'',
$lang =
null
320 'titles' =>
'File:' .
$name,
321 'iiprop' => self::getIIProps(),
322 'iiurlwidth' => $width,
323 'iiurlheight' => $height,
324 'iiurlparam' => $otherParams,
325 'prop' =>
'imageinfo',
330 if ( $data && $info && isset( $info[
'thumberror'] ) ) {
331 wfDebug( __METHOD__ .
" got remote thumb error " . $info[
'thumberror'] );
334 'thumbnail_error_remote',
366 return $this->getThumbUrl(
$name, $width, $height, $result, $params );
370 $sizekey =
"$width:$height:$params";
373 $knownThumbUrls = $this->wanCache->get( $key );
374 if ( !$knownThumbUrls ) {
376 $knownThumbUrls = [];
377 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
378 wfDebug( __METHOD__ .
': Got thumburl from local cache: ' .
379 "{$knownThumbUrls[$sizekey]}" );
381 return $knownThumbUrls[$sizekey];
385 $foreignUrl = $this->getThumbUrl(
$name, $width, $height, $metadata, $params );
387 if ( !$foreignUrl ) {
388 wfDebug( __METHOD__ .
" Could not find thumburl" );
394 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
396 wfDebug( __METHOD__ .
" The deduced filename $fileName is not safe" );
401 $localFilename = $localPath .
"/" . $fileName;
403 rawurlencode(
$name ) .
"/" . rawurlencode( $fileName );
406 && isset( $metadata[
'timestamp'] )
408 wfDebug( __METHOD__ .
" Thumbnail was already downloaded before" );
410 $remoteModified = (int)
wfTimestamp( TS_UNIX, $metadata[
'timestamp'] );
412 $diff = abs( $modified - $current );
413 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
415 $knownThumbUrls[$sizekey] = $localUrl;
416 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
423 $thumb =
self::httpGet( $foreignUrl,
'default', [], $mtime );
425 wfDebug( __METHOD__ .
" Could not download thumb" );
430 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
432 $params = [
'dst' => $localFilename,
'content' => $thumb ];
434 wfDebug( __METHOD__ .
" could not write to thumb path '$localFilename'" );
438 $knownThumbUrls[$sizekey] = $localUrl;
441 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
443 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
444 wfDebug( __METHOD__ .
" got local thumb $localUrl, saving to cache" );
462 return parent::getZoneUrl( $zone,
$ext );
472 $supported = [
'public',
'thumb' ];
473 if ( in_array( $zone, $supported ) ) {
474 return parent::getZonePath( $zone );
485 return ( $this->apiThumbCacheExpiry > 0 );
493 return MediaWikiServices::getInstance()->getHttpRequestFactory()->getUserAgent() .
494 " ForeignAPIRepo/" . self::VERSION;
504 $info = parent::getInfo();
505 $info[
'apiurl'] = $this->getApiUrl();
510 'meta' =>
'siteinfo',
511 'siprop' =>
'general',
517 $siteInfo = FormatJson::decode( $data,
true );
518 $general = $siteInfo[
'query'][
'general'];
520 $info[
'articlepath'] = $general[
'articlepath'];
521 $info[
'server'] = $general[
'server'];
522 if ( !isset( $info[
'favicon'] ) && isset( $general[
'favicon'] ) ) {
523 $info[
'favicon'] = $general[
'favicon'];
538 $url, $timeout =
'default', $options = [], &$mtime =
false
540 $options[
'timeout'] = $timeout;
543 wfDebug(
"ForeignAPIRepo: HTTP GET: $url" );
544 $options[
'method'] =
"GET";
546 if ( !isset( $options[
'timeout'] ) ) {
547 $options[
'timeout'] =
'default';
552 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()
553 ->create(
$url, $options, __METHOD__ );
554 $status = $req->execute();
556 if ( $status->isOK() ) {
557 $lmod = $req->getResponseHeader(
'Last-Modified' );
558 $mtime = $lmod ? (int)
wfTimestamp( TS_UNIX, $lmod ) :
false;
560 return $req->getContent();
562 $logger = LoggerFactory::getInstance(
'http' );
564 $status->getWikiText(
false,
false,
'en' ),
565 [
'caller' =>
'ForeignAPIRepo::httpGet' ]
577 return implode(
'|', self::IMAGE_INFO_PROPS );
588 if ( $this->mApiBase ) {
594 return $this->wanCache->getWithSetCallback(
598 $this->wanCache->makeGlobalKey(
"filerepo-$attribute", sha1(
$url ) ),
600 function ( $curValue, &$ttl ) use (
$url ) {
604 if ( $html !==
false ) {
605 $ttl = $mtime ? $this->wanCache->adaptiveTTL( $mtime, $ttl ) : $ttl;
607 $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
613 [
'pcGroup' =>
'http-get:3',
'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
623 throw new MWException(
'enumFiles is not supported by ' . static::class );
630 throw new MWException( 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.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
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.
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.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!is_readable( $file)) $ext
if(!isset( $args[0])) $lang