MediaWiki master
ForeignAPIRepo.php
Go to the documentation of this file.
1<?php
29
47 /* This version string is used in the user agent for requests and will help
48 * server maintainers in identify ForeignAPI usage.
49 * Update the version every time you make breaking or significant changes. */
50 private const VERSION = "2.1";
51
55 private const IMAGE_INFO_PROPS = [
56 'url',
57 'timestamp',
58 ];
59
61 protected $fileFactory = [ ForeignAPIFile::class, 'newFromTitle' ];
63 protected $apiThumbCacheExpiry = 24 * 3600; // 1 day
64
66 protected $fileCacheExpiry = 30 * 24 * 3600; // 1 month
67
79 protected $apiMetadataExpiry = 4 * 3600; // 4 hours
80
82 protected $mFileExists = [];
83
85 private $mApiBase;
86
90 public function __construct( $info ) {
91 $localFileRepo = MediaWikiServices::getInstance()->getMainConfig()
92 ->get( MainConfigNames::LocalFileRepo );
93 parent::__construct( $info );
94
95 // https://commons.wikimedia.org/w/api.php
96 $this->mApiBase = $info['apibase'] ?? null;
97
98 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
99 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
100 }
101 if ( isset( $info['fileCacheExpiry'] ) ) {
102 $this->fileCacheExpiry = $info['fileCacheExpiry'];
103 }
104 if ( isset( $info['apiMetadataExpiry'] ) ) {
105 $this->apiMetadataExpiry = $info['apiMetadataExpiry'];
106 }
107 if ( !$this->scriptDirUrl ) {
108 // hack for description fetches
109 $this->scriptDirUrl = dirname( $this->mApiBase );
110 }
111 // If we can cache thumbs we can guess sensible defaults for these
112 if ( $this->canCacheThumbs() && !$this->url ) {
113 $this->url = $localFileRepo['url'];
114 }
115 if ( $this->canCacheThumbs() && !$this->thumbUrl ) {
116 $this->thumbUrl = $this->url . '/thumb';
117 }
118 }
119
128 public function newFile( $title, $time = false ) {
129 if ( $time ) {
130 return false;
131 }
132
133 return parent::newFile( $title, $time );
134 }
135
140 public function fileExistsBatch( array $files ) {
141 $results = [];
142 foreach ( $files as $k => $f ) {
143 if ( isset( $this->mFileExists[$f] ) ) {
144 $results[$k] = $this->mFileExists[$f];
145 unset( $files[$k] );
146 } elseif ( self::isVirtualUrl( $f ) ) {
147 # @todo FIXME: We need to be able to handle virtual
148 # URLs better, at least when we know they refer to the
149 # same repo.
150 $results[$k] = false;
151 unset( $files[$k] );
152 } elseif ( FileBackend::isStoragePath( $f ) ) {
153 $results[$k] = false;
154 unset( $files[$k] );
155 wfWarn( "Got mwstore:// path '$f'." );
156 }
157 }
158
159 $data = $this->fetchImageQuery( [
160 'titles' => implode( '|', $files ),
161 'prop' => 'imageinfo' ]
162 );
163
164 if ( isset( $data['query']['pages'] ) ) {
165 # First, get results from the query. Note we only care whether the image exists,
166 # not whether it has a description page.
167 foreach ( $data['query']['pages'] as $p ) {
168 $this->mFileExists[$p['title']] = ( $p['imagerepository'] !== '' );
169 }
170 # Second, copy the results to any redirects that were queried
171 if ( isset( $data['query']['redirects'] ) ) {
172 foreach ( $data['query']['redirects'] as $r ) {
173 $this->mFileExists[$r['from']] = $this->mFileExists[$r['to']];
174 }
175 }
176 # Third, copy the results to any non-normalized titles that were queried
177 if ( isset( $data['query']['normalized'] ) ) {
178 foreach ( $data['query']['normalized'] as $n ) {
179 $this->mFileExists[$n['from']] = $this->mFileExists[$n['to']];
180 }
181 }
182 # Finally, copy the results to the output
183 foreach ( $files as $key => $file ) {
184 $results[$key] = $this->mFileExists[$file];
185 }
186 }
187
188 return $results;
189 }
190
195 public function getFileProps( $virtualUrl ) {
196 return [];
197 }
198
205 public function fetchImageQuery( $query ) {
206 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
207 ->get( MainConfigNames::LanguageCode );
208
209 $query = array_merge( $query,
210 [
211 'format' => 'json',
212 'action' => 'query',
213 'redirects' => 'true'
214 ] );
215
216 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
217 $query['uselang'] = $languageCode;
218 }
219
220 $data = $this->httpGetCached( 'Metadata', $query, $this->apiMetadataExpiry );
221
222 if ( $data ) {
223 return FormatJson::decode( $data, true );
224 } else {
225 return null;
226 }
227 }
228
233 public function getImageInfo( $data ) {
234 if ( $data && isset( $data['query']['pages'] ) ) {
235 foreach ( $data['query']['pages'] as $info ) {
236 if ( isset( $info['imageinfo'][0] ) ) {
237 $return = $info['imageinfo'][0];
238 if ( isset( $info['pageid'] ) ) {
239 $return['pageid'] = $info['pageid'];
240 }
241 return $return;
242 }
243 }
244 }
245
246 return false;
247 }
248
253 public function findBySha1( $hash ) {
254 $results = $this->fetchImageQuery( [
255 'aisha1base36' => $hash,
256 'aiprop' => ForeignAPIFile::getProps(),
257 'list' => 'allimages',
258 ] );
259 $ret = [];
260 if ( isset( $results['query']['allimages'] ) ) {
261 foreach ( $results['query']['allimages'] as $img ) {
262 // 1.14 was broken, doesn't return name attribute
263 if ( !isset( $img['name'] ) ) {
264 continue;
265 }
266 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
267 }
268 }
269
270 return $ret;
271 }
272
282 private function getThumbUrl(
283 $name, $width = -1, $height = -1, &$result = null, $otherParams = ''
284 ) {
285 $data = $this->fetchImageQuery( [
286 'titles' => 'File:' . $name,
287 'iiprop' => self::getIIProps(),
288 'iiurlwidth' => $width,
289 'iiurlheight' => $height,
290 'iiurlparam' => $otherParams,
291 'prop' => 'imageinfo' ] );
292 $info = $this->getImageInfo( $data );
293
294 if ( $data && $info && isset( $info['thumburl'] ) ) {
295 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] );
296 $result = $info;
297
298 return $info['thumburl'];
299 } else {
300 return false;
301 }
302 }
303
313 public function getThumbError(
314 $name, $width = -1, $height = -1, $otherParams = '', $lang = null
315 ) {
316 $data = $this->fetchImageQuery( [
317 'titles' => 'File:' . $name,
318 'iiprop' => self::getIIProps(),
319 'iiurlwidth' => $width,
320 'iiurlheight' => $height,
321 'iiurlparam' => $otherParams,
322 'prop' => 'imageinfo',
323 'uselang' => $lang,
324 ] );
325 $info = $this->getImageInfo( $data );
326
327 if ( $data && $info && isset( $info['thumberror'] ) ) {
328 wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] );
329
330 return new MediaTransformError(
331 'thumbnail_error_remote',
332 $width,
333 $height,
334 $this->getDisplayName(),
335 $info['thumberror'] // already parsed message from foreign repo
336 );
337 } else {
338 return false;
339 }
340 }
341
355 public function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
356 // We can't check the local cache using FileRepo functions because
357 // we override fileExistsBatch(). We have to use the FileBackend directly.
358 $backend = $this->getBackend(); // convenience
359
360 if ( !$this->canCacheThumbs() ) {
361 $result = null; // can't pass "null" by reference, but it's ok as default value
362
363 return $this->getThumbUrl( $name, $width, $height, $result, $params );
364 }
365
366 $key = $this->getLocalCacheKey( 'file-thumb-url', sha1( $name ) );
367 $sizekey = "$width:$height:$params";
368
369 /* Get the array of urls that we already know */
370 $knownThumbUrls = $this->wanCache->get( $key );
371 if ( !$knownThumbUrls ) {
372 /* No knownThumbUrls for this file */
373 $knownThumbUrls = [];
374 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
375 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
376 "{$knownThumbUrls[$sizekey]}" );
377
378 return $knownThumbUrls[$sizekey];
379 }
380
381 $metadata = null;
382 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
383
384 if ( !$foreignUrl ) {
385 wfDebug( __METHOD__ . " Could not find thumburl" );
386
387 return false;
388 }
389
390 // We need the same filename as the remote one :)
391 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
392 if ( !$this->validateFilename( $fileName ) ) {
393 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe" );
394
395 return false;
396 }
397 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
398 $localFilename = $localPath . "/" . $fileName;
399 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) .
400 rawurlencode( $name ) . "/" . rawurlencode( $fileName );
401
402 if ( $backend->fileExists( [ 'src' => $localFilename ] )
403 && isset( $metadata['timestamp'] )
404 ) {
405 wfDebug( __METHOD__ . " Thumbnail was already downloaded before" );
406 $modified = (int)wfTimestamp( TS_UNIX, $backend->getFileTimestamp( [ 'src' => $localFilename ] ) );
407 $remoteModified = (int)wfTimestamp( TS_UNIX, $metadata['timestamp'] );
408 $current = (int)wfTimestamp( TS_UNIX );
409 $diff = abs( $modified - $current );
410 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
411 /* Use our current and already downloaded thumbnail */
412 $knownThumbUrls[$sizekey] = $localUrl;
413 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
414
415 return $localUrl;
416 }
417 /* There is a new Commons file, or existing thumbnail older than a month */
418 }
419
420 $thumb = self::httpGet( $foreignUrl, 'default', [], $mtime );
421 if ( !$thumb ) {
422 wfDebug( __METHOD__ . " Could not download thumb" );
423
424 return false;
425 }
426
427 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
428 $backend->prepare( [ 'dir' => dirname( $localFilename ) ] );
429 $params = [ 'dst' => $localFilename, 'content' => $thumb ];
430 if ( !$backend->quickCreate( $params )->isOK() ) {
431 wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'" );
432
433 return $foreignUrl;
434 }
435 $knownThumbUrls[$sizekey] = $localUrl;
436
437 $ttl = $mtime
438 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
440 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
441 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache" );
442
443 return $localUrl;
444 }
445
452 public function getZoneUrl( $zone, $ext = null ) {
453 switch ( $zone ) {
454 case 'public':
455 return $this->url;
456 case 'thumb':
457 return $this->thumbUrl;
458 default:
459 return parent::getZoneUrl( $zone, $ext );
460 }
461 }
462
468 public function getZonePath( $zone ) {
469 $supported = [ 'public', 'thumb' ];
470 if ( in_array( $zone, $supported ) ) {
471 return parent::getZonePath( $zone );
472 }
473
474 return false;
475 }
476
481 public function canCacheThumbs() {
482 return ( $this->apiThumbCacheExpiry > 0 );
483 }
484
489 public static function getUserAgent() {
490 return MediaWikiServices::getInstance()->getHttpRequestFactory()->getUserAgent() .
491 " ForeignAPIRepo/" . self::VERSION;
492 }
493
500 public function getInfo() {
501 $info = parent::getInfo();
502 $info['apiurl'] = $this->mApiBase;
503
504 $query = [
505 'format' => 'json',
506 'action' => 'query',
507 'meta' => 'siteinfo',
508 'siprop' => 'general',
509 ];
510
511 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
512
513 if ( $data ) {
514 $siteInfo = FormatJson::decode( $data, true );
515 $general = $siteInfo['query']['general'];
516
517 $info['articlepath'] = $general['articlepath'];
518 $info['server'] = $general['server'];
519 if ( !isset( $info['favicon'] ) && isset( $general['favicon'] ) ) {
520 $info['favicon'] = $general['favicon'];
521 }
522 }
523
524 return $info;
525 }
526
534 public static function httpGet(
535 $url, $timeout = 'default', $options = [], &$mtime = false
536 ) {
537 $options['timeout'] = $timeout;
538 $url = MediaWikiServices::getInstance()->getUrlUtils()
539 ->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 = MediaWikiServices::getInstance()->getHttpRequestFactory()
553 ->create( $url, $options, __METHOD__ );
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 ) {
622 throw new RuntimeException( 'enumFiles is not supported by ' . static::class );
623 }
624
628 protected function assertWritableRepo() {
629 throw new LogicException( static::class . ': write operations are not supported.' );
630 }
631}
const NS_FILE
Definition Defines.php:71
const PROTO_HTTP
Definition Defines.php:204
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:52
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:809
FileBackend $backend
Definition FileRepo.php:75
string false $url
Public zone URL.
Definition FileRepo.php:116
validateFilename( $filename)
Determine if a relative path is valid, i.e.
string $name
Definition FileRepo.php:166
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
getBackend()
Get the file backend instance.
Definition FileRepo.php:254
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.
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.