MediaWiki REL1_39
ForeignAPIRepo.php
Go to the documentation of this file.
1<?php
26
44 /* This version string is used in the user agent for requests and will help
45 * server maintainers in identify ForeignAPI usage.
46 * Update the version every time you make breaking or significant changes. */
47 private const VERSION = "2.1";
48
52 private const IMAGE_INFO_PROPS = [
53 'url',
54 'timestamp',
55 ];
56
57 protected $fileFactory = [ ForeignAPIFile::class, 'newFromTitle' ];
59 protected $apiThumbCacheExpiry = 86400; // 1 day (24*3600)
60
62 protected $fileCacheExpiry = 2592000; // 1 month (30*24*3600)
63
75 protected $apiMetadataExpiry = 14400; // 4 hours
76
78 protected $mFileExists = [];
79
81 private $mApiBase;
82
86 public function __construct( $info ) {
87 $localFileRepo = MediaWikiServices::getInstance()->getMainConfig()
88 ->get( MainConfigNames::LocalFileRepo );
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
119 private function getApiUrl() {
120 return $this->mApiBase;
121 }
122
131 public function newFile( $title, $time = false ) {
132 if ( $time ) {
133 return false;
134 }
135
136 return parent::newFile( $title, $time );
137 }
138
143 public function fileExistsBatch( array $files ) {
144 $results = [];
145 foreach ( $files as $k => $f ) {
146 if ( isset( $this->mFileExists[$f] ) ) {
147 $results[$k] = $this->mFileExists[$f];
148 unset( $files[$k] );
149 } elseif ( self::isVirtualUrl( $f ) ) {
150 # @todo FIXME: We need to be able to handle virtual
151 # URLs better, at least when we know they refer to the
152 # same repo.
153 $results[$k] = false;
154 unset( $files[$k] );
155 } elseif ( FileBackend::isStoragePath( $f ) ) {
156 $results[$k] = false;
157 unset( $files[$k] );
158 wfWarn( "Got mwstore:// path '$f'." );
159 }
160 }
161
162 $data = $this->fetchImageQuery( [
163 'titles' => implode( '|', $files ),
164 'prop' => 'imageinfo' ]
165 );
166
167 if ( isset( $data['query']['pages'] ) ) {
168 # First, get results from the query. Note we only care whether the image exists,
169 # not whether it has a description page.
170 foreach ( $data['query']['pages'] as $p ) {
171 $this->mFileExists[$p['title']] = ( $p['imagerepository'] !== '' );
172 }
173 # Second, copy the results to any redirects that were queried
174 if ( isset( $data['query']['redirects'] ) ) {
175 foreach ( $data['query']['redirects'] as $r ) {
176 $this->mFileExists[$r['from']] = $this->mFileExists[$r['to']];
177 }
178 }
179 # Third, copy the results to any non-normalized titles that were queried
180 if ( isset( $data['query']['normalized'] ) ) {
181 foreach ( $data['query']['normalized'] as $n ) {
182 $this->mFileExists[$n['from']] = $this->mFileExists[$n['to']];
183 }
184 }
185 # Finally, copy the results to the output
186 foreach ( $files as $key => $file ) {
187 $results[$key] = $this->mFileExists[$file];
188 }
189 }
190
191 return $results;
192 }
193
198 public function getFileProps( $virtualUrl ) {
199 return [];
200 }
201
208 public function fetchImageQuery( $query ) {
209 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
210 ->get( MainConfigNames::LanguageCode );
211
212 $query = array_merge( $query,
213 [
214 'format' => 'json',
215 'action' => 'query',
216 'redirects' => 'true'
217 ] );
218
219 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
220 $query['uselang'] = $languageCode;
221 }
222
223 $data = $this->httpGetCached( 'Metadata', $query, $this->apiMetadataExpiry );
224
225 if ( $data ) {
226 return FormatJson::decode( $data, true );
227 } else {
228 return null;
229 }
230 }
231
236 public function getImageInfo( $data ) {
237 if ( $data && isset( $data['query']['pages'] ) ) {
238 foreach ( $data['query']['pages'] as $info ) {
239 if ( isset( $info['imageinfo'][0] ) ) {
240 $return = $info['imageinfo'][0];
241 if ( isset( $info['pageid'] ) ) {
242 $return['pageid'] = $info['pageid'];
243 }
244 return $return;
245 }
246 }
247 }
248
249 return false;
250 }
251
256 public function findBySha1( $hash ) {
257 $results = $this->fetchImageQuery( [
258 'aisha1base36' => $hash,
259 'aiprop' => ForeignAPIFile::getProps(),
260 'list' => 'allimages',
261 ] );
262 $ret = [];
263 if ( isset( $results['query']['allimages'] ) ) {
264 foreach ( $results['query']['allimages'] as $img ) {
265 // 1.14 was broken, doesn't return name attribute
266 if ( !isset( $img['name'] ) ) {
267 continue;
268 }
269 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
270 }
271 }
272
273 return $ret;
274 }
275
285 private function getThumbUrl(
286 $name, $width = -1, $height = -1, &$result = null, $otherParams = ''
287 ) {
288 $data = $this->fetchImageQuery( [
289 'titles' => 'File:' . $name,
290 'iiprop' => self::getIIProps(),
291 'iiurlwidth' => $width,
292 'iiurlheight' => $height,
293 'iiurlparam' => $otherParams,
294 'prop' => 'imageinfo' ] );
295 $info = $this->getImageInfo( $data );
296
297 if ( $data && $info && isset( $info['thumburl'] ) ) {
298 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] );
299 $result = $info;
300
301 return $info['thumburl'];
302 } else {
303 return false;
304 }
305 }
306
316 public function getThumbError(
317 $name, $width = -1, $height = -1, $otherParams = '', $lang = null
318 ) {
319 $data = $this->fetchImageQuery( [
320 'titles' => 'File:' . $name,
321 'iiprop' => self::getIIProps(),
322 'iiurlwidth' => $width,
323 'iiurlheight' => $height,
324 'iiurlparam' => $otherParams,
325 'prop' => 'imageinfo',
326 'uselang' => $lang,
327 ] );
328 $info = $this->getImageInfo( $data );
329
330 if ( $data && $info && isset( $info['thumberror'] ) ) {
331 wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] );
332
333 return new MediaTransformError(
334 'thumbnail_error_remote',
335 $width,
336 $height,
337 $this->getDisplayName(),
338 $info['thumberror'] // already parsed message from foreign repo
339 );
340 } else {
341 return false;
342 }
343 }
344
358 public function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
359 // We can't check the local cache using FileRepo functions because
360 // we override fileExistsBatch(). We have to use the FileBackend directly.
361 $backend = $this->getBackend(); // convenience
362
363 if ( !$this->canCacheThumbs() ) {
364 $result = null; // can't pass "null" by reference, but it's ok as default value
365
366 return $this->getThumbUrl( $name, $width, $height, $result, $params );
367 }
368
369 $key = $this->getLocalCacheKey( 'file-thumb-url', sha1( $name ) );
370 $sizekey = "$width:$height:$params";
371
372 /* Get the array of urls that we already know */
373 $knownThumbUrls = $this->wanCache->get( $key );
374 if ( !$knownThumbUrls ) {
375 /* No knownThumbUrls for this file */
376 $knownThumbUrls = [];
377 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
378 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
379 "{$knownThumbUrls[$sizekey]}" );
380
381 return $knownThumbUrls[$sizekey];
382 }
383
384 $metadata = null;
385 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
386
387 if ( !$foreignUrl ) {
388 wfDebug( __METHOD__ . " Could not find thumburl" );
389
390 return false;
391 }
392
393 // We need the same filename as the remote one :)
394 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
395 if ( !$this->validateFilename( $fileName ) ) {
396 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe" );
397
398 return false;
399 }
400 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
401 $localFilename = $localPath . "/" . $fileName;
402 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) .
403 rawurlencode( $name ) . "/" . rawurlencode( $fileName );
404
405 if ( $backend->fileExists( [ 'src' => $localFilename ] )
406 && isset( $metadata['timestamp'] )
407 ) {
408 wfDebug( __METHOD__ . " Thumbnail was already downloaded before" );
409 $modified = (int)wfTimestamp( TS_UNIX, $backend->getFileTimestamp( [ 'src' => $localFilename ] ) );
410 $remoteModified = (int)wfTimestamp( TS_UNIX, $metadata['timestamp'] );
411 $current = (int)wfTimestamp( TS_UNIX );
412 $diff = abs( $modified - $current );
413 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
414 /* Use our current and already downloaded thumbnail */
415 $knownThumbUrls[$sizekey] = $localUrl;
416 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
417
418 return $localUrl;
419 }
420 /* There is a new Commons file, or existing thumbnail older than a month */
421 }
422
423 $thumb = self::httpGet( $foreignUrl, 'default', [], $mtime );
424 if ( !$thumb ) {
425 wfDebug( __METHOD__ . " Could not download thumb" );
426
427 return false;
428 }
429
430 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
431 $backend->prepare( [ 'dir' => dirname( $localFilename ) ] );
432 $params = [ 'dst' => $localFilename, 'content' => $thumb ];
433 if ( !$backend->quickCreate( $params )->isOK() ) {
434 wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'" );
435
436 return $foreignUrl;
437 }
438 $knownThumbUrls[$sizekey] = $localUrl;
439
440 $ttl = $mtime
441 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
443 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
444 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache" );
445
446 return $localUrl;
447 }
448
455 public function getZoneUrl( $zone, $ext = null ) {
456 switch ( $zone ) {
457 case 'public':
458 return $this->url;
459 case 'thumb':
460 return $this->thumbUrl;
461 default:
462 return parent::getZoneUrl( $zone, $ext );
463 }
464 }
465
471 public function getZonePath( $zone ) {
472 $supported = [ 'public', 'thumb' ];
473 if ( in_array( $zone, $supported ) ) {
474 return parent::getZonePath( $zone );
475 }
476
477 return false;
478 }
479
484 public function canCacheThumbs() {
485 return ( $this->apiThumbCacheExpiry > 0 );
486 }
487
492 public static function getUserAgent() {
493 return MediaWikiServices::getInstance()->getHttpRequestFactory()->getUserAgent() .
494 " ForeignAPIRepo/" . self::VERSION;
495 }
496
503 public function getInfo() {
504 $info = parent::getInfo();
505 $info['apiurl'] = $this->getApiUrl();
506
507 $query = [
508 'format' => 'json',
509 'action' => 'query',
510 'meta' => 'siteinfo',
511 'siprop' => 'general',
512 ];
513
514 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
515
516 if ( $data ) {
517 $siteInfo = FormatJson::decode( $data, true );
518 $general = $siteInfo['query']['general'];
519
520 $info['articlepath'] = $general['articlepath'];
521 $info['server'] = $general['server'];
522 if ( !isset( $info['favicon'] ) && isset( $general['favicon'] ) ) {
523 $info['favicon'] = $general['favicon'];
524 }
525 }
526
527 return $info;
528 }
529
537 public static function httpGet(
538 $url, $timeout = 'default', $options = [], &$mtime = false
539 ) {
540 $options['timeout'] = $timeout;
541 /* Http::get */
543 wfDebug( "ForeignAPIRepo: HTTP GET: $url" );
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 // @phan-suppress-previous-line PhanPluginNeverReturnMethod
623 throw new MWException( 'enumFiles is not supported by ' . static::class );
624 }
625
629 protected function assertWritableRepo() {
630 throw new MWException( static::class . ': write operations are not supported.' );
631 }
632}
const NS_FILE
Definition Defines.php:70
const PROTO_HTTP
Definition Defines.php:193
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.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
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.
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
quickCreate(array $params, array $opts=[])
Performs a single quick create operation.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getFileTimestamp(array $params)
Get the last-modified timestamp of the file at a storage path.
prepare(array $params)
Prepare a storage directory for usage.
Base class for file repositories.
Definition FileRepo.php:47
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:806
FileBackend $backend
Definition FileRepo.php:70
string false $url
Public zone URL.
Definition FileRepo.php:111
validateFilename( $filename)
Determine if a relative path is valid, i.e.
string $name
Definition FileRepo.php:161
string false $thumbUrl
The base thumbnail URL.
Definition FileRepo.php:114
getHashPath( $name)
Get a relative path including trailing slash, e.g.
Definition FileRepo.php:745
getBackend()
Get the file backend instance.
Definition FileRepo.php:250
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)
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)
MediaWiki exception.
Basic media transform error class.
PSR-3 logger instance factory.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
A foreign repo that implement support for API queries.
Interface for objects (potentially) representing an editable wiki page.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42
if(!is_readable( $file)) $ext
Definition router.php:48
if(!isset( $args[0])) $lang