Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[lhc/web/wiklou.git] / includes / filerepo / file / ForeignAPIFile.php
1 <?php
2 /**
3 * Foreign file accessible through api.php requests.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup FileAbstraction
22 */
23
24 use MediaWiki\MediaWikiServices;
25
26 /**
27 * Foreign file accessible through api.php requests.
28 * Very hacky and inefficient, do not use :D
29 *
30 * @ingroup FileAbstraction
31 */
32 class ForeignAPIFile extends File {
33 /** @var bool */
34 private $mExists;
35 /** @var array */
36 private $mInfo = [];
37
38 protected $repoClass = ForeignAPIRepo::class;
39
40 /**
41 * @param Title|string|bool $title
42 * @param ForeignApiRepo $repo
43 * @param array $info
44 * @param bool $exists
45 */
46 function __construct( $title, $repo, $info, $exists = false ) {
47 parent::__construct( $title, $repo );
48
49 $this->mInfo = $info;
50 $this->mExists = $exists;
51
52 $this->assertRepoDefined();
53 }
54
55 /**
56 * @param Title $title
57 * @param ForeignApiRepo $repo
58 * @return ForeignAPIFile|null
59 */
60 static function newFromTitle( Title $title, $repo ) {
61 $data = $repo->fetchImageQuery( [
62 'titles' => 'File:' . $title->getDBkey(),
63 'iiprop' => self::getProps(),
64 'prop' => 'imageinfo',
65 'iimetadataversion' => MediaHandler::getMetadataVersion(),
66 // extmetadata is language-dependant, accessing the current language here
67 // would be problematic, so we just get them all
68 'iiextmetadatamultilang' => 1,
69 ] );
70
71 $info = $repo->getImageInfo( $data );
72
73 if ( $info ) {
74 $lastRedirect = isset( $data['query']['redirects'] )
75 ? count( $data['query']['redirects'] ) - 1
76 : -1;
77 if ( $lastRedirect >= 0 ) {
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 );
83 }
84
85 return $img;
86 } else {
87 return null;
88 }
89 }
90
91 /**
92 * Get the property string for iiprop and aiprop
93 * @return string
94 */
95 static function getProps() {
96 return 'timestamp|user|comment|url|size|sha1|metadata|mime|mediatype|extmetadata';
97 }
98
99 // Dummy functions...
100
101 /**
102 * @return bool
103 */
104 public function exists() {
105 return $this->mExists;
106 }
107
108 /**
109 * @return bool
110 */
111 public function getPath() {
112 return false;
113 }
114
115 /**
116 * @param array $params
117 * @param int $flags
118 * @return bool|MediaTransformOutput
119 */
120 function transform( $params, $flags = 0 ) {
121 if ( !$this->canRender() ) {
122 // show icon
123 return parent::transform( $params, $flags );
124 }
125
126 // Note, the this->canRender() check above implies
127 // that we have a handler, and it can do makeParamString.
128 $otherParams = $this->handler->makeParamString( $params );
129 $width = $params['width'] ?? -1;
130 $height = $params['height'] ?? -1;
131
132 $thumbUrl = $this->repo->getThumbUrlFromCache(
133 $this->getName(),
134 $width,
135 $height,
136 $otherParams
137 );
138 if ( $thumbUrl === false ) {
139 global $wgLang;
140
141 return $this->repo->getThumbError(
142 $this->getName(),
143 $width,
144 $height,
145 $otherParams,
146 $wgLang->getCode()
147 );
148 }
149
150 return $this->handler->getTransform( $this, 'bogus', $thumbUrl, $params );
151 }
152
153 // Info we can get from API...
154
155 /**
156 * @param int $page
157 * @return int
158 */
159 public function getWidth( $page = 1 ) {
160 return isset( $this->mInfo['width'] ) ? intval( $this->mInfo['width'] ) : 0;
161 }
162
163 /**
164 * @param int $page
165 * @return int
166 */
167 public function getHeight( $page = 1 ) {
168 return isset( $this->mInfo['height'] ) ? intval( $this->mInfo['height'] ) : 0;
169 }
170
171 /**
172 * @return bool|null|string
173 */
174 public function getMetadata() {
175 if ( isset( $this->mInfo['metadata'] ) ) {
176 return serialize( self::parseMetadata( $this->mInfo['metadata'] ) );
177 }
178
179 return null;
180 }
181
182 /**
183 * @return array|null Extended metadata (see imageinfo API for format) or
184 * null on error
185 */
186 public function getExtendedMetadata() {
187 return $this->mInfo['extmetadata'] ?? null;
188 }
189
190 /**
191 * @param mixed $metadata
192 * @return mixed
193 */
194 public static function parseMetadata( $metadata ) {
195 if ( !is_array( $metadata ) ) {
196 return $metadata;
197 }
198 $ret = [];
199 foreach ( $metadata as $meta ) {
200 $ret[$meta['name']] = self::parseMetadata( $meta['value'] );
201 }
202
203 return $ret;
204 }
205
206 /**
207 * @return bool|int|null
208 */
209 public function getSize() {
210 return isset( $this->mInfo['size'] ) ? intval( $this->mInfo['size'] ) : null;
211 }
212
213 /**
214 * @return null|string
215 */
216 public function getUrl() {
217 return isset( $this->mInfo['url'] ) ? strval( $this->mInfo['url'] ) : null;
218 }
219
220 /**
221 * Get short description URL for a file based on the foreign API response,
222 * or if unavailable, the short URL is constructed from the foreign page ID.
223 *
224 * @return null|string
225 * @since 1.27
226 */
227 public function getDescriptionShortUrl() {
228 if ( isset( $this->mInfo['descriptionshorturl'] ) ) {
229 return $this->mInfo['descriptionshorturl'];
230 } elseif ( isset( $this->mInfo['pageid'] ) ) {
231 $url = $this->repo->makeUrl( [ 'curid' => $this->mInfo['pageid'] ] );
232 if ( $url !== false ) {
233 return $url;
234 }
235 }
236 return null;
237 }
238
239 /**
240 * @param string $type
241 * @return int|null|string
242 */
243 public function getUser( $type = 'text' ) {
244 if ( $type == 'text' ) {
245 return isset( $this->mInfo['user'] ) ? strval( $this->mInfo['user'] ) : null;
246 } else {
247 return 0; // What makes sense here, for a remote user?
248 }
249 }
250
251 /**
252 * @param int $audience
253 * @param User|null $user
254 * @return null|string
255 */
256 public function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
257 return isset( $this->mInfo['comment'] ) ? strval( $this->mInfo['comment'] ) : null;
258 }
259
260 /**
261 * @return null|string
262 */
263 function getSha1() {
264 return isset( $this->mInfo['sha1'] )
265 ? Wikimedia\base_convert( strval( $this->mInfo['sha1'] ), 16, 36, 31 )
266 : null;
267 }
268
269 /**
270 * @return bool|string
271 */
272 function getTimestamp() {
273 return wfTimestamp( TS_MW,
274 isset( $this->mInfo['timestamp'] )
275 ? strval( $this->mInfo['timestamp'] )
276 : null
277 );
278 }
279
280 /**
281 * @return string
282 */
283 function getMimeType() {
284 if ( !isset( $this->mInfo['mime'] ) ) {
285 $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
286 $this->mInfo['mime'] = $magic->guessTypesForExtension( $this->getExtension() );
287 }
288
289 return $this->mInfo['mime'];
290 }
291
292 /**
293 * @return int|string
294 */
295 function getMediaType() {
296 if ( isset( $this->mInfo['mediatype'] ) ) {
297 return $this->mInfo['mediatype'];
298 }
299 $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
300
301 return $magic->getMediaType( null, $this->getMimeType() );
302 }
303
304 /**
305 * @return bool|string
306 */
307 function getDescriptionUrl() {
308 return $this->mInfo['descriptionurl'] ?? false;
309 }
310
311 /**
312 * Only useful if we're locally caching thumbs anyway...
313 * @param string $suffix
314 * @return null|string
315 */
316 function getThumbPath( $suffix = '' ) {
317 if ( !$this->repo->canCacheThumbs() ) {
318 return null;
319 }
320
321 $path = $this->repo->getZonePath( 'thumb' ) . '/' . $this->getHashPath();
322 if ( $suffix ) {
323 $path .= $suffix . '/';
324 }
325 return $path;
326 }
327
328 /**
329 * @return string[]
330 */
331 function getThumbnails() {
332 $dir = $this->getThumbPath( $this->getName() );
333 $iter = $this->repo->getBackend()->getFileList( [ 'dir' => $dir ] );
334
335 $files = [];
336 if ( $iter ) {
337 foreach ( $iter as $file ) {
338 $files[] = $file;
339 }
340 }
341
342 return $files;
343 }
344
345 function purgeCache( $options = [] ) {
346 $this->purgeThumbnails( $options );
347 $this->purgeDescriptionPage();
348 }
349
350 function purgeDescriptionPage() {
351 $services = MediaWikiServices::getInstance();
352 $url = $this->repo->getDescriptionRenderUrl(
353 $this->getName(), $services->getContentLanguage()->getCode() );
354 $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', md5( $url ) );
355
356 $services->getMainWANObjectCache()->delete( $key );
357 }
358
359 /**
360 * @param array $options
361 */
362 function purgeThumbnails( $options = [] ) {
363 $key = $this->repo->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $this->getName() );
364 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
365
366 $files = $this->getThumbnails();
367 // Give media handler a chance to filter the purge list
368 $handler = $this->getHandler();
369 if ( $handler ) {
370 $handler->filterThumbnailPurgeList( $files, $options );
371 }
372
373 $dir = $this->getThumbPath( $this->getName() );
374 $purgeList = [];
375 foreach ( $files as $file ) {
376 $purgeList[] = "{$dir}{$file}";
377 }
378
379 # Delete the thumbnails
380 $this->repo->quickPurgeBatch( $purgeList );
381 # Clear out the thumbnail directory if empty
382 $this->repo->quickCleanDir( $dir );
383 }
384
385 /**
386 * The thumbnail is created on the foreign server and fetched over internet
387 * @since 1.25
388 * @return bool
389 */
390 public function isTransformedLocally() {
391 return false;
392 }
393 }