Debian Codegraph @

includes/filerepo/ForeignAPIRepo.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\Json\FormatJson;
22 use MediaWiki\Linker\LinkTarget;
23 use MediaWiki\Logger\LoggerFactory;
24 use MediaWiki\MainConfigNames;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Page\PageIdentity;
27 use MediaWiki\Title\Title;
28 use Wikimedia\FileBackend\FileBackend;
29 use Wikimedia\ObjectCache\WANObjectCache;
30
31 /**
32 * A foreign repository for a remote MediaWiki accessible through api.php requests.
33 *
34 * @par Example config:
35 * @code
36 * $wgForeignFileRepos[] = [
37 * 'class' => ForeignAPIRepo::class,
38 * 'name' => 'shared',
39 * 'apibase' => 'https://en.wikipedia.org/w/api.php',
40 * 'fetchDescription' => true, // Optional
41 * 'descriptionCacheExpiry' => 3600,
42 * ];
43 * @endcode
44 *
45 * @ingroup FileRepo
46 */
47 class ForeignAPIRepo extends FileRepo implements IForeignRepoWithMWApi {
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
53 /**
54 * List of iiprop values for the thumbnail fetch queries.
55 */
56 private const IMAGE_INFO_PROPS = [
57 'url',
58 'timestamp',
59 ];
60
61 /** @var callable */
62 protected $fileFactory = [ ForeignAPIFile::class, 'newFromTitle' ];
63 /** @var int Check back with Commons after this expiry */
64 protected $apiThumbCacheExpiry = 24 * 3600; // 1 day
65
66 /** @var int Redownload thumbnail files after this expiry */
67 protected $fileCacheExpiry = 30 * 24 * 3600; // 1 month
68
69 /**
70 * @var int API metadata cache time.
71 * @since 1.38
72 *
73 * This is often the performance bottleneck for ForeignAPIRepo. For
74 * each file used, we must fetch file metadata for it and every high-DPI
75 * variant, in serial, during the parse. This is slow if a page has many
76 * files, with RTT of the handshake often being significant. The metadata
77 * rarely changes, but if a new version of the file was uploaded, it might
78 * be displayed incorrectly until its metadata entry falls out of cache.
79 */
80 protected $apiMetadataExpiry = 4 * 3600; // 4 hours
81
82 /** @var array */
83 protected $mFileExists = [];
84
85 /** @var string */
86 private $mApiBase;
87
88 /** @var string */
89 private $userAgent;
90
91 /**
92 * @param array|null $info
93 */
94 public function __construct( $info ) {
95 $localFileRepo = MediaWikiServices::getInstance()->getMainConfig()
96 ->get( MainConfigNames::LocalFileRepo );
97 parent::__construct( $info );
98
99 // https://commons.wikimedia.org/w/api.php
100 $this->mApiBase = $info['apibase'] ?? null;
101
102 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
103 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
104 }
105 if ( isset( $info['fileCacheExpiry'] ) ) {
106 $this->fileCacheExpiry = $info['fileCacheExpiry'];
107 }
108 if ( isset( $info['apiMetadataExpiry'] ) ) {
109 $this->apiMetadataExpiry = $info['apiMetadataExpiry'];
110 }
111 if ( isset( $info['userAgent'] ) ) {
112 $this->userAgent = $info['userAgent'];
113 }
114 if ( !$this->scriptDirUrl ) {
115 // hack for description fetches
116 $this->scriptDirUrl = dirname( $this->mApiBase );
117 }
118 // If we can cache thumbs we can guess sensible defaults for these
119 if ( $this->canCacheThumbs() && !$this->url ) {
120 $this->url = $localFileRepo['url'];
121 }
122 if ( $this->canCacheThumbs() && !$this->thumbUrl ) {
123 $this->thumbUrl = $this->url . '/thumb';
124 }
125 }
126
127 /**
128 * Per docs in FileRepo, this needs to return false if we don't support versioned
129 * files. Well, we don't.
130 *
131 * @param PageIdentity|LinkTarget|string $title
132 * @param string|false $time
133 * @return File|false
134 */
135 public function newFile( $title, $time = false ) {
136 if ( $time ) {
137 return false;
138 }
139
140 return parent::newFile( $title, $time );
141 }
142
143 /**
144 * @param string[] $files
145 * @return array
146 */
147 public function fileExistsBatch( array $files ) {
148 $results = [];
149 foreach ( $files as $k => $f ) {
150 if ( isset( $this->mFileExists[$f] ) ) {
151 $results[$k] = $this->mFileExists[$f];
152 unset( $files[$k] );
153 } elseif ( self::isVirtualUrl( $f ) ) {
154 # @todo FIXME: We need to be able to handle virtual
155 # URLs better, at least when we know they refer to the
156 # same repo.
157 $results[$k] = false;
158 unset( $files[$k] );
159 } elseif ( FileBackend::isStoragePath( $f ) ) {
160 $results[$k] = false;
161 unset( $files[$k] );
162 wfWarn( "Got mwstore:// path '$f'." );
163 }
164 }
165
166 $data = $this->fetchImageQuery( [
167 'titles' => implode( '|', $files ),
168 'prop' => 'imageinfo' ]
169 );
170
171 if ( isset( $data['query']['pages'] ) ) {
172 # First, get results from the query. Note we only care whether the image exists,
173 # not whether it has a description page.
174 foreach ( $data['query']['pages'] as $p ) {
175 $this->mFileExists[$p['title']] = ( $p['imagerepository'] !== '' );
176 }
177 # Second, copy the results to any redirects that were queried
178 if ( isset( $data['query']['redirects'] ) ) {
179 foreach ( $data['query']['redirects'] as $r ) {
180 $this->mFileExists[$r['from']] = $this->mFileExists[$r['to']];
181 }
182 }
183 # Third, copy the results to any non-normalized titles that were queried
184 if ( isset( $data['query']['normalized'] ) ) {
185 foreach ( $data['query']['normalized'] as $n ) {
186 $this->mFileExists[$n['from']] = $this->mFileExists[$n['to']];
187 }
188 }
189 # Finally, copy the results to the output
190 foreach ( $files as $key => $file ) {
191 $results[$key] = $this->mFileExists[$file];
192 }
193 }
194
195 return $results;
196 }
197
198 /**
199 * @param string $virtualUrl
200 * @return array
201 */
202 public function getFileProps( $virtualUrl ) {
203 return [];
204 }
205
206 /**
207 * Make an API query in the foreign repo, caching results
208 *
209 * @param array $query
210 * @return array|null
211 */
212 public function fetchImageQuery( $query ) {
213 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
214 ->get( MainConfigNames::LanguageCode );
215
216 $query = array_merge( $query,
217 [
218 'format' => 'json',
219 'action' => 'query',
220 'redirects' => 'true'
221 ] );
222
223 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
224 $query['uselang'] = $languageCode;
225 }
226
227 $data = $this->httpGetCached( 'Metadata', $query, $this->apiMetadataExpiry );
228
229 if ( $data ) {
230 return FormatJson::decode( $data, true );
231 } else {
232 return null;
233 }
234 }
235
236 /**
237 * @param array $data
238 * @return array|false
239 */
240 public function getImageInfo( $data ) {
241 if ( $data && isset( $data['query']['pages'] ) ) {
242 foreach ( $data['query']['pages'] as $info ) {
243 if ( isset( $info['imageinfo'][0] ) ) {
244 $return = $info['imageinfo'][0];
245 if ( isset( $info['pageid'] ) ) {
246 $return['pageid'] = $info['pageid'];
247 }
248 return $return;
249 }
250 }
251 }
252
253 return false;
254 }
255
256 /**
257 * @param string $hash
258 * @return ForeignAPIFile[]
259 */
260 public function findBySha1( $hash ) {
261 $results = $this->fetchImageQuery( [
262 'aisha1base36' => $hash,
263 'aiprop' => ForeignAPIFile::getProps(),
264 'list' => 'allimages',
265 ] );
266 $ret = [];
267 if ( isset( $results['query']['allimages'] ) ) {
268 foreach ( $results['query']['allimages'] as $img ) {
269 // 1.14 was broken, doesn't return name attribute
270 if ( !isset( $img['name'] ) ) {
271 continue;
272 }
273 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
274 }
275 }
276
277 return $ret;
278 }
279
280 /**
281 * @param string $name
282 * @param int $width
283 * @param int $height
284 * @param array|null &$result Output-only parameter, guaranteed to become an array
285 * @param string $otherParams
286 *
287 * @return string|false
288 */
289 private function getThumbUrl(
290 $name, $width = -1, $height = -1, &$result = null, $otherParams = ''
291 ) {
292 $data = $this->fetchImageQuery( [
293 'titles' => 'File:' . $name,
294 'iiprop' => self::getIIProps(),
295 'iiurlwidth' => $width,
296 'iiurlheight' => $height,
297 'iiurlparam' => $otherParams,
298 'prop' => 'imageinfo' ] );
299 $info = $this->getImageInfo( $data );
300
301 if ( $data && $info && isset( $info['thumburl'] ) ) {
302 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] );
303 $result = $info;
304
305 return $info['thumburl'];
306 } else {
307 return false;
308 }
309 }
310
311 /**
312 * @param string $name
313 * @param int $width
314 * @param int $height
315 * @param string $otherParams
316 * @param string|null $lang Language code for language of error
317 * @return MediaTransformError|false
318 * @since 1.22
319 */
320 public function getThumbError(
321 $name, $width = -1, $height = -1, $otherParams = '', $lang = null
322 ) {
323 $data = $this->fetchImageQuery( [
324 'titles' => 'File:' . $name,
325 'iiprop' => self::getIIProps(),
326 'iiurlwidth' => $width,
327 'iiurlheight' => $height,
328 'iiurlparam' => $otherParams,
329 'prop' => 'imageinfo',
330 'uselang' => $lang,
331 ] );
332 $info = $this->getImageInfo( $data );
333
334 if ( $data && $info && isset( $info['thumberror'] ) ) {
335 wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] );
336
337 return new MediaTransformError(
338 'thumbnail_error_remote',
339 $width,
340 $height,
341 $this->getDisplayName(),
342 $info['thumberror'] // already parsed message from foreign repo
343 );
344 } else {
345 return false;
346 }
347 }
348
349 /**
350 * Return the imageurl from cache if possible
351 *
352 * If the url has been requested today, get it from cache
353 * Otherwise retrieve remote thumb url, check for local file.
354 *
355 * @param string $name Is a dbkey form of a title
356 * @param int $width
357 * @param int $height
358 * @param string $params Other rendering parameters (page number, etc)
359 * from handler's makeParamString.
360 * @return string|false
361 */
362 public function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
363 // We can't check the local cache using FileRepo functions because
364 // we override fileExistsBatch(). We have to use the FileBackend directly.
365 $backend = $this->getBackend(); // convenience
366
367 if ( !$this->canCacheThumbs() ) {
368 $result = null; // can't pass "null" by reference, but it's ok as default value
369
370 return $this->getThumbUrl( $name, $width, $height, $result, $params );
371 }
372
373 $key = $this->getLocalCacheKey( 'file-thumb-url', sha1( $name ) );
374 $sizekey = "$width:$height:$params";
375
376 /* Get the array of urls that we already know */
377 $knownThumbUrls = $this->wanCache->get( $key );
378 if ( !$knownThumbUrls ) {
379 /* No knownThumbUrls for this file */
380 $knownThumbUrls = [];
381 } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
382 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
383 "{$knownThumbUrls[$sizekey]}" );
384
385 return $knownThumbUrls[$sizekey];
386 }
387
388 $metadata = null;
389 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
390
391 if ( !$foreignUrl ) {
392 wfDebug( __METHOD__ . " Could not find thumburl" );
393
394 return false;
395 }
396
397 // We need the same filename as the remote one :)
398 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
399 if ( !$this->validateFilename( $fileName ) ) {
400 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe" );
401
402 return false;
403 }
404 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
405 $localFilename = $localPath . "/" . $fileName;
406 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) .
407 rawurlencode( $name ) . "/" . rawurlencode( $fileName );
408
409 if ( $backend->fileExists( [ 'src' => $localFilename ] )
410 && isset( $metadata['timestamp'] )
411 ) {
412 wfDebug( __METHOD__ . " Thumbnail was already downloaded before" );
413 $modified = (int)wfTimestamp( TS_UNIX, $backend->getFileTimestamp( [ 'src' => $localFilename ] ) );
414 $remoteModified = (int)wfTimestamp( TS_UNIX, $metadata['timestamp'] );
415 $current = (int)wfTimestamp( TS_UNIX );
416 $diff = abs( $modified - $current );
417 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
418 /* Use our current and already downloaded thumbnail */
419 $knownThumbUrls[$sizekey] = $localUrl;
420 $this->wanCache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
421
422 return $localUrl;
423 }
424 /* There is a new Commons file, or existing thumbnail older than a month */
425 }
426
427 $thumb = $this->httpGet( $foreignUrl, 'default', [], $mtime );
428 if ( !$thumb ) {
429 wfDebug( __METHOD__ . " Could not download thumb" );
430
431 return false;
432 }
433
434 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
435 $backend->prepare( [ 'dir' => dirname( $localFilename ) ] );
436 $params = [ 'dst' => $localFilename, 'content' => $thumb ];
437 if ( !$backend->quickCreate( $params )->isOK() ) {
438 wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'" );
439
440 return $foreignUrl;
441 }
442 $knownThumbUrls[$sizekey] = $localUrl;
443
444 $ttl = $mtime
445 ? $this->wanCache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
446 : $this->apiThumbCacheExpiry;
447 $this->wanCache->set( $key, $knownThumbUrls, $ttl );
448 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache" );
449
450 return $localUrl;
451 }
452
453 /**
454 * @see FileRepo::getZoneUrl()
455 * @param string $zone
456 * @param string|null $ext Optional file extension
457 * @return string
458 */
459 public function getZoneUrl( $zone, $ext = null ) {
460 switch ( $zone ) {
461 case 'public':
462 return $this->url;
463 case 'thumb':
464 return $this->thumbUrl;
465 default:
466 return parent::getZoneUrl( $zone, $ext );
467 }
468 }
469
470 /**
471 * Get the local directory corresponding to one of the basic zones
472 * @param string $zone
473 * @return null|string|false
474 */
475 public function getZonePath( $zone ) {
476 $supported = [ 'public', 'thumb' ];
477 if ( in_array( $zone, $supported ) ) {
478 return parent::getZonePath( $zone );
479 }
480
481 return false;
482 }
483
484 /**
485 * Are we locally caching the thumbnails?
486 * @return bool
487 */
488 public function canCacheThumbs() {
489 return ( $this->apiThumbCacheExpiry > 0 );
490 }
491
492 /**
493 * The user agent the ForeignAPIRepo will use.
494 * @return string
495 */
496 public function getUserAgent() {
497 $mediaWikiVersion = MediaWikiServices::getInstance()->getHttpRequestFactory()->getUserAgent();
498 $classVersion = self::VERSION;
499 $contactUrl = MediaWikiServices::getInstance()->getUrlUtils()->getCanonicalServer();
500 $extra = $this->userAgent !== null ? ' ' . $this->userAgent : '';
501 return "$mediaWikiVersion ($contactUrl) ForeignAPIRepo/$classVersion" . $extra;
502 }
503
504 /**
505 * Get information about the repo - overrides/extends the parent
506 * class's information.
507 * @return array
508 * @since 1.22
509 */
510 public function getInfo() {
511 $info = parent::getInfo();
512 $info['apiurl'] = $this->mApiBase;
513
514 $query = [
515 'format' => 'json',
516 'action' => 'query',
517 'meta' => 'siteinfo',
518 'siprop' => 'general',
519 ];
520
521 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
522
523 if ( $data ) {
524 $siteInfo = FormatJson::decode( $data, true );
525 $general = $siteInfo['query']['general'];
526
527 $info['articlepath'] = $general['articlepath'];
528 $info['server'] = $general['server'];
529 if ( !isset( $info['favicon'] ) && isset( $general['favicon'] ) ) {
530 $info['favicon'] = $general['favicon'];
531 }
532 }
533
534 return $info;
535 }
536
537 /**
538 * @param string $url
539 * @param string $timeout
540 * @param array $options
541 * @param int|false &$mtime Resulting Last-Modified UNIX timestamp if received
542 * @return string|false
543 */
544 public function httpGet(
545 $url, $timeout = 'default', $options = [], &$mtime = false
546 ) {
547 $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
548 $requestFactory = MediaWikiServices::getInstance()->getHttpRequestFactory();
549
550 $options['timeout'] = $timeout;
551 $url = $urlUtils->expand( $url, PROTO_HTTP );
552 wfDebug( "ForeignAPIRepo: HTTP GET: $url" );
553 if ( !$url ) {
554 return false;
555 }
556 $options['method'] = "GET";
557
558 if ( !isset( $options['timeout'] ) ) {
559 $options['timeout'] = 'default';
560 }
561
562 $options['userAgent'] = $this->getUserAgent();
563
564 $req = $requestFactory->create( $url, $options, __METHOD__ );
565 $req->setHeader( 'Referer', $urlUtils->getCanonicalServer() );
566 $status = $req->execute();
567
568 if ( $status->isOK() ) {
569 $lmod = $req->getResponseHeader( 'Last-Modified' );
570 $mtime = $lmod ? (int)wfTimestamp( TS_UNIX, $lmod ) : false;
571
572 return $req->getContent();
573 } else {
574 $logger = LoggerFactory::getInstance( 'http' );
575 $logger->warning(
576 $status->getWikiText( false, false, 'en' ),
577 [ 'caller' => __METHOD__ ]
578 );
579
580 return false;
581 }
582 }
583
584 /**
585 * @return string
586 * @since 1.23
587 */
588 protected static function getIIProps() {
589 return implode( '|', self::IMAGE_INFO_PROPS );
590 }
591
592 /**
593 * HTTP GET request to a mediawiki API (with caching)
594 * @param string $attribute Used in cache key creation, mostly
595 * @param array $query The query parameters for the API request
596 * @param int $cacheTTL Time to live for the memcached caching
597 * @return string|null
598 */
599 public function httpGetCached( $attribute, $query, $cacheTTL = 3600 ) {
600 if ( $this->mApiBase ) {
601 $url = wfAppendQuery( $this->mApiBase, $query );
602 } else {
603 $url = $this->makeUrl( $query, 'api' );
604 }
605
606 return $this->wanCache->getWithSetCallback(
607 // Allow reusing the same cached data across wikis (T285271).
608 // This does not use getSharedCacheKey() because caching here
609 // is transparent to client wikis (which are not expected to issue purges).
610 $this->wanCache->makeGlobalKey( "filerepo-$attribute", sha1( $url ) ),
611 $cacheTTL,
612 function ( $curValue, &$ttl ) use ( $url ) {
613 $html = $this->httpGet( $url, 'default', [], $mtime );
614 // FIXME: This should use the mtime from the api response body
615 // not the mtime from the last-modified header which usually is not set.
616 if ( $html !== false ) {
617 $ttl = $mtime ? $this->wanCache->adaptiveTTL( $mtime, $ttl ) : $ttl;
618 } else {
619 $ttl = $this->wanCache->adaptiveTTL( $mtime, $ttl );
620 $html = null; // caches negatives
621 }
622
623 return $html;
624 },
625 [ 'pcGroup' => 'http-get:3', 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
626 );
627 }
628
629 /**
630 * @param callable $callback
631 * @return never
632 */
633 public function enumFiles( $callback ) {
634 throw new RuntimeException( 'enumFiles is not supported by ' . static::class );
635 }
636
637 /**
638 * @return never
639 */
640 protected function assertWritableRepo() {
641 throw new LogicException( static::class . ': write operations are not supported.' );
642 }
643 }