Merge "docs: Fix typo"
[mediawiki.git] / includes / filerepo / file / ForeignAPIFile.php
blob1ffcd20f86041f95ee71ed8fb0e8cf6e63c8f1d1
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.
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.
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
18 * @file
21 use MediaWiki\MediaWikiServices;
22 use MediaWiki\Permissions\Authority;
23 use MediaWiki\Title\Title;
24 use MediaWiki\User\UserIdentity;
25 use MediaWiki\User\UserIdentityValue;
27 /**
28 * Foreign file accessible through api.php requests.
30 * @ingroup FileAbstraction
32 class ForeignAPIFile extends File {
33 /** @var bool */
34 private $mExists;
35 /** @var array */
36 private $mInfo;
38 /** @inheritDoc */
39 protected $repoClass = ForeignAPIRepo::class;
41 /**
42 * @param Title|string|false $title
43 * @param ForeignApiRepo $repo
44 * @param array $info
45 * @param bool $exists
47 public function __construct( $title, $repo, $info, $exists = false ) {
48 parent::__construct( $title, $repo );
50 $this->mInfo = $info;
51 $this->mExists = $exists;
53 $this->assertRepoDefined();
56 /**
57 * @param Title $title
58 * @param ForeignApiRepo $repo
59 * @return ForeignAPIFile|null
61 public static function newFromTitle( Title $title, $repo ) {
62 $data = $repo->fetchImageQuery( [
63 'titles' => 'File:' . $title->getDBkey(),
64 'iiprop' => self::getProps(),
65 'prop' => 'imageinfo',
66 'iimetadataversion' => MediaHandler::getMetadataVersion(),
67 // extmetadata is language-dependent, accessing the current language here
68 // would be problematic, so we just get them all
69 'iiextmetadatamultilang' => 1,
70 ] );
72 $info = $repo->getImageInfo( $data );
74 if ( $info ) {
75 $lastRedirect = count( $data['query']['redirects'] ?? [] ) - 1;
76 if ( $lastRedirect >= 0 ) {
77 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
78 $newtitle = Title::newFromText( $data['query']['redirects'][$lastRedirect]['to'] );
79 $img = new self( $newtitle, $repo, $info, true );
80 $img->redirectedFrom( $title->getDBkey() );
81 } else {
82 $img = new self( $title, $repo, $info, true );
85 return $img;
86 } else {
87 return null;
91 /**
92 * Get the property string for iiprop and aiprop
93 * @return string
95 public static function getProps() {
96 return 'timestamp|user|comment|url|size|sha1|metadata|mime|mediatype|extmetadata';
99 /**
100 * @return ForeignAPIRepo|false
102 public function getRepo() {
103 return $this->repo;
106 // Dummy functions...
109 * @return bool
111 public function exists() {
112 return $this->mExists;
116 * @return bool
118 public function getPath() {
119 return false;
123 * @param array $params
124 * @param int $flags
125 * @return MediaTransformOutput|false
127 public function transform( $params, $flags = 0 ) {
128 if ( !$this->canRender() ) {
129 // show icon
130 return parent::transform( $params, $flags );
133 // Note, the this->canRender() check above implies
134 // that we have a handler, and it can do makeParamString.
135 $otherParams = $this->handler->makeParamString( $params );
136 $width = $params['width'] ?? -1;
137 $height = $params['height'] ?? -1;
138 $thumbUrl = false;
140 if ( $width > 0 || $height > 0 ) {
141 // Only query the remote if there are dimensions
142 $thumbUrl = $this->repo->getThumbUrlFromCache(
143 $this->getName(),
144 $width,
145 $height,
146 $otherParams
148 } elseif ( $this->getMediaType() === MEDIATYPE_AUDIO ) {
149 // This has no dimensions, but we still need to pass a value to getTransform()
150 $thumbUrl = '/';
152 if ( $thumbUrl === false ) {
153 global $wgLang;
155 return $this->repo->getThumbError(
156 $this->getName(),
157 $width,
158 $height,
159 $otherParams,
160 $wgLang->getCode()
164 return $this->handler->getTransform( $this, 'bogus', $thumbUrl, $params );
167 // Info we can get from API...
170 * @param int $page
171 * @return int
173 public function getWidth( $page = 1 ) {
174 return (int)( $this->mInfo['width'] ?? 0 );
178 * @param int $page
179 * @return int
181 public function getHeight( $page = 1 ) {
182 return (int)( $this->mInfo['height'] ?? 0 );
186 * @return string|false
188 public function getMetadata() {
189 if ( isset( $this->mInfo['metadata'] ) ) {
190 return serialize( self::parseMetadata( $this->mInfo['metadata'] ) );
193 return false;
196 public function getMetadataArray(): array {
197 if ( isset( $this->mInfo['metadata'] ) ) {
198 return self::parseMetadata( $this->mInfo['metadata'] );
201 return [];
205 * @return array|null Extended metadata (see imageinfo API for format) or
206 * null on error
208 public function getExtendedMetadata() {
209 return $this->mInfo['extmetadata'] ?? null;
213 * @param mixed $metadata
214 * @return array
216 public static function parseMetadata( $metadata ) {
217 if ( !is_array( $metadata ) ) {
218 return [ '_error' => $metadata ];
220 '@phan-var array[] $metadata';
221 $ret = [];
222 foreach ( $metadata as $meta ) {
223 $ret[$meta['name']] = self::parseMetadataValue( $meta['value'] );
226 return $ret;
230 * @param mixed $metadata
231 * @return mixed
233 private static function parseMetadataValue( $metadata ) {
234 if ( !is_array( $metadata ) ) {
235 return $metadata;
237 '@phan-var array[] $metadata';
238 $ret = [];
239 foreach ( $metadata as $meta ) {
240 $ret[$meta['name']] = self::parseMetadataValue( $meta['value'] );
243 return $ret;
247 * @return int|null|false
249 public function getSize() {
250 return isset( $this->mInfo['size'] ) ? intval( $this->mInfo['size'] ) : null;
254 * @return null|string
256 public function getUrl() {
257 return isset( $this->mInfo['url'] ) ? strval( $this->mInfo['url'] ) : null;
261 * Get short description URL for a file based on the foreign API response,
262 * or if unavailable, the short URL is constructed from the foreign page ID.
264 * @return null|string
265 * @since 1.27
267 public function getDescriptionShortUrl() {
268 if ( isset( $this->mInfo['descriptionshorturl'] ) ) {
269 return $this->mInfo['descriptionshorturl'];
270 } elseif ( isset( $this->mInfo['pageid'] ) ) {
271 $url = $this->repo->makeUrl( [ 'curid' => $this->mInfo['pageid'] ] );
272 if ( $url !== false ) {
273 return $url;
276 return null;
279 public function getUploader( int $audience = self::FOR_PUBLIC, ?Authority $performer = null ): ?UserIdentity {
280 if ( isset( $this->mInfo['user'] ) ) {
281 return UserIdentityValue::newExternal( $this->getRepoName(), $this->mInfo['user'] );
283 return null;
287 * @param int $audience
288 * @param Authority|null $performer
289 * @return null|string
291 public function getDescription( $audience = self::FOR_PUBLIC, ?Authority $performer = null ) {
292 return isset( $this->mInfo['comment'] ) ? strval( $this->mInfo['comment'] ) : null;
296 * @return null|string
298 public function getSha1() {
299 return isset( $this->mInfo['sha1'] )
300 ? Wikimedia\base_convert( strval( $this->mInfo['sha1'] ), 16, 36, 31 )
301 : null;
305 * @return string|false
307 public function getTimestamp() {
308 return wfTimestamp( TS_MW,
309 isset( $this->mInfo['timestamp'] )
310 ? strval( $this->mInfo['timestamp'] )
311 : null
316 * @return string
318 public function getMimeType() {
319 if ( !isset( $this->mInfo['mime'] ) ) {
320 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
321 $this->mInfo['mime'] = $magic->getMimeTypeFromExtensionOrNull( $this->getExtension() );
324 return $this->mInfo['mime'];
328 * @return int|string
330 public function getMediaType() {
331 if ( isset( $this->mInfo['mediatype'] ) ) {
332 return $this->mInfo['mediatype'];
334 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
336 return $magic->getMediaType( null, $this->getMimeType() );
340 * @return string|false
342 public function getDescriptionUrl() {
343 return $this->mInfo['descriptionurl'] ?? false;
347 * Only useful if we're locally caching thumbs anyway...
348 * @param string $suffix
349 * @return null|string
351 public function getThumbPath( $suffix = '' ) {
352 if ( !$this->repo->canCacheThumbs() ) {
353 return null;
356 $path = $this->repo->getZonePath( 'thumb' ) . '/' . $this->getHashPath();
357 if ( $suffix ) {
358 $path .= $suffix . '/';
360 return $path;
364 * @return string[]
366 protected function getThumbnails() {
367 $dir = $this->getThumbPath( $this->getName() );
368 $iter = $this->repo->getBackend()->getFileList( [ 'dir' => $dir ] );
370 $files = [];
371 if ( $iter ) {
372 foreach ( $iter as $file ) {
373 $files[] = $file;
377 return $files;
380 public function purgeCache( $options = [] ) {
381 $this->purgeThumbnails( $options );
382 $this->purgeDescriptionPage();
385 private function purgeDescriptionPage() {
386 $services = MediaWikiServices::getInstance();
387 $langCode = $services->getContentLanguageCode()->toString();
389 // Key must match File::getDescriptionText
390 $key = $this->repo->getLocalCacheKey( 'file-remote-description', $langCode, md5( $this->getName() ) );
391 $services->getMainWANObjectCache()->delete( $key );
395 * @param array $options
397 public function purgeThumbnails( $options = [] ) {
398 $key = $this->repo->getLocalCacheKey( 'file-thumb-url', sha1( $this->getName() ) );
399 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
401 $files = $this->getThumbnails();
402 // Give media handler a chance to filter the purge list
403 $handler = $this->getHandler();
404 if ( $handler ) {
405 $handler->filterThumbnailPurgeList( $files, $options );
408 $dir = $this->getThumbPath( $this->getName() );
409 $purgeList = [];
410 foreach ( $files as $file ) {
411 $purgeList[] = "{$dir}{$file}";
414 # Delete the thumbnails
415 $this->repo->quickPurgeBatch( $purgeList );
416 # Clear out the thumbnail directory if empty
417 $this->repo->quickCleanDir( $dir );
421 * The thumbnail is created on the foreign server and fetched over internet
422 * @since 1.25
423 * @return bool
425 public function isTransformedLocally() {
426 return false;