56 protected $fileFactory = [ ForeignAPIFile::class,
'newFromTitle' ];
74 parent::__construct( $info );
77 $this->mApiBase = $info[
'apibase'] ??
null;
79 if ( isset( $info[
'apiThumbCacheExpiry'] ) ) {
80 $this->apiThumbCacheExpiry = $info[
'apiThumbCacheExpiry'];
82 if ( isset( $info[
'fileCacheExpiry'] ) ) {
83 $this->fileCacheExpiry = $info[
'fileCacheExpiry'];
85 if ( !$this->scriptDirUrl ) {
87 $this->scriptDirUrl = dirname( $this->mApiBase );
94 $this->thumbUrl = $this->url .
'/thumb';
118 return parent::newFile(
$title, $time );
127 foreach ( $files as $k => $f ) {
128 if ( isset( $this->mFileExists[$f] ) ) {
129 $results[$k] = $this->mFileExists[$f];
131 } elseif ( self::isVirtualUrl( $f ) ) {
132 # @todo FIXME: We need to be able to handle virtual
133 # URLs better, at least when we know they refer to the
135 $results[$k] =
false;
138 $results[$k] =
false;
140 wfWarn(
"Got mwstore:// path '$f'." );
145 'titles' => implode(
'|', $files ),
146 'prop' =>
'imageinfo' ]
149 if ( isset( $data[
'query'][
'pages'] ) ) {
150 # First, get results from the query. Note we only care whether the image exists,
151 # not whether it has a description page.
152 foreach ( $data[
'query'][
'pages'] as $p ) {
153 $this->mFileExists[$p[
'title']] = ( $p[
'imagerepository'] !==
'' );
155 # Second, copy the results to any redirects that were queried
156 if ( isset( $data[
'query'][
'redirects'] ) ) {
157 foreach ( $data[
'query'][
'redirects'] as $r ) {
158 $this->mFileExists[$r[
'from']] = $this->mFileExists[$r[
'to']];
161 # Third, copy the results to any non-normalized titles that were queried
162 if ( isset( $data[
'query'][
'normalized'] ) ) {
163 foreach ( $data[
'query'][
'normalized'] as $n ) {
164 $this->mFileExists[$n[
'from']] = $this->mFileExists[$n[
'to']];
167 # Finally, copy the results to the output
168 foreach ( $files as $key =>
$file ) {
169 $results[$key] = $this->mFileExists[
$file];
191 $query = array_merge( $query,
195 'redirects' =>
'true'
198 if ( !isset( $query[
'uselang'] ) ) {
205 return FormatJson::decode( $data,
true );
216 if ( $data && isset( $data[
'query'][
'pages'] ) ) {
217 foreach ( $data[
'query'][
'pages'] as $info ) {
218 if ( isset( $info[
'imageinfo'][0] ) ) {
219 $return = $info[
'imageinfo'][0];
220 if ( isset( $info[
'pageid'] ) ) {
221 $return[
'pageid'] = $info[
'pageid'];
237 'aisha1base36' => $hash,
239 'list' =>
'allimages',
242 if ( isset( $results[
'query'][
'allimages'] ) ) {
243 foreach ( $results[
'query'][
'allimages'] as $img ) {
245 if ( !isset( $img[
'name'] ) ) {
265 $name, $width = -1, $height = -1, &$result =
null, $otherParams =
''
268 'titles' =>
'File:' .
$name,
269 'iiprop' => self::getIIProps(),
270 'iiurlwidth' => $width,
271 'iiurlheight' => $height,
272 'iiurlparam' => $otherParams,
273 'prop' =>
'imageinfo' ] );
276 if ( $data && $info && isset( $info[
'thumburl'] ) ) {
277 wfDebug( __METHOD__ .
" got remote thumb " . $info[
'thumburl'] );
280 return $info[
'thumburl'];
296 $name, $width = -1, $height = -1, $otherParams =
'',
$lang =
null
299 'titles' =>
'File:' .
$name,
300 'iiprop' => self::getIIProps(),
301 'iiurlwidth' => $width,
302 'iiurlheight' => $height,
303 'iiurlparam' => $otherParams,
304 'prop' =>
'imageinfo',
309 if ( $data && $info && isset( $info[
'thumberror'] ) ) {
310 wfDebug( __METHOD__ .
" got remote thumb error " . $info[
'thumberror'] );
313 'thumbnail_error_remote',
349 $sizekey =
"$width:$height:$params";
352 $knownThumbUrls = $this->wanCache->get( $key );
353 if ( !$knownThumbUrls ) {
355 $knownThumbUrls = [];
356 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
357 wfDebug( __METHOD__ .
': Got thumburl from local cache: ' .
358 "{$knownThumbUrls[$sizekey]}" );
360 return $knownThumbUrls[$sizekey];
364 $foreignUrl = $this->
getThumbUrl(
$name, $width, $height, $metadata, $params );
366 if ( !$foreignUrl ) {
367 wfDebug( __METHOD__ .
" Could not find thumburl" );
373 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
375 wfDebug( __METHOD__ .
" The deduced filename $fileName is not safe" );
380 $localFilename = $localPath .
"/" . $fileName;
382 rawurlencode(
$name ) .
"/" . rawurlencode( $fileName );
385 && isset( $metadata[
'timestamp'] )
387 wfDebug( __METHOD__ .
" Thumbnail was already downloaded before" );
389 $remoteModified = strtotime( $metadata[
'timestamp'] );
391 $diff = abs( $modified - $current );
392 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
394 $knownThumbUrls[$sizekey] = $localUrl;
395 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
402 $thumb =
self::httpGet( $foreignUrl,
'default', [], $mtime );
404 wfDebug( __METHOD__ .
" Could not download thumb" );
409 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
411 $params = [
'dst' => $localFilename,
'content' => $thumb ];
413 wfDebug( __METHOD__ .
" could not write to thumb path '$localFilename'" );
417 $knownThumbUrls[$sizekey] = $localUrl;
420 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
422 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
423 wfDebug( __METHOD__ .
" got local thumb $localUrl, saving to cache" );
441 return parent::getZoneUrl( $zone,
$ext );
451 $supported = [
'public',
'thumb' ];
452 if ( in_array( $zone, $supported ) ) {
453 return parent::getZonePath( $zone );
464 return ( $this->apiThumbCacheExpiry > 0 );
472 return MediaWikiServices::getInstance()->getHttpRequestFactory()->getUserAgent() .
483 $info = parent::getInfo();
489 'meta' =>
'siteinfo',
490 'siprop' =>
'general',
496 $siteInfo = FormatJson::decode( $data,
true );
497 $general = $siteInfo[
'query'][
'general'];
499 $info[
'articlepath'] = $general[
'articlepath'];
500 $info[
'server'] = $general[
'server'];
502 if ( isset( $general[
'favicon'] ) ) {
503 $info[
'favicon'] = $general[
'favicon'];
518 $url, $timeout =
'default', $options = [], &$mtime =
false
520 $options[
'timeout'] = $timeout;
523 wfDebug(
"ForeignAPIRepo: HTTP GET: $url" );
524 $options[
'method'] =
"GET";
526 if ( !isset( $options[
'timeout'] ) ) {
527 $options[
'timeout'] =
'default';
532 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()
533 ->create(
$url, $options, __METHOD__ );
534 $status = $req->execute();
536 if ( $status->isOK() ) {
537 $lmod = $req->getResponseHeader(
'Last-Modified' );
538 $mtime = $lmod ?
wfTimestamp( TS_UNIX, $lmod ) :
false;
540 return $req->getContent();
542 $logger = LoggerFactory::getInstance(
'http' );
544 $status->getWikiText(
false,
false,
'en' ),
545 [
'caller' =>
'ForeignAPIRepo::httpGet' ]
557 return implode(
'|', self::IMAGE_INFO_PROPS );
568 if ( $this->mApiBase ) {
574 return $this->wanCache->getWithSetCallback(
577 function ( $curValue, &$ttl ) use (
$url ) {
579 if ( $html !==
false ) {
580 $ttl = $mtime ? $this->wanCache->adaptiveTTL( $mtime, $ttl ) : $ttl;
582 $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
588 [
'pcGroup' =>
'http-get:3',
'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
598 throw new MWException(
'enumFiles is not supported by ' . static::class );
605 throw new MWException( static::class .
': write operations are not supported.' );
$wgLanguageCode
Site language code.
$wgLocalFileRepo
File repository structures.
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 $thumbUrl
The base thumbnail URL.
string false $url
Public zone URL.
validateFilename( $filename)
Determine if a relative path is valid, i.e.
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.
static httpGet( $url, $timeout='default', $options=[], &$mtime=false)
getThumbUrl( $name, $width=-1, $height=-1, &$result=null, $otherParams='')
getInfo()
Get information about the repo - overrides/extends the parent class's information.
const IMAGE_INFO_PROPS
List of iiprop values for the thumbnail fetch queries.
static getUserAgent()
The user agent the ForeignAPIRepo will use.
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)
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