3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\Json\FormatJson
;
22 use MediaWiki\Linker\LinkTarget
;
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MainConfigNames
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Page\PageIdentity
;
27 use MediaWiki\Title\Title
;
28 use Wikimedia\FileBackend\FileBackend
;
29 use Wikimedia\ObjectCache\WANObjectCache
;
32 * A foreign repository for a remote MediaWiki accessible through api.php requests.
34 * @par Example config:
36 * $wgForeignFileRepos[] = [
37 * 'class' => ForeignAPIRepo::class,
39 * 'apibase' => 'https://en.wikipedia.org/w/api.php',
40 * 'fetchDescription' => true, // Optional
41 * 'descriptionCacheExpiry' => 3600,
47 class ForeignAPIRepo
extends FileRepo
implements IForeignRepoWithMWApi
{
48 /* This version string is used in the user agent for requests and will help
49 * server maintainers in identify ForeignAPI usage.
50 * Update the version every time you make breaking or significant changes. */
51 private const VERSION
= "2.1";
54 * List of iiprop values for the thumbnail fetch queries.
56 private const IMAGE_INFO_PROPS
= [
62 protected $fileFactory = [ ForeignAPIFile
::class, 'newFromTitle' ];
63 /** @var int Check back with Commons after this expiry */
64 protected $apiThumbCacheExpiry = 24 * 3600; // 1 day
66 /** @var int Redownload thumbnail files after this expiry */
67 protected $fileCacheExpiry = 30 * 24 * 3600; // 1 month
70 * @var int API metadata cache time.
73 * This is often the performance bottleneck for ForeignAPIRepo. For
74 * each file used, we must fetch file metadata for it and every high-DPI
75 * variant, in serial, during the parse. This is slow if a page has many
76 * files, with RTT of the handshake often being significant. The metadata
77 * rarely changes, but if a new version of the file was uploaded, it might
78 * be displayed incorrectly until its metadata entry falls out of cache.
80 protected $apiMetadataExpiry = 4 * 3600; // 4 hours
83 protected $mFileExists = [];
89 * @param array|null $info
91 public function __construct( $info ) {
92 $localFileRepo = MediaWikiServices
::getInstance()->getMainConfig()
93 ->get( MainConfigNames
::LocalFileRepo
);
94 parent
::__construct( $info );
96 // https://commons.wikimedia.org/w/api.php
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
) {
109 // hack for description fetches
110 $this->scriptDirUrl
= dirname( $this->mApiBase
);
112 // If we can cache thumbs we can guess sensible defaults for these
113 if ( $this->canCacheThumbs() && !$this->url
) {
114 $this->url
= $localFileRepo['url'];
116 if ( $this->canCacheThumbs() && !$this->thumbUrl
) {
117 $this->thumbUrl
= $this->url
. '/thumb';
122 * Per docs in FileRepo, this needs to return false if we don't support versioned
123 * files. Well, we don't.
125 * @param PageIdentity|LinkTarget|string $title
126 * @param string|false $time
129 public function newFile( $title, $time = false ) {
134 return parent
::newFile( $title, $time );
138 * @param string[] $files
141 public function fileExistsBatch( array $files ) {
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'." );
160 $data = $this->fetchImageQuery( [
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];
193 * @param string $virtualUrl
196 public function getFileProps( $virtualUrl ) {
201 * Make an API query in the foreign repo, caching results
203 * @param array $query
206 public function fetchImageQuery( $query ) {
207 $languageCode = MediaWikiServices
::getInstance()->getMainConfig()
208 ->get( MainConfigNames
::LanguageCode
);
210 $query = array_merge( $query,
214 'redirects' => 'true'
217 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
218 $query['uselang'] = $languageCode;
221 $data = $this->httpGetCached( 'Metadata', $query, $this->apiMetadataExpiry
);
224 return FormatJson
::decode( $data, true );
232 * @return array|false
234 public function getImageInfo( $data ) {
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'];
251 * @param string $hash
252 * @return ForeignAPIFile[]
254 public function findBySha1( $hash ) {
255 $results = $this->fetchImageQuery( [
256 'aisha1base36' => $hash,
257 'aiprop' => ForeignAPIFile
::getProps(),
258 'list' => 'allimages',
261 if ( isset( $results['query']['allimages'] ) ) {
262 foreach ( $results['query']['allimages'] as $img ) {
263 // 1.14 was broken, doesn't return name attribute
264 if ( !isset( $img['name'] ) ) {
267 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
275 * @param string $name
278 * @param array|null &$result Output-only parameter, guaranteed to become an array
279 * @param string $otherParams
281 * @return string|false
283 private function getThumbUrl(
284 $name, $width = -1, $height = -1, &$result = null, $otherParams = ''
286 $data = $this->fetchImageQuery( [
287 'titles' => 'File:' . $name,
288 'iiprop' => self
::getIIProps(),
289 'iiurlwidth' => $width,
290 'iiurlheight' => $height,
291 'iiurlparam' => $otherParams,
292 'prop' => 'imageinfo' ] );
293 $info = $this->getImageInfo( $data );
295 if ( $data && $info && isset( $info['thumburl'] ) ) {
296 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] );
299 return $info['thumburl'];
306 * @param string $name
309 * @param string $otherParams
310 * @param string|null $lang Language code for language of error
311 * @return MediaTransformError|false
314 public function getThumbError(
315 $name, $width = -1, $height = -1, $otherParams = '', $lang = null
317 $data = $this->fetchImageQuery( [
318 'titles' => 'File:' . $name,
319 'iiprop' => self
::getIIProps(),
320 'iiurlwidth' => $width,
321 'iiurlheight' => $height,
322 'iiurlparam' => $otherParams,
323 'prop' => 'imageinfo',
326 $info = $this->getImageInfo( $data );
328 if ( $data && $info && isset( $info['thumberror'] ) ) {
329 wfDebug( __METHOD__
. " got remote thumb error " . $info['thumberror'] );
331 return new MediaTransformError(
332 'thumbnail_error_remote',
335 $this->getDisplayName(),
336 $info['thumberror'] // already parsed message from foreign repo
344 * Return the imageurl from cache if possible
346 * If the url has been requested today, get it from cache
347 * Otherwise retrieve remote thumb url, check for local file.
349 * @param string $name Is a dbkey form of a title
352 * @param string $params Other rendering parameters (page number, etc)
353 * from handler's makeParamString.
354 * @return string|false
356 public function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
357 // We can't check the local cache using FileRepo functions because
358 // we override fileExistsBatch(). We have to use the FileBackend directly.
359 $backend = $this->getBackend(); // convenience
361 if ( !$this->canCacheThumbs() ) {
362 $result = null; // can't pass "null" by reference, but it's ok as default value
364 return $this->getThumbUrl( $name, $width, $height, $result, $params );
367 $key = $this->getLocalCacheKey( 'file-thumb-url', sha1( $name ) );
368 $sizekey = "$width:$height:$params";
370 /* Get the array of urls that we already know */
371 $knownThumbUrls = $this->wanCache
->get( $key );
372 if ( !$knownThumbUrls ) {
373 /* No knownThumbUrls for this file */
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" );
391 // We need the same filename as the remote one :)
392 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
393 if ( !$this->validateFilename( $fileName ) ) {
394 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe" );
398 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
399 $localFilename = $localPath . "/" . $fileName;
400 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) .
401 rawurlencode( $name ) . "/" . rawurlencode( $fileName );
403 if ( $backend->fileExists( [ 'src' => $localFilename ] )
404 && isset( $metadata['timestamp'] )
406 wfDebug( __METHOD__
. " Thumbnail was already downloaded before" );
407 $modified = (int)wfTimestamp( TS_UNIX
, $backend->getFileTimestamp( [ 'src' => $localFilename ] ) );
408 $remoteModified = (int)wfTimestamp( TS_UNIX
, $metadata['timestamp'] );
409 $current = (int)wfTimestamp( TS_UNIX
);
410 $diff = abs( $modified - $current );
411 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
412 /* Use our current and already downloaded thumbnail */
413 $knownThumbUrls[$sizekey] = $localUrl;
414 $this->wanCache
->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
418 /* There is a new Commons file, or existing thumbnail older than a month */
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?
429 $backend->prepare( [ 'dir' => dirname( $localFilename ) ] );
430 $params = [ 'dst' => $localFilename, 'content' => $thumb ];
431 if ( !$backend->quickCreate( $params )->isOK() ) {
432 wfDebug( __METHOD__
. " could not write to thumb path '$localFilename'" );
436 $knownThumbUrls[$sizekey] = $localUrl;
439 ?
$this->wanCache
->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry
)
440 : $this->apiThumbCacheExpiry
;
441 $this->wanCache
->set( $key, $knownThumbUrls, $ttl );
442 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache" );
448 * @see FileRepo::getZoneUrl()
449 * @param string $zone
450 * @param string|null $ext Optional file extension
453 public function getZoneUrl( $zone, $ext = null ) {
458 return $this->thumbUrl
;
460 return parent
::getZoneUrl( $zone, $ext );
465 * Get the local directory corresponding to one of the basic zones
466 * @param string $zone
467 * @return null|string|false
469 public function getZonePath( $zone ) {
470 $supported = [ 'public', 'thumb' ];
471 if ( in_array( $zone, $supported ) ) {
472 return parent
::getZonePath( $zone );
479 * Are we locally caching the thumbnails?
482 public function canCacheThumbs() {
483 return ( $this->apiThumbCacheExpiry
> 0 );
487 * The user agent the ForeignAPIRepo will use.
490 public static function getUserAgent() {
491 return MediaWikiServices
::getInstance()->getHttpRequestFactory()->getUserAgent() .
492 " ForeignAPIRepo/" . self
::VERSION
;
496 * Get information about the repo - overrides/extends the parent
497 * class's information.
501 public function getInfo() {
502 $info = parent
::getInfo();
503 $info['apiurl'] = $this->mApiBase
;
508 'meta' => 'siteinfo',
509 'siprop' => 'general',
512 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
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'];
530 * @param string $timeout
531 * @param array $options
532 * @param int|false &$mtime Resulting Last-Modified UNIX timestamp if received
533 * @return string|false
535 public static function httpGet(
536 $url, $timeout = 'default', $options = [], &$mtime = false
538 $options['timeout'] = $timeout;
539 $url = MediaWikiServices
::getInstance()->getUrlUtils()
540 ->expand( $url, PROTO_HTTP
);
541 wfDebug( "ForeignAPIRepo: HTTP GET: $url" );
545 $options['method'] = "GET";
547 if ( !isset( $options['timeout'] ) ) {
548 $options['timeout'] = 'default';
551 $options['userAgent'] = self
::getUserAgent();
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' ]
577 protected static function getIIProps() {
578 return implode( '|', self
::IMAGE_INFO_PROPS
);
582 * HTTP GET request to a mediawiki API (with caching)
583 * @param string $attribute Used in cache key creation, mostly
584 * @param array $query The query parameters for the API request
585 * @param int $cacheTTL Time to live for the memcached caching
586 * @return string|null
588 public function httpGetCached( $attribute, $query, $cacheTTL = 3600 ) {
589 if ( $this->mApiBase
) {
590 $url = wfAppendQuery( $this->mApiBase
, $query );
592 $url = $this->makeUrl( $query, 'api' );
595 return $this->wanCache
->getWithSetCallback(
596 // Allow reusing the same cached data across wikis (T285271).
597 // This does not use getSharedCacheKey() because caching here
598 // is transparent to client wikis (which are not expected to issue purges).
599 $this->wanCache
->makeGlobalKey( "filerepo-$attribute", sha1( $url ) ),
601 function ( $curValue, &$ttl ) use ( $url ) {
602 $html = self
::httpGet( $url, 'default', [], $mtime );
603 // FIXME: This should use the mtime from the api response body
604 // not the mtime from the last-modified header which usually is not set.
605 if ( $html !== false ) {
606 $ttl = $mtime ?
$this->wanCache
->adaptiveTTL( $mtime, $ttl ) : $ttl;
608 $ttl = $this->wanCache
->adaptiveTTL( $mtime, $ttl );
609 $html = null; // caches negatives
614 [ 'pcGroup' => 'http-get:3', 'pcTTL' => WANObjectCache
::TTL_PROC_LONG
]
619 * @param callable $callback
622 public function enumFiles( $callback ) {
623 throw new RuntimeException( 'enumFiles is not supported by ' . static::class );
629 protected function assertWritableRepo() {
630 throw new LogicException( static::class . ': write operations are not supported.' );