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';
119 return parent::newFile(
$title, $time );
128 foreach ( $files as $k => $f ) {
129 if ( isset( $this->mFileExists[$f] ) ) {
130 $results[$k] = $this->mFileExists[$f];
132 } elseif ( self::isVirtualUrl( $f ) ) {
133 # @todo FIXME: We need to be able to handle virtual
134 # URLs better, at least when we know they refer to the
136 $results[$k] =
false;
139 $results[$k] =
false;
141 wfWarn(
"Got mwstore:// path '$f'." );
146 'titles' => implode(
'|', $files ),
147 'prop' =>
'imageinfo' ]
150 if ( isset( $data[
'query'][
'pages'] ) ) {
151 # First, get results from the query. Note we only care whether the image exists,
152 # not whether it has a description page.
153 foreach ( $data[
'query'][
'pages'] as $p ) {
154 $this->mFileExists[$p[
'title']] = ( $p[
'imagerepository'] !==
'' );
156 # Second, copy the results to any redirects that were queried
157 if ( isset( $data[
'query'][
'redirects'] ) ) {
158 foreach ( $data[
'query'][
'redirects'] as $r ) {
159 $this->mFileExists[$r[
'from']] = $this->mFileExists[$r[
'to']];
162 # Third, copy the results to any non-normalized titles that were queried
163 if ( isset( $data[
'query'][
'normalized'] ) ) {
164 foreach ( $data[
'query'][
'normalized'] as $n ) {
165 $this->mFileExists[$n[
'from']] = $this->mFileExists[$n[
'to']];
168 # Finally, copy the results to the output
169 foreach ( $files as $key =>
$file ) {
170 $results[$key] = $this->mFileExists[
$file];
192 $query = array_merge( $query,
196 'redirects' =>
'true'
199 if ( !isset( $query[
'uselang'] ) ) {
206 return FormatJson::decode( $data,
true );
217 if ( $data && isset( $data[
'query'][
'pages'] ) ) {
218 foreach ( $data[
'query'][
'pages'] as $info ) {
219 if ( isset( $info[
'imageinfo'][0] ) ) {
220 $return = $info[
'imageinfo'][0];
221 if ( isset( $info[
'pageid'] ) ) {
222 $return[
'pageid'] = $info[
'pageid'];
238 'aisha1base36' => $hash,
240 'list' =>
'allimages',
243 if ( isset( $results[
'query'][
'allimages'] ) ) {
244 foreach ( $results[
'query'][
'allimages'] as $img ) {
246 if ( !isset( $img[
'name'] ) ) {
265 function getThumbUrl(
$name, $width = -1, $height = -1, &$result =
null, $otherParams =
'' ) {
267 'titles' =>
'File:' .
$name,
268 'iiprop' => self::getIIProps(),
269 'iiurlwidth' => $width,
270 'iiurlheight' => $height,
271 'iiurlparam' => $otherParams,
272 'prop' =>
'imageinfo' ] );
275 if ( $data && $info && isset( $info[
'thumburl'] ) ) {
276 wfDebug( __METHOD__ .
" got remote thumb " . $info[
'thumburl'] .
"\n" );
279 return $info[
'thumburl'];
296 'titles' =>
'File:' .
$name,
297 'iiprop' => self::getIIProps(),
298 'iiurlwidth' => $width,
299 'iiurlheight' => $height,
300 'iiurlparam' => $otherParams,
301 'prop' =>
'imageinfo',
306 if ( $data && $info && isset( $info[
'thumberror'] ) ) {
307 wfDebug( __METHOD__ .
" got remote thumb error " . $info[
'thumberror'] .
"\n" );
310 'thumbnail_error_remote',
344 $sizekey =
"$width:$height:$params";
347 $knownThumbUrls = $this->wanCache->get( $key );
348 if ( !$knownThumbUrls ) {
350 $knownThumbUrls = [];
351 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
352 wfDebug( __METHOD__ .
': Got thumburl from local cache: ' .
353 "{$knownThumbUrls[$sizekey]} \n" );
355 return $knownThumbUrls[$sizekey];
359 $foreignUrl = $this->
getThumbUrl(
$name, $width, $height, $metadata, $params );
361 if ( !$foreignUrl ) {
362 wfDebug( __METHOD__ .
" Could not find thumburl\n" );
368 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
370 wfDebug( __METHOD__ .
" The deduced filename $fileName is not safe\n" );
375 $localFilename = $localPath .
"/" . $fileName;
377 rawurlencode(
$name ) .
"/" . rawurlencode( $fileName );
380 && isset( $metadata[
'timestamp'] )
382 wfDebug( __METHOD__ .
" Thumbnail was already downloaded before\n" );
384 $remoteModified = strtotime( $metadata[
'timestamp'] );
386 $diff = abs( $modified - $current );
387 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
389 $knownThumbUrls[$sizekey] = $localUrl;
390 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
397 $thumb =
self::httpGet( $foreignUrl,
'default', [], $mtime );
399 wfDebug( __METHOD__ .
" Could not download thumb\n" );
404 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
406 $params = [
'dst' => $localFilename,
'content' => $thumb ];
408 wfDebug( __METHOD__ .
" could not write to thumb path '$localFilename'\n" );
412 $knownThumbUrls[$sizekey] = $localUrl;
415 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
417 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
418 wfDebug( __METHOD__ .
" got local thumb $localUrl, saving to cache \n" );
436 return parent::getZoneUrl( $zone,
$ext );
446 $supported = [
'public',
'thumb' ];
447 if ( in_array( $zone, $supported ) ) {
448 return parent::getZonePath( $zone );
459 return ( $this->apiThumbCacheExpiry > 0 );
467 return Http::userAgent() .
" ForeignAPIRepo/" .
self::VERSION;
477 $info = parent::getInfo();
483 'meta' =>
'siteinfo',
484 'siprop' =>
'general',
490 $siteInfo = FormatJson::decode( $data,
true );
491 $general = $siteInfo[
'query'][
'general'];
493 $info[
'articlepath'] = $general[
'articlepath'];
494 $info[
'server'] = $general[
'server'];
496 if ( isset( $general[
'favicon'] ) ) {
497 $info[
'favicon'] = $general[
'favicon'];
515 $url, $timeout =
'default', $options = [], &$mtime =
false
517 $options[
'timeout'] = $timeout;
520 wfDebug(
"ForeignAPIRepo: HTTP GET: $url\n" );
521 $options[
'method'] =
"GET";
523 if ( !isset( $options[
'timeout'] ) ) {
524 $options[
'timeout'] =
'default';
527 $req = MWHttpRequest::factory(
$url, $options, __METHOD__ );
528 $req->setUserAgent( self::getUserAgent() );
529 $status = $req->execute();
531 if ( $status->isOK() ) {
532 $lmod = $req->getResponseHeader(
'Last-Modified' );
533 $mtime = $lmod ?
wfTimestamp( TS_UNIX, $lmod ) :
false;
535 return $req->getContent();
537 $logger = LoggerFactory::getInstance(
'http' );
539 $status->getWikiText(
false,
false,
'en' ),
540 [
'caller' =>
'ForeignAPIRepo::httpGet' ]
552 return implode(
'|', self::$imageInfoProps );
563 if ( $this->mApiBase ) {
569 return $this->wanCache->getWithSetCallback(
572 function ( $curValue, &$ttl ) use (
$url ) {
574 if ( $html !==
false ) {
575 $ttl = $mtime ? $this->wanCache->adaptiveTTL( $mtime, $ttl ) : $ttl;
577 $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
583 [
'pcGroup' =>
'http-get:3',
'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
592 throw new MWException(
'enumFiles is not supported by ' . static::class );
599 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.
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.
quickCreate(array $params)
Performs a single quick create operation.
Base class for file repositories.
getLocalCacheKey()
Get a key for this repo in the local cache domain.
getDisplayName()
Get the human-readable name of the repo.
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 with a remote MediaWiki with an API thingy.
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.
httpGetCached( $target, $query, $cacheTTL=3600)
HTTP GET request to a mediawiki API (with caching)
static httpGet( $url, $timeout='default', $options=[], &$mtime=false)
Like a HttpRequestFactory::get request, but with custom User-Agent.
getThumbUrl( $name, $width=-1, $height=-1, &$result=null, $otherParams='')
getInfo()
Get information about the repo - overrides/extends the parent class's information.
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.
static $imageInfoProps
List of iiprop values for the thumbnail fetch queries.
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.
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