23use Wikimedia\Timestamp\ConvertibleTimestamp;
24use Wikimedia\Timestamp\TimestampFormat as TS;
46 private const VERSION =
"2.1";
51 private const IMAGE_INFO_PROPS = [
57 protected $fileFactory = [ ForeignAPIFile::class,
'newFromTitle' ];
92 parent::__construct( $info );
95 $this->mApiBase = $info[
'apibase'] ??
null;
97 if ( isset( $info[
'apiThumbCacheExpiry'] ) ) {
98 $this->apiThumbCacheExpiry = $info[
'apiThumbCacheExpiry'];
100 if ( isset( $info[
'fileCacheExpiry'] ) ) {
101 $this->fileCacheExpiry = $info[
'fileCacheExpiry'];
103 if ( isset( $info[
'apiMetadataExpiry'] ) ) {
104 $this->apiMetadataExpiry = $info[
'apiMetadataExpiry'];
106 if ( isset( $info[
'userAgent'] ) ) {
107 $this->userAgent = $info[
'userAgent'];
109 if ( !$this->scriptDirUrl ) {
111 $this->scriptDirUrl = dirname( $this->mApiBase );
115 $this->url = $localFileRepo[
'url'];
118 $this->thumbUrl = $this->url .
'/thumb';
130 public function newFile( $title, $time =
false ) {
135 return parent::newFile( $title, $time );
144 foreach ( $files as $k => $f ) {
145 if ( isset( $this->mFileExists[$f] ) ) {
146 $results[$k] = $this->mFileExists[$f];
148 } elseif ( self::isVirtualUrl( $f ) ) {
149 # @todo FIXME: We need to be able to handle virtual
150 # URLs better, at least when we know they refer to the
152 $results[$k] =
false;
155 $results[$k] =
false;
157 wfWarn(
"Got mwstore:// path '$f'." );
162 'titles' => implode(
'|', $files ),
163 'prop' =>
'imageinfo' ]
166 if ( isset( $data[
'query'][
'pages'] ) ) {
167 # First, get results from the query. Note we only care whether the image exists,
168 # not whether it has a description page.
169 foreach ( $data[
'query'][
'pages'] as $p ) {
170 $this->mFileExists[$p[
'title']] = ( $p[
'imagerepository'] !==
'' );
172 # Second, copy the results to any redirects that were queried
173 if ( isset( $data[
'query'][
'redirects'] ) ) {
174 foreach ( $data[
'query'][
'redirects'] as $r ) {
175 $this->mFileExists[$r[
'from']] = $this->mFileExists[$r[
'to']];
178 # Third, copy the results to any non-normalized titles that were queried
179 if ( isset( $data[
'query'][
'normalized'] ) ) {
180 foreach ( $data[
'query'][
'normalized'] as $n ) {
181 $this->mFileExists[$n[
'from']] = $this->mFileExists[$n[
'to']];
184 # Finally, copy the results to the output
185 foreach ( $files as $key => $file ) {
186 $results[$key] = $this->mFileExists[$file];
211 $query = array_merge( $query,
215 'redirects' =>
'true'
218 if ( !isset( $query[
'uselang'] ) ) {
219 $query[
'uselang'] = $languageCode;
222 $data = $this->
httpGetCached(
'Metadata', $query, $this->apiMetadataExpiry );
225 return FormatJson::decode( $data,
true );
236 if ( $data && isset( $data[
'query'][
'pages'] ) ) {
237 foreach ( $data[
'query'][
'pages'] as $info ) {
238 if ( isset( $info[
'imageinfo'][0] ) ) {
239 $return = $info[
'imageinfo'][0];
240 if ( isset( $info[
'pageid'] ) ) {
241 $return[
'pageid'] = $info[
'pageid'];
257 'aisha1base36' => $hash,
259 'list' =>
'allimages',
262 if ( isset( $results[
'query'][
'allimages'] ) ) {
263 foreach ( $results[
'query'][
'allimages'] as $img ) {
265 if ( !isset( $img[
'name'] ) ) {
284 private function getThumbUrl(
285 $name, $width = -1, $height = -1, &$result =
null, $otherParams =
''
288 'titles' =>
'File:' .
$name,
289 'iiprop' => self::getIIProps(),
290 'iiurlwidth' => $width,
291 'iiurlheight' => $height,
292 'iiurlparam' => $otherParams,
293 'prop' =>
'imageinfo' ] );
296 if ( $data && $info && isset( $info[
'thumburl'] ) ) {
297 wfDebug( __METHOD__ .
" got remote thumb " . $info[
'thumburl'] );
300 return $info[
'thumburl'];
316 $name, $width = -1, $height = -1, $otherParams =
'', $lang =
null
319 'titles' =>
'File:' .
$name,
320 'iiprop' => self::getIIProps(),
321 'iiurlwidth' => $width,
322 'iiurlheight' => $height,
323 'iiurlparam' => $otherParams,
324 'prop' =>
'imageinfo',
329 if ( $data && $info && isset( $info[
'thumberror'] ) ) {
330 wfDebug( __METHOD__ .
" got remote thumb error " . $info[
'thumberror'] );
333 'thumbnail_error_remote',
365 return $this->getThumbUrl(
$name, $width, $height, $result, $params );
369 $sizekey =
"$width:$height:$params";
372 $knownThumbUrls = $this->wanCache->get( $key );
373 if ( !$knownThumbUrls ) {
375 $knownThumbUrls = [];
376 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
377 wfDebug( __METHOD__ .
': Got thumburl from local cache: ' .
378 "{$knownThumbUrls[$sizekey]}" );
380 return $knownThumbUrls[$sizekey];
384 $foreignUrl = $this->getThumbUrl(
$name, $width, $height, $metadata, $params );
386 if ( !$foreignUrl ) {
387 wfDebug( __METHOD__ .
" Could not find thumburl" );
393 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
395 wfDebug( __METHOD__ .
" The deduced filename $fileName is not safe" );
400 $localFilename = $localPath .
"/" . $fileName;
402 rawurlencode(
$name ) .
"/" . rawurlencode( $fileName );
405 && isset( $metadata[
'timestamp'] )
407 wfDebug( __METHOD__ .
" Thumbnail was already downloaded before" );
409 $remoteModified = (int)
wfTimestamp( TS::UNIX, $metadata[
'timestamp'] );
410 $current = (int)ConvertibleTimestamp::now( TS::UNIX );
411 $diff = abs( $modified - $current );
412 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
414 $knownThumbUrls[$sizekey] = $localUrl;
415 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
422 $thumb = $this->
httpGet( $foreignUrl,
'default', [], $mtime );
424 wfDebug( __METHOD__ .
" Could not download thumb" );
429 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
431 $params = [
'dst' => $localFilename,
'content' => $thumb ];
433 wfDebug( __METHOD__ .
" could not write to thumb path '$localFilename'" );
437 $knownThumbUrls[$sizekey] = $localUrl;
440 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
442 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
443 wfDebug( __METHOD__ .
" got local thumb $localUrl, saving to cache" );
461 return parent::getZoneUrl( $zone, $ext );
471 $supported = [
'public',
'thumb' ];
472 if ( in_array( $zone, $supported ) ) {
473 return parent::getZonePath( $zone );
484 return ( $this->apiThumbCacheExpiry > 0 );
493 $classVersion = self::VERSION;
495 $extra = $this->userAgent !==
null ?
' ' . $this->userAgent :
'';
496 return "$mediaWikiVersion ($contactUrl) ForeignAPIRepo/$classVersion" . $extra;
506 $info = parent::getInfo();
507 $info[
'apiurl'] = $this->mApiBase;
512 'meta' =>
'siteinfo',
513 'siprop' =>
'general',
519 $siteInfo = FormatJson::decode( $data,
true );
520 $general = $siteInfo[
'query'][
'general'];
522 $info[
'articlepath'] = $general[
'articlepath'];
523 $info[
'server'] = $general[
'server'];
524 if ( !isset( $info[
'favicon'] ) && isset( $general[
'favicon'] ) ) {
525 $info[
'favicon'] = $general[
'favicon'];
540 $url, $timeout =
'default', $options = [], &$mtime =
false
545 $options[
'timeout'] = $timeout;
547 wfDebug(
"ForeignAPIRepo: HTTP GET: $url" );
551 $options[
'method'] =
"GET";
553 if ( !isset( $options[
'timeout'] ) ) {
554 $options[
'timeout'] =
'default';
559 $req = $requestFactory->create(
$url, $options, __METHOD__ );
560 $req->setHeader(
'Referer', $urlUtils->getCanonicalServer() );
561 $status = $req->execute();
563 if ( $status->isOK() ) {
564 $lmod = $req->getResponseHeader(
'Last-Modified' );
565 $mtime = $lmod ? (int)
wfTimestamp( TS::UNIX, $lmod ) :
false;
567 return $req->getContent();
569 $logger = LoggerFactory::getInstance(
'http' );
571 $status->getWikiText(
false,
false,
'en' ),
572 [
'caller' => __METHOD__ ]
584 return implode(
'|', self::IMAGE_INFO_PROPS );
595 if ( $this->mApiBase ) {
601 return $this->wanCache->getWithSetCallback(
605 $this->wanCache->makeGlobalKey(
"filerepo-$attribute", sha1(
$url ) ),
607 function ( $curValue, &$ttl ) use (
$url ) {
608 $html = $this->
httpGet(
$url,
'default', [], $mtime );
611 if ( $html !==
false ) {
612 $ttl = $mtime ? $this->wanCache->adaptiveTTL( $mtime, $ttl ) : $ttl;
614 $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
620 [
'pcGroup' =>
'http-get:3',
'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
629 throw new RuntimeException(
'enumFiles is not supported by ' . static::class );
633 throw new LogicException( static::class .
': write operations are not supported.' );
638class_alias( ForeignAPIRepo::class,
'ForeignAPIRepo' );
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.
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
A class containing constants representing the names of configuration variables.
const LocalFileRepo
Name constant for the LocalFileRepo setting, for use with Config::get()
const LanguageCode
Name constant for the LanguageCode setting, for use with Config::get()
Interface for objects (potentially) representing an editable wiki page.