MediaWiki master
ForeignAPIRepo.php
Go to the documentation of this file.
1<?php
7namespace MediaWiki\FileRepo;
8
9use LogicException;
20use RuntimeException;
23use Wikimedia\Timestamp\ConvertibleTimestamp;
24use Wikimedia\Timestamp\TimestampFormat as TS;
25
43 /* This version string is used in the user agent for requests and will help
44 * server maintainers in identify ForeignAPI usage.
45 * Update the version every time you make breaking or significant changes. */
46 private const VERSION = "2.1";
47
51 private const IMAGE_INFO_PROPS = [
52 'url',
53 'timestamp',
54 ];
55
57 protected $fileFactory = [ ForeignAPIFile::class, 'newFromTitle' ];
59 protected $apiThumbCacheExpiry = 24 * 3600; // 1 day
60
62 protected $fileCacheExpiry = 30 * 24 * 3600; // 1 month
63
75 protected $apiMetadataExpiry = 4 * 3600; // 4 hours
76
78 protected $mFileExists = [];
79
81 private $mApiBase;
82
86 public function __construct( $info ) {
87 $localFileRepo = MediaWikiServices::getInstance()->getMainConfig()
89 parent::__construct( $info );
90
91 // https://commons.wikimedia.org/w/api.php
92 $this->mApiBase = $info['apibase'] ?? null;
93
94 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
95 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
96 }
97 if ( isset( $info['fileCacheExpiry'] ) ) {
98 $this->fileCacheExpiry = $info['fileCacheExpiry'];
99 }
100 if ( isset( $info['apiMetadataExpiry'] ) ) {
101 $this->apiMetadataExpiry = $info['apiMetadataExpiry'];
102 }
103 if ( !$this->scriptDirUrl ) {
104 // hack for description fetches
105 $this->scriptDirUrl = dirname( $this->mApiBase );
106 }
107 // If we can cache thumbs we can guess sensible defaults for these
108 if ( $this->canCacheThumbs() && !$this->url ) {
109 $this->url = $localFileRepo['url'];
110 }
111 if ( $this->canCacheThumbs() && !$this->thumbUrl ) {
112 $this->thumbUrl = $this->url . '/thumb';
113 }
114 }
115
124 public function newFile( $title, $time = false ) {
125 if ( $time ) {
126 return false;
127 }
128
129 return parent::newFile( $title, $time );
130 }
131
136 public function fileExistsBatch( array $files ) {
137 $results = [];
138 foreach ( $files as $k => $f ) {
139 if ( isset( $this->mFileExists[$f] ) ) {
140 $results[$k] = $this->mFileExists[$f];
141 unset( $files[$k] );
142 } elseif ( self::isVirtualUrl( $f ) ) {
143 # @todo FIXME: We need to be able to handle virtual
144 # URLs better, at least when we know they refer to the
145 # same repo.
146 $results[$k] = false;
147 unset( $files[$k] );
148 } elseif ( FileBackend::isStoragePath( $f ) ) {
149 $results[$k] = false;
150 unset( $files[$k] );
151 wfWarn( "Got mwstore:// path '$f'." );
152 }
153 }
154
155 $data = $this->fetchImageQuery( [
156 'titles' => implode( '|', $files ),
157 'prop' => 'imageinfo' ]
158 );
159
160 if ( isset( $data['query']['pages'] ) ) {
161 # First, get results from the query. Note we only care whether the image exists,
162 # not whether it has a description page.
163 foreach ( $data['query']['pages'] as $p ) {
164 $this->mFileExists[$p['title']] = ( $p['imagerepository'] !== '' );
165 }
166 # Second, copy the results to any redirects that were queried
167 if ( isset( $data['query']['redirects'] ) ) {
168 foreach ( $data['query']['redirects'] as $r ) {
169 $this->mFileExists[$r['from']] = $this->mFileExists[$r['to']];
170 }
171 }
172 # Third, copy the results to any non-normalized titles that were queried
173 if ( isset( $data['query']['normalized'] ) ) {
174 foreach ( $data['query']['normalized'] as $n ) {
175 $this->mFileExists[$n['from']] = $this->mFileExists[$n['to']];
176 }
177 }
178 # Finally, copy the results to the output
179 foreach ( $files as $key => $file ) {
180 $results[$key] = $this->mFileExists[$file];
181 }
182 }
183
184 return $results;
185 }
186
191 public function getFileProps( $virtualUrl ) {
192 return [];
193 }
194
201 public function fetchImageQuery( $query ) {
202 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
204
205 $query = array_merge( $query,
206 [
207 'format' => 'json',
208 'action' => 'query',
209 'redirects' => 'true'
210 ] );
211
212 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
213 $query['uselang'] = $languageCode;
214 }
215
216 $data = $this->httpGetCached( 'Metadata', $query, $this->apiMetadataExpiry );
217
218 if ( $data ) {
219 return FormatJson::decode( $data, true );
220 } else {
221 return null;
222 }
223 }
224
229 public function getImageInfo( $data ) {
230 if ( $data && isset( $data['query']['pages'] ) ) {
231 foreach ( $data['query']['pages'] as $info ) {
232 if ( isset( $info['imageinfo'][0] ) ) {
233 $return = $info['imageinfo'][0];
234 if ( isset( $info['pageid'] ) ) {
235 $return['pageid'] = $info['pageid'];
236 }
237 return $return;
238 }
239 }
240 }
241
242 return false;
243 }
244
249 public function findBySha1( $hash ) {
250 $results = $this->fetchImageQuery( [
251 'aisha1base36' => $hash,
252 'aiprop' => ForeignAPIFile::getProps(),
253 'list' => 'allimages',
254 ] );
255 $ret = [];
256 if ( isset( $results['query']['allimages'] ) ) {
257 foreach ( $results['query']['allimages'] as $img ) {
258 // 1.14 was broken, doesn't return name attribute
259 if ( !isset( $img['name'] ) ) {
260 continue;
261 }
262 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
263 }
264 }
265
266 return $ret;
267 }
268
278 private function getThumbUrl(
279 $name, $width = -1, $height = -1, &$result = null, $otherParams = ''
280 ) {
281 $data = $this->fetchImageQuery( [
282 'titles' => 'File:' . $name,
283 'iiprop' => self::getIIProps(),
284 'iiurlwidth' => $width,
285 'iiurlheight' => $height,
286 'iiurlparam' => $otherParams,
287 'prop' => 'imageinfo' ] );
288 $info = $this->getImageInfo( $data );
289
290 if ( $data && $info && isset( $info['thumburl'] ) ) {
291 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] );
292 $result = $info;
293
294 return $info['thumburl'];
295 } else {
296 return false;
297 }
298 }
299
309 public function getThumbError(
310 $name, $width = -1, $height = -1, $otherParams = '', $lang = null
311 ) {
312 $data = $this->fetchImageQuery( [
313 'titles' => 'File:' . $name,
314 'iiprop' => self::getIIProps(),
315 'iiurlwidth' => $width,
316 'iiurlheight' => $height,
317 'iiurlparam' => $otherParams,
318 'prop' => 'imageinfo',
319 'uselang' => $lang,
320 ] );
321 $info = $this->getImageInfo( $data );
322
323 if ( $data && $info && isset( $info['thumberror'] ) ) {
324 wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] );
325
326 return new MediaTransformError(
327 'thumbnail_error_remote',
328 $width,
329 $height,
330 $this->getDisplayName(),
331 $info['thumberror'] // already parsed message from foreign repo
332 );
333 } else {
334 return false;
335 }
336 }
337
351 public function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
352 // We can't check the local cache using FileRepo functions because
353 // we override fileExistsBatch(). We have to use the FileBackend directly.
354 $backend = $this->getBackend(); // convenience
355
356 if ( !$this->canCacheThumbs() ) {
357 $result = null; // can't pass "null" by reference, but it's ok as default value
358
359 return $this->getThumbUrl( $name, $width, $height, $result, $params );
360 }
361
362 $key = $this->getLocalCacheKey( 'file-thumb-url', sha1( $name ) );
363 $sizekey = "$width:$height:$params";
364
365 /* Get the array of urls that we already know */
366 $knownThumbUrls = $this->wanCache->get( $key );
367 if ( !$knownThumbUrls ) {
368 /* No knownThumbUrls for this file */
369 $knownThumbUrls = [];
370 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
371 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
372 "{$knownThumbUrls[$sizekey]}" );
373
374 return $knownThumbUrls[$sizekey];
375 }
376
377 $metadata = null;
378 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
379
380 if ( !$foreignUrl ) {
381 wfDebug( __METHOD__ . " Could not find thumburl" );
382
383 return false;
384 }
385
386 // We need the same filename as the remote one :)
387 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
388 if ( !$this->validateFilename( $fileName ) ) {
389 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe" );
390
391 return false;
392 }
393 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
394 $localFilename = $localPath . "/" . $fileName;
395 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) .
396 rawurlencode( $name ) . "/" . rawurlencode( $fileName );
397
398 if ( $backend->fileExists( [ 'src' => $localFilename ] )
399 && isset( $metadata['timestamp'] )
400 ) {
401 wfDebug( __METHOD__ . " Thumbnail was already downloaded before" );
402 $modified = (int)wfTimestamp( TS::UNIX, $backend->getFileTimestamp( [ 'src' => $localFilename ] ) );
403 $remoteModified = (int)wfTimestamp( TS::UNIX, $metadata['timestamp'] );
404 $current = (int)ConvertibleTimestamp::now( TS::UNIX );
405 $diff = abs( $modified - $current );
406 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
407 /* Use our current and already downloaded thumbnail */
408 $knownThumbUrls[$sizekey] = $localUrl;
409 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
410
411 return $localUrl;
412 }
413 /* There is a new Commons file, or existing thumbnail older than a month */
414 }
415
416 $thumb = self::httpGet( $foreignUrl, 'default', [], $mtime );
417 if ( !$thumb ) {
418 wfDebug( __METHOD__ . " Could not download thumb" );
419
420 return false;
421 }
422
423 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
424 $backend->prepare( [ 'dir' => dirname( $localFilename ) ] );
425 $params = [ 'dst' => $localFilename, 'content' => $thumb ];
426 if ( !$backend->quickCreate( $params )->isOK() ) {
427 wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'" );
428
429 return $foreignUrl;
430 }
431 $knownThumbUrls[$sizekey] = $localUrl;
432
433 $ttl = $mtime
434 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
436 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
437 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache" );
438
439 return $localUrl;
440 }
441
448 public function getZoneUrl( $zone, $ext = null ) {
449 switch ( $zone ) {
450 case 'public':
451 return $this->url;
452 case 'thumb':
453 return $this->thumbUrl;
454 default:
455 return parent::getZoneUrl( $zone, $ext );
456 }
457 }
458
464 public function getZonePath( $zone ) {
465 $supported = [ 'public', 'thumb' ];
466 if ( in_array( $zone, $supported ) ) {
467 return parent::getZonePath( $zone );
468 }
469
470 return false;
471 }
472
477 public function canCacheThumbs() {
478 return ( $this->apiThumbCacheExpiry > 0 );
479 }
480
485 public static function getUserAgent() {
486 $mediaWikiVersion = MediaWikiServices::getInstance()->getHttpRequestFactory()->getUserAgent();
487 $classVersion = self::VERSION;
488 $contactUrl = MediaWikiServices::getInstance()->getUrlUtils()->getCanonicalServer();
489 return "$mediaWikiVersion ($contactUrl) ForeignAPIRepo/$classVersion";
490 }
491
498 public function getInfo() {
499 $info = parent::getInfo();
500 $info['apiurl'] = $this->mApiBase;
501
502 $query = [
503 'format' => 'json',
504 'action' => 'query',
505 'meta' => 'siteinfo',
506 'siprop' => 'general',
507 ];
508
509 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
510
511 if ( $data ) {
512 $siteInfo = FormatJson::decode( $data, true );
513 $general = $siteInfo['query']['general'];
514
515 $info['articlepath'] = $general['articlepath'];
516 $info['server'] = $general['server'];
517 if ( !isset( $info['favicon'] ) && isset( $general['favicon'] ) ) {
518 $info['favicon'] = $general['favicon'];
519 }
520 }
521
522 return $info;
523 }
524
532 public static function httpGet(
533 $url, $timeout = 'default', $options = [], &$mtime = false
534 ) {
535 $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
536 $requestFactory = MediaWikiServices::getInstance()->getHttpRequestFactory();
537
538 $options['timeout'] = $timeout;
539 $url = $urlUtils->expand( $url, PROTO_HTTP );
540 wfDebug( "ForeignAPIRepo: HTTP GET: $url" );
541 if ( !$url ) {
542 return false;
543 }
544 $options['method'] = "GET";
545
546 if ( !isset( $options['timeout'] ) ) {
547 $options['timeout'] = 'default';
548 }
549
550 $options['userAgent'] = self::getUserAgent();
551
552 $req = $requestFactory->create( $url, $options, __METHOD__ );
553 $req->setHeader( 'Referer', $urlUtils->getCanonicalServer() );
554 $status = $req->execute();
555
556 if ( $status->isOK() ) {
557 $lmod = $req->getResponseHeader( 'Last-Modified' );
558 $mtime = $lmod ? (int)wfTimestamp( TS::UNIX, $lmod ) : false;
559
560 return $req->getContent();
561 } else {
562 $logger = LoggerFactory::getInstance( 'http' );
563 $logger->warning(
564 $status->getWikiText( false, false, 'en' ),
565 [ 'caller' => 'ForeignAPIRepo::httpGet' ]
566 );
567
568 return false;
569 }
570 }
571
576 protected static function getIIProps() {
577 return implode( '|', self::IMAGE_INFO_PROPS );
578 }
579
587 public function httpGetCached( $attribute, $query, $cacheTTL = 3600 ) {
588 if ( $this->mApiBase ) {
589 $url = wfAppendQuery( $this->mApiBase, $query );
590 } else {
591 $url = $this->makeUrl( $query, 'api' );
592 }
593
594 return $this->wanCache->getWithSetCallback(
595 // Allow reusing the same cached data across wikis (T285271).
596 // This does not use getSharedCacheKey() because caching here
597 // is transparent to client wikis (which are not expected to issue purges).
598 $this->wanCache->makeGlobalKey( "filerepo-$attribute", sha1( $url ) ),
599 $cacheTTL,
600 function ( $curValue, &$ttl ) use ( $url ) {
601 $html = self::httpGet( $url, 'default', [], $mtime );
602 // FIXME: This should use the mtime from the api response body
603 // not the mtime from the last-modified header which usually is not set.
604 if ( $html !== false ) {
605 $ttl = $mtime ? $this->wanCache->adaptiveTTL( $mtime, $ttl ) : $ttl;
606 } else {
607 $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
608 $html = null; // caches negatives
609 }
610
611 return $html;
612 },
613 [ 'pcGroup' => 'http-get:3', 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
614 );
615 }
616
621 public function enumFiles( $callback ): never {
622 throw new RuntimeException( 'enumFiles is not supported by ' . static::class );
623 }
624
625 protected function assertWritableRepo(): never {
626 throw new LogicException( static::class . ': write operations are not supported.' );
627 }
628}
629
631class_alias( ForeignAPIRepo::class, 'ForeignAPIRepo' );
const NS_FILE
Definition Defines.php:57
const PROTO_HTTP
Definition Defines.php:217
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...
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
Base class for file repositories.
Definition FileRepo.php:52
string false $url
Public zone URL.
Definition FileRepo.php:116
getLocalCacheKey( $kClassSuffix,... $components)
Get a site-local, repository-qualified, WAN cache key.
getBackend()
Get the file backend instance.
Definition FileRepo.php:254
string false $thumbUrl
The base thumbnail URL.
Definition FileRepo.php:119
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:748
getDisplayName()
Get the human-readable name of the repo.
makeUrl( $query='', $entry='index')
Make an url to this repo.
Definition FileRepo.php:809
validateFilename( $filename)
Determine if a relative path is valid, i.e.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:79
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.
getThumbUrlFromCache( $name, $width, $height, $params="")
Return the imageurl from cache if possible.
int $apiMetadataExpiry
API metadata cache time.
static getUserAgent()
The user agent the ForeignAPIRepo will use.
int $fileCacheExpiry
Redownload thumbnail files after this expiry.
assertWritableRepo()
Throw an exception if this repo is read-only by design.
newFile( $title, $time=false)
Per docs in FileRepo, this needs to return false if we don't support versioned files.
fetchImageQuery( $query)
Make an API query in the foreign repo, caching results.
httpGetCached( $attribute, $query, $cacheTTL=3600)
HTTP GET request to a mediawiki API (with caching)
getZonePath( $zone)
Get the local directory corresponding to one of the basic zones.
canCacheThumbs()
Are we locally caching the thumbnails?
getInfo()
Get information about the repo - overrides/extends the parent class's information.
getThumbError( $name, $width=-1, $height=-1, $otherParams='', $lang=null)
static httpGet( $url, $timeout='default', $options=[], &$mtime=false)
int $apiThumbCacheExpiry
Check back with Commons after this expiry.
JSON formatter wrapper class.
Create PSR-3 logger objects.
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()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Basic media transform error class.
Represents a title within MediaWiki.
Definition Title.php:69
Base class for all file backend classes (including multi-write backends).
prepare(array $params)
Prepare a storage directory for usage.
getFileTimestamp(array $params)
Get the last-modified timestamp of the file at a storage path.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
quickCreate(array $params, array $opts=[])
Performs a single quick create operation.
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Multi-datacenter aware caching interface.
A foreign repo that implement support for API queries.
Represents the target of a wiki link.
Interface for objects (potentially) representing an editable wiki page.