MediaWiki master
ForeignAPIRepo.php
Go to the documentation of this file.
1<?php
30
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";
52
56 private const IMAGE_INFO_PROPS = [
57 'url',
58 'timestamp',
59 ];
60
62 protected $fileFactory = [ ForeignAPIFile::class, 'newFromTitle' ];
64 protected $apiThumbCacheExpiry = 24 * 3600; // 1 day
65
67 protected $fileCacheExpiry = 30 * 24 * 3600; // 1 month
68
80 protected $apiMetadataExpiry = 4 * 3600; // 4 hours
81
83 protected $mFileExists = [];
84
86 private $mApiBase;
87
91 public function __construct( $info ) {
92 $localFileRepo = MediaWikiServices::getInstance()->getMainConfig()
93 ->get( MainConfigNames::LocalFileRepo );
94 parent::__construct( $info );
95
96 // https://commons.wikimedia.org/w/api.php
97 $this->mApiBase = $info['apibase'] ?? null;
98
99 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
100 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
101 }
102 if ( isset( $info['fileCacheExpiry'] ) ) {
103 $this->fileCacheExpiry = $info['fileCacheExpiry'];
104 }
105 if ( isset( $info['apiMetadataExpiry'] ) ) {
106 $this->apiMetadataExpiry = $info['apiMetadataExpiry'];
107 }
108 if ( !$this->scriptDirUrl ) {
109 // hack for description fetches
110 $this->scriptDirUrl = dirname( $this->mApiBase );
111 }
112 // If we can cache thumbs we can guess sensible defaults for these
113 if ( $this->canCacheThumbs() && !$this->url ) {
114 $this->url = $localFileRepo['url'];
115 }
116 if ( $this->canCacheThumbs() && !$this->thumbUrl ) {
117 $this->thumbUrl = $this->url . '/thumb';
118 }
119 }
120
129 public function newFile( $title, $time = false ) {
130 if ( $time ) {
131 return false;
132 }
133
134 return parent::newFile( $title, $time );
135 }
136
141 public function fileExistsBatch( array $files ) {
142 $results = [];
143 foreach ( $files as $k => $f ) {
144 if ( isset( $this->mFileExists[$f] ) ) {
145 $results[$k] = $this->mFileExists[$f];
146 unset( $files[$k] );
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
150 # same repo.
151 $results[$k] = false;
152 unset( $files[$k] );
153 } elseif ( FileBackend::isStoragePath( $f ) ) {
154 $results[$k] = false;
155 unset( $files[$k] );
156 wfWarn( "Got mwstore:// path '$f'." );
157 }
158 }
159
160 $data = $this->fetchImageQuery( [
161 'titles' => implode( '|', $files ),
162 'prop' => 'imageinfo' ]
163 );
164
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'] !== '' );
170 }
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']];
175 }
176 }
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']];
181 }
182 }
183 # Finally, copy the results to the output
184 foreach ( $files as $key => $file ) {
185 $results[$key] = $this->mFileExists[$file];
186 }
187 }
188
189 return $results;
190 }
191
196 public function getFileProps( $virtualUrl ) {
197 return [];
198 }
199
206 public function fetchImageQuery( $query ) {
207 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
208 ->get( MainConfigNames::LanguageCode );
209
210 $query = array_merge( $query,
211 [
212 'format' => 'json',
213 'action' => 'query',
214 'redirects' => 'true'
215 ] );
216
217 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
218 $query['uselang'] = $languageCode;
219 }
220
221 $data = $this->httpGetCached( 'Metadata', $query, $this->apiMetadataExpiry );
222
223 if ( $data ) {
224 return FormatJson::decode( $data, true );
225 } else {
226 return null;
227 }
228 }
229
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'];
241 }
242 return $return;
243 }
244 }
245 }
246
247 return false;
248 }
249
254 public function findBySha1( $hash ) {
255 $results = $this->fetchImageQuery( [
256 'aisha1base36' => $hash,
257 'aiprop' => ForeignAPIFile::getProps(),
258 'list' => 'allimages',
259 ] );
260 $ret = [];
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'] ) ) {
265 continue;
266 }
267 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
268 }
269 }
270
271 return $ret;
272 }
273
283 private function getThumbUrl(
284 $name, $width = -1, $height = -1, &$result = null, $otherParams = ''
285 ) {
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 );
294
295 if ( $data && $info && isset( $info['thumburl'] ) ) {
296 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] );
297 $result = $info;
298
299 return $info['thumburl'];
300 } else {
301 return false;
302 }
303 }
304
314 public function getThumbError(
315 $name, $width = -1, $height = -1, $otherParams = '', $lang = null
316 ) {
317 $data = $this->fetchImageQuery( [
318 'titles' => 'File:' . $name,
319 'iiprop' => self::getIIProps(),
320 'iiurlwidth' => $width,
321 'iiurlheight' => $height,
322 'iiurlparam' => $otherParams,
323 'prop' => 'imageinfo',
324 'uselang' => $lang,
325 ] );
326 $info = $this->getImageInfo( $data );
327
328 if ( $data && $info && isset( $info['thumberror'] ) ) {
329 wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] );
330
331 return new MediaTransformError(
332 'thumbnail_error_remote',
333 $width,
334 $height,
335 $this->getDisplayName(),
336 $info['thumberror'] // already parsed message from foreign repo
337 );
338 } else {
339 return false;
340 }
341 }
342
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
360
361 if ( !$this->canCacheThumbs() ) {
362 $result = null; // can't pass "null" by reference, but it's ok as default value
363
364 return $this->getThumbUrl( $name, $width, $height, $result, $params );
365 }
366
367 $key = $this->getLocalCacheKey( 'file-thumb-url', sha1( $name ) );
368 $sizekey = "$width:$height:$params";
369
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]}" );
378
379 return $knownThumbUrls[$sizekey];
380 }
381
382 $metadata = null;
383 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
384
385 if ( !$foreignUrl ) {
386 wfDebug( __METHOD__ . " Could not find thumburl" );
387
388 return false;
389 }
390
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" );
395
396 return false;
397 }
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 );
402
403 if ( $backend->fileExists( [ 'src' => $localFilename ] )
404 && isset( $metadata['timestamp'] )
405 ) {
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 );
415
416 return $localUrl;
417 }
418 /* There is a new Commons file, or existing thumbnail older than a month */
419 }
420
421 $thumb = self::httpGet( $foreignUrl, 'default', [], $mtime );
422 if ( !$thumb ) {
423 wfDebug( __METHOD__ . " Could not download thumb" );
424
425 return false;
426 }
427
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'" );
433
434 return $foreignUrl;
435 }
436 $knownThumbUrls[$sizekey] = $localUrl;
437
438 $ttl = $mtime
439 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
441 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
442 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache" );
443
444 return $localUrl;
445 }
446
453 public function getZoneUrl( $zone, $ext = null ) {
454 switch ( $zone ) {
455 case 'public':
456 return $this->url;
457 case 'thumb':
458 return $this->thumbUrl;
459 default:
460 return parent::getZoneUrl( $zone, $ext );
461 }
462 }
463
469 public function getZonePath( $zone ) {
470 $supported = [ 'public', 'thumb' ];
471 if ( in_array( $zone, $supported ) ) {
472 return parent::getZonePath( $zone );
473 }
474
475 return false;
476 }
477
482 public function canCacheThumbs() {
483 return ( $this->apiThumbCacheExpiry > 0 );
484 }
485
490 public static function getUserAgent() {
491 return MediaWikiServices::getInstance()->getHttpRequestFactory()->getUserAgent() .
492 " ForeignAPIRepo/" . self::VERSION;
493 }
494
501 public function getInfo() {
502 $info = parent::getInfo();
503 $info['apiurl'] = $this->mApiBase;
504
505 $query = [
506 'format' => 'json',
507 'action' => 'query',
508 'meta' => 'siteinfo',
509 'siprop' => 'general',
510 ];
511
512 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
513
514 if ( $data ) {
515 $siteInfo = FormatJson::decode( $data, true );
516 $general = $siteInfo['query']['general'];
517
518 $info['articlepath'] = $general['articlepath'];
519 $info['server'] = $general['server'];
520 if ( !isset( $info['favicon'] ) && isset( $general['favicon'] ) ) {
521 $info['favicon'] = $general['favicon'];
522 }
523 }
524
525 return $info;
526 }
527
535 public static function httpGet(
536 $url, $timeout = 'default', $options = [], &$mtime = false
537 ) {
538 $options['timeout'] = $timeout;
539 $url = MediaWikiServices::getInstance()->getUrlUtils()
540 ->expand( $url, PROTO_HTTP );
541 wfDebug( "ForeignAPIRepo: HTTP GET: $url" );
542 if ( !$url ) {
543 return false;
544 }
545 $options['method'] = "GET";
546
547 if ( !isset( $options['timeout'] ) ) {
548 $options['timeout'] = 'default';
549 }
550
551 $options['userAgent'] = self::getUserAgent();
552
553 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()
554 ->create( $url, $options, __METHOD__ );
555 $status = $req->execute();
556
557 if ( $status->isOK() ) {
558 $lmod = $req->getResponseHeader( 'Last-Modified' );
559 $mtime = $lmod ? (int)wfTimestamp( TS_UNIX, $lmod ) : false;
560
561 return $req->getContent();
562 } else {
563 $logger = LoggerFactory::getInstance( 'http' );
564 $logger->warning(
565 $status->getWikiText( false, false, 'en' ),
566 [ 'caller' => 'ForeignAPIRepo::httpGet' ]
567 );
568
569 return false;
570 }
571 }
572
577 protected static function getIIProps() {
578 return implode( '|', self::IMAGE_INFO_PROPS );
579 }
580
588 public function httpGetCached( $attribute, $query, $cacheTTL = 3600 ) {
589 if ( $this->mApiBase ) {
590 $url = wfAppendQuery( $this->mApiBase, $query );
591 } else {
592 $url = $this->makeUrl( $query, 'api' );
593 }
594
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 ) ),
600 $cacheTTL,
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;
607 } else {
608 $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
609 $html = null; // caches negatives
610 }
611
612 return $html;
613 },
614 [ 'pcGroup' => 'http-get:3', 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
615 );
616 }
617
622 public function enumFiles( $callback ) {
623 throw new RuntimeException( 'enumFiles is not supported by ' . static::class );
624 }
625
629 protected function assertWritableRepo() {
630 throw new LogicException( static::class . ': write operations are not supported.' );
631 }
632}
const NS_FILE
Definition Defines.php:71
const PROTO_HTTP
Definition Defines.php:210
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.
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.
array $params
The job parameters.
Base class for file repositories.
Definition FileRepo.php:57
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.
Definition FileRepo.php:814
FileBackend $backend
Definition FileRepo.php:80
string false $url
Public zone URL.
Definition FileRepo.php:121
validateFilename( $filename)
Determine if a relative path is valid, i.e.
string $name
Definition FileRepo.php:171
string false $thumbUrl
The base thumbnail URL.
Definition FileRepo.php:124
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:753
getBackend()
Get the file backend instance.
Definition FileRepo.php:259
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.
int $apiMetadataExpiry
API metadata cache time.
static httpGet( $url, $timeout='default', $options=[], &$mtime=false)
enumFiles( $callback)
callable $fileFactory
getInfo()
Get information about the repo - overrides/extends the parent class's information.
static getUserAgent()
The user agent the ForeignAPIRepo will use.
fetchImageQuery( $query)
Make an API query in the foreign repo, caching results.
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)
Basic media transform error class.
JSON formatter wrapper class.
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Represents a title within MediaWiki.
Definition Title.php:78
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.
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.