MediaWiki  master
ForeignAPIRepo.php
Go to the documentation of this file.
1 <?php
26 
43 class ForeignAPIRepo extends FileRepo implements IForeignRepoWithMWApi {
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 */
542  $url = MediaWikiServices::getInstance()->getUrlUtils()
543  ->expand( $url, PROTO_HTTP );
544  wfDebug( "ForeignAPIRepo: HTTP GET: $url" );
545  if ( !$url ) {
546  return false;
547  }
548  $options['method'] = "GET";
549 
550  if ( !isset( $options['timeout'] ) ) {
551  $options['timeout'] = 'default';
552  }
553 
554  $options['userAgent'] = self::getUserAgent();
555 
556  $req = MediaWikiServices::getInstance()->getHttpRequestFactory()
557  ->create( $url, $options, __METHOD__ );
558  $status = $req->execute();
559 
560  if ( $status->isOK() ) {
561  $lmod = $req->getResponseHeader( 'Last-Modified' );
562  $mtime = $lmod ? (int)wfTimestamp( TS_UNIX, $lmod ) : false;
563 
564  return $req->getContent();
565  } else {
566  $logger = LoggerFactory::getInstance( 'http' );
567  $logger->warning(
568  $status->getWikiText( false, false, 'en' ),
569  [ 'caller' => 'ForeignAPIRepo::httpGet' ]
570  );
571 
572  return false;
573  }
574  }
575 
580  protected static function getIIProps() {
581  return implode( '|', self::IMAGE_INFO_PROPS );
582  }
583 
591  public function httpGetCached( $attribute, $query, $cacheTTL = 3600 ) {
592  if ( $this->mApiBase ) {
593  $url = wfAppendQuery( $this->mApiBase, $query );
594  } else {
595  $url = $this->makeUrl( $query, 'api' );
596  }
597 
598  return $this->wanCache->getWithSetCallback(
599  // Allow reusing the same cached data across wikis (T285271).
600  // This does not use getSharedCacheKey() because caching here
601  // is transparent to client wikis (which are not expected to issue purges).
602  $this->wanCache->makeGlobalKey( "filerepo-$attribute", sha1( $url ) ),
603  $cacheTTL,
604  function ( $curValue, &$ttl ) use ( $url ) {
605  $html = self::httpGet( $url, 'default', [], $mtime );
606  // FIXME: This should use the mtime from the api response body
607  // not the mtime from the last-modified header which usually is not set.
608  if ( $html !== false ) {
609  $ttl = $mtime ? $this->wanCache->adaptiveTTL( $mtime, $ttl ) : $ttl;
610  } else {
611  $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
612  $html = null; // caches negatives
613  }
614 
615  return $html;
616  },
617  [ 'pcGroup' => 'http-get:3', 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
618  );
619  }
620 
625  public function enumFiles( $callback ) {
626  // @phan-suppress-previous-line PhanPluginNeverReturnMethod
627  throw new MWException( 'enumFiles is not supported by ' . static::class );
628  }
629 
633  protected function assertWritableRepo() {
634  throw new MWException( static::class . ': write operations are not supported.' );
635  }
636 }
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.
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.
Definition: FileRepo.php:1840
getLocalCacheKey( $kClassSuffix,... $components)
Get a site-local, repository-qualified, WAN cache key.
Definition: FileRepo.php:1902
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.
Definition: FileRepo.php:1741
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)
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:146
MediaWiki exception.
Definition: MWException.php:29
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.
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:641
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