Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
64.13% covered (warning)
64.13%
286 / 446
33.33% covered (danger)
33.33%
5 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryImageInfo
64.27% covered (warning)
64.27%
286 / 445
33.33% covered (danger)
33.33%
5 / 15
1147.16
0.00% covered (danger)
0.00%
0 / 1
 __construct
71.43% covered (warning)
71.43%
10 / 14
0.00% covered (danger)
0.00%
0 / 1
2.09
 execute
55.56% covered (warning)
55.56%
65 / 117
0.00% covered (danger)
0.00%
0 / 1
149.78
 getScale
57.14% covered (warning)
57.14%
4 / 7
0.00% covered (danger)
0.00%
0 / 1
5.26
 mergeThumbParams
6.06% covered (danger)
6.06%
2 / 33
0.00% covered (danger)
0.00%
0 / 1
176.48
 checkParameterNormalise
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 getInfo
72.55% covered (warning)
72.55%
111 / 153
0.00% covered (danger)
0.00%
0 / 1
195.48
 getTransformCount
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 processMetaData
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 getCacheMode
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getContinueStr
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAllowedParams
100.00% covered (success)
100.00%
64 / 64
100.00% covered (success)
100.00%
1 / 1
1
 getPropertyNames
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getPropertyMessages
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
1
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 getHelpUrls
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9namespace MediaWiki\Api;
10
11use MediaWiki\FileRepo\File\File;
12use MediaWiki\FileRepo\File\OldLocalFile;
13use MediaWiki\FileRepo\RepoGroup;
14use MediaWiki\Language\Language;
15use MediaWiki\Linker\Linker;
16use MediaWiki\MainConfigNames;
17use MediaWiki\Media\FormatMetadata;
18use MediaWiki\Media\MediaTransformError;
19use MediaWiki\MediaWikiServices;
20use MediaWiki\Page\File\BadFileLookup;
21use MediaWiki\Specials\SpecialUpload;
22use MediaWiki\Title\Title;
23use MediaWiki\Upload\UploadBase;
24use Wikimedia\ParamValidator\ParamValidator;
25use Wikimedia\ParamValidator\TypeDef\IntegerDef;
26use Wikimedia\Timestamp\TimestampFormat as TS;
27
28/**
29 * A query action to get image information and upload history.
30 *
31 * @ingroup API
32 */
33class ApiQueryImageInfo extends ApiQueryBase {
34    public const TRANSFORM_LIMIT = 50;
35    /** @var int */
36    private static $transformCount = 0;
37
38    private RepoGroup $repoGroup;
39    private Language $contentLanguage;
40    private BadFileLookup $badFileLookup;
41
42    /**
43     * @param ApiQuery $query
44     * @param string $moduleName
45     * @param string|RepoGroup|null $prefixOrRepoGroup
46     * @param RepoGroup|Language|null $repoGroupOrContentLanguage
47     * @param Language|BadFileLookup|null $contentLanguageOrBadFileLookup
48     * @param BadFileLookup|null $badFileLookupOrUnused
49     */
50    public function __construct(
51        ApiQuery $query,
52        string $moduleName,
53        $prefixOrRepoGroup = null,
54        $repoGroupOrContentLanguage = null,
55        $contentLanguageOrBadFileLookup = null,
56        $badFileLookupOrUnused = null
57    ) {
58        // We allow a subclass to override the prefix, to create a related API module.
59        // The ObjectFactory is injecting the services without the prefix.
60        if ( !is_string( $prefixOrRepoGroup ) ) {
61            $prefix = 'ii';
62            $repoGroup = $prefixOrRepoGroup;
63            $contentLanguage = $repoGroupOrContentLanguage;
64            $badFileLookup = $contentLanguageOrBadFileLookup;
65            // $badFileLookupOrUnused is null in this case
66        } else {
67            $prefix = $prefixOrRepoGroup;
68            $repoGroup = $repoGroupOrContentLanguage;
69            $contentLanguage = $contentLanguageOrBadFileLookup;
70            $badFileLookup = $badFileLookupOrUnused;
71        }
72        parent::__construct( $query, $moduleName, $prefix );
73        // This class is extended and therefor fallback to global state - T259960
74        $services = MediaWikiServices::getInstance();
75        $this->repoGroup = $repoGroup ?? $services->getRepoGroup();
76        $this->contentLanguage = $contentLanguage ?? $services->getContentLanguage();
77        $this->badFileLookup = $badFileLookup ?? $services->getBadFileLookup();
78    }
79
80    public function execute() {
81        $params = $this->extractRequestParams();
82
83        /** @var array<string,true> $prop */
84        $prop = array_fill_keys( $params['prop'], true );
85
86        $scale = $this->getScale( $params );
87
88        $opts = [
89            'version' => $params['metadataversion'],
90            'language' => $params['extmetadatalanguage'],
91            'multilang' => $params['extmetadatamultilang'],
92            'extmetadatafilter' => $params['extmetadatafilter'],
93            'revdelUser' => $this->getAuthority(),
94        ];
95
96        if ( isset( $params['badfilecontexttitle'] ) ) {
97            $badFileContextTitle = Title::newFromText( $params['badfilecontexttitle'] );
98            if ( !$badFileContextTitle || $badFileContextTitle->isExternal() ) {
99                $p = $this->getModulePrefix();
100                $this->dieWithError( [ 'apierror-bad-badfilecontexttitle', $p ], 'invalid-title' );
101            }
102        } else {
103            $badFileContextTitle = null;
104        }
105
106        $pageIds = $this->getPageSet()->getGoodAndMissingTitlesByNamespace();
107        if ( !empty( $pageIds[NS_FILE] ) ) {
108            $titles = array_keys( $pageIds[NS_FILE] );
109            asort( $titles ); // Ensure the order is always the same
110
111            $fromTitle = null;
112            if ( $params['continue'] !== null ) {
113                $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'string' ] );
114                $fromTitle = $cont[0];
115                $fromTimestamp = $cont[1];
116                // Filter out any titles before $fromTitle
117                foreach ( $titles as $key => $title ) {
118                    if ( $title < $fromTitle ) {
119                        unset( $titles[$key] );
120                    } else {
121                        break;
122                    }
123                }
124            }
125
126            $performer = $this->getAuthority();
127            $findTitles = array_map( static function ( $title ) use ( $performer ) {
128                return [
129                    'title' => $title,
130                    'private' => $performer,
131                ];
132            }, $titles );
133
134            if ( $params['localonly'] ) {
135                $images = $this->repoGroup->getLocalRepo()->findFiles( $findTitles );
136            } else {
137                $images = $this->repoGroup->findFiles( $findTitles );
138            }
139
140            $result = $this->getResult();
141            foreach ( $titles as $title ) {
142                $info = [];
143                $pageId = $pageIds[NS_FILE][$title];
144                // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
145                // $fromTimestamp declared when $fromTitle notnull
146                $start = $title === $fromTitle ? $fromTimestamp : $params['start'];
147
148                if ( !isset( $images[$title] ) ) {
149                    if ( isset( $prop['uploadwarning'] ) || isset( $prop['badfile'] ) ) {
150                        // uploadwarning and badfile need info about non-existing files
151                        $images[$title] = $this->repoGroup->getLocalRepo()->newFile( $title );
152                        // Doesn't exist, so set an empty image repository
153                        $info['imagerepository'] = '';
154                    } else {
155                        $result->addValue(
156                            [ 'query', 'pages', (int)$pageId ],
157                            'imagerepository', ''
158                        );
159                        // The above can't fail because it doesn't increase the result size
160                        continue;
161                    }
162                }
163
164                /** @var File $img */
165                $img = $images[$title];
166
167                if ( self::getTransformCount() >= self::TRANSFORM_LIMIT ) {
168                    if ( count( $pageIds[NS_FILE] ) == 1 ) {
169                        // See the 'the user is screwed' comment below
170                        $this->setContinueEnumParameter( 'start',
171                            $start ?? wfTimestamp( TS::ISO_8601, $img->getTimestamp() )
172                        );
173                    } else {
174                        $this->setContinueEnumParameter( 'continue',
175                            $this->getContinueStr( $img, $start ) );
176                    }
177                    break;
178                }
179
180                if ( !isset( $info['imagerepository'] ) ) {
181                    $info['imagerepository'] = $img->getRepoName();
182                }
183                if ( isset( $prop['badfile'] ) ) {
184                    $info['badfile'] = (bool)$this->badFileLookup->isBadFile( $title, $badFileContextTitle );
185                }
186
187                // Use ApiResult::IGNORE_CONFLICT_KEYS, the module is extended and the value can be set twice (T402438)
188                $fit = $result->addValue( [ 'query', 'pages' ], (int)$pageId, $info, ApiResult::IGNORE_CONFLICT_KEYS );
189                if ( !$fit ) {
190                    if ( count( $pageIds[NS_FILE] ) == 1 ) {
191                        // The user is screwed. imageinfo can't be solely
192                        // responsible for exceeding the limit in this case,
193                        // so set a query-continue that just returns the same
194                        // thing again. When the violating queries have been
195                        // out-continued, the result will get through
196                        $this->setContinueEnumParameter( 'start',
197                            $start ?? wfTimestamp( TS::ISO_8601, $img->getTimestamp() )
198                        );
199                    } else {
200                        $this->setContinueEnumParameter( 'continue',
201                            $this->getContinueStr( $img, $start ) );
202                    }
203                    break;
204                }
205
206                // Check if we can make the requested thumbnail, and get transform parameters.
207                $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
208
209                // Parser::makeImage always sets a targetlang, usually based on the language
210                // the content is in.  To support Parsoid's standalone mode, overload the badfilecontexttitle
211                // to also set the targetlang based on the page language.  Don't add this unless we're
212                // already scaling since a set $finalThumbParams usually expects a width.
213                if ( $badFileContextTitle && $finalThumbParams ) {
214                    $finalThumbParams['targetlang'] = $badFileContextTitle->getPageLanguage()->getCode();
215                }
216
217                // Get information about the current version first
218                // Check that the current version is within the start-end boundaries
219                $gotOne = false;
220                if (
221                    ( $start === null || $img->getTimestamp() <= $start ) &&
222                    ( $params['end'] === null || $img->getTimestamp() >= $params['end'] )
223                ) {
224                    $gotOne = true;
225
226                    $fit = $this->addPageSubItem( $pageId,
227                        static::getInfo( $img, $prop, $result,
228                            $finalThumbParams, $opts
229                        )
230                    );
231                    if ( !$fit ) {
232                        if ( count( $pageIds[NS_FILE] ) == 1 ) {
233                            // See the 'the user is screwed' comment above
234                            $this->setContinueEnumParameter( 'start',
235                                wfTimestamp( TS::ISO_8601, $img->getTimestamp() ) );
236                        } else {
237                            $this->setContinueEnumParameter( 'continue',
238                                $this->getContinueStr( $img ) );
239                        }
240                        break;
241                    }
242                }
243
244                // Now get the old revisions
245                // Get one more to facilitate query-continue functionality
246                $count = ( $gotOne ? 1 : 0 );
247                $oldies = $img->getHistory( $params['limit'] - $count + 1, $start, $params['end'] );
248                /** @var File $oldie */
249                foreach ( $oldies as $oldie ) {
250                    if ( ++$count > $params['limit'] ) {
251                        // We've reached the extra one which shows that there are
252                        // additional pages to be had. Stop here...
253                        // Only set a query-continue if there was only one title
254                        if ( count( $pageIds[NS_FILE] ) == 1 ) {
255                            $this->setContinueEnumParameter( 'start',
256                                wfTimestamp( TS::ISO_8601, $oldie->getTimestamp() ) );
257                        }
258                        break;
259                    }
260                    $fit = self::getTransformCount() < self::TRANSFORM_LIMIT &&
261                        $this->addPageSubItem( $pageId,
262                            static::getInfo( $oldie, $prop, $result,
263                                $finalThumbParams, $opts
264                            )
265                        );
266                    if ( !$fit ) {
267                        if ( count( $pageIds[NS_FILE] ) == 1 ) {
268                            $this->setContinueEnumParameter( 'start',
269                                wfTimestamp( TS::ISO_8601, $oldie->getTimestamp() ) );
270                        } else {
271                            $this->setContinueEnumParameter( 'continue',
272                                $this->getContinueStr( $oldie ) );
273                        }
274                        break;
275                    }
276                }
277                if ( !$fit ) {
278                    break;
279                }
280            }
281        }
282    }
283
284    /**
285     * From parameters, construct a 'scale' array
286     * @param array $params Parameters passed to api.
287     * @return array|null Key-val array of 'width' and 'height', or null
288     */
289    public function getScale( $params ) {
290        if ( $params['urlwidth'] != -1 ) {
291            return [ 'width' => $params['urlwidth'], 'height' => $params['urlheight'] ];
292        } elseif ( $params['urlheight'] != -1 ) {
293            // Height is specified but width isn't
294            // Don't set $scale['width']; this signals mergeThumbParams() to fill it with the image's width
295            return [ 'height' => $params['urlheight'] ];
296        } elseif ( $params['urlparam'] ) {
297            // Audio files might not have a width/height.
298            return [];
299        } else {
300            return null;
301        }
302    }
303
304    /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
305     *
306     * We do this later than getScale, since we need the image
307     * to know which handler, since handlers can make their own parameters.
308     * @param File $image Image that params are for.
309     * @param array|null $thumbParams Thumbnail parameters from getScale
310     * @param string $otherParams String of otherParams (iiurlparam).
311     * @return array|null Array of parameters for transform.
312     */
313    protected function mergeThumbParams( $image, $thumbParams, $otherParams ) {
314        if ( $thumbParams === null ) {
315            // No scaling requested
316            return null;
317        }
318        if ( !isset( $thumbParams['width'] ) && isset( $thumbParams['height'] ) ) {
319            // We want to limit only by height in this situation, so pass the
320            // image's full width as the limiting width. But some file types
321            // don't have a width of their own, or are scalable, so pick
322            // something arbitrary so thumbnailing the default icon works.
323            if ( $image->getWidth() <= 0 || $image->isVectorized() ) {
324                $thumbParams['width'] =
325                    max( $this->getConfig()->get( MainConfigNames::ThumbLimits ) );
326            } else {
327                $thumbParams['width'] = $image->getWidth();
328            }
329        }
330
331        if ( !$otherParams ) {
332            $this->checkParameterNormalise( $image, $thumbParams );
333            return $thumbParams;
334        }
335        $p = $this->getModulePrefix();
336
337        $h = $image->getHandler();
338        if ( !$h ) {
339            $this->addWarning( [ 'apiwarn-nothumb-noimagehandler', wfEscapeWikiText( $image->getName() ) ] );
340
341            return $thumbParams;
342        }
343
344        $paramList = $h->parseParamString( $otherParams );
345        if ( !$paramList ) {
346            // Just set a warning (instead of dieWithError), as in many cases
347            // we could still render the image using width and height parameters,
348            // and this type of thing could happen between different versions of
349            // handlers.
350            $this->addWarning( [ 'apiwarn-badurlparam', $p, wfEscapeWikiText( $image->getName() ) ] );
351            $this->checkParameterNormalise( $image, $thumbParams );
352            return $thumbParams;
353        }
354
355        if (
356            isset( $paramList['width'] ) && isset( $thumbParams['width'] ) &&
357            (int)$paramList['width'] != (int)$thumbParams['width']
358        ) {
359            $this->addWarning(
360                [ 'apiwarn-urlparamwidth', $p, $paramList['width'], $thumbParams['width'] ]
361            );
362        }
363
364        foreach ( $paramList as $name => $value ) {
365            if ( !$h->validateParam( $name, $value ) ) {
366                $this->dieWithError(
367                    [ 'apierror-invalidurlparam', $p, wfEscapeWikiText( $name ), wfEscapeWikiText( $value ) ]
368                );
369            }
370        }
371
372        $finalParams = $thumbParams + $paramList;
373        $this->checkParameterNormalise( $image, $finalParams );
374        return $finalParams;
375    }
376
377    /**
378     * Verify that the final image parameters can be normalised.
379     *
380     * This doesn't use the normalised parameters, since $file->transform
381     * expects the pre-normalised parameters, but doing the normalisation
382     * allows us to catch certain error conditions early (such as missing
383     * required parameter).
384     *
385     * @param File $image
386     * @param array $finalParams List of parameters to transform image with
387     */
388    protected function checkParameterNormalise( $image, $finalParams ) {
389        $h = $image->getHandler();
390        if ( !$h ) {
391            return;
392        }
393        // Note: normaliseParams modifies the array in place, but we aren't interested
394        // in the actual normalised version, only if we can actually normalise them,
395        // so we use the functions scope to throw away the normalisations.
396        if ( !$h->normaliseParams( $image, $finalParams ) ) {
397            $this->dieWithError( [ 'apierror-urlparamnormal', wfEscapeWikiText( $image->getName() ) ] );
398        }
399    }
400
401    /**
402     * Get result information for an image revision
403     *
404     * @param File $file
405     * @param array<string,true> $prop Array of properties to get (in the keys)
406     * @param ApiResult $result
407     * @param array|null $thumbParams Containing 'width' and 'height' items, or null
408     * @param array|false|string $opts Options for data fetching.
409     *   This is an array consisting of the keys:
410     *    'version': The metadata version for the metadata option
411     *    'language': The language for extmetadata property
412     *    'multilang': Return all translations in extmetadata property
413     *    'revdelUser': Authority to use when checking whether to show revision-deleted fields.
414     * @return array
415     */
416    public static function getInfo( $file, $prop, $result, $thumbParams = null, $opts = false ) {
417        $anyHidden = false;
418
419        $services = MediaWikiServices::getInstance();
420
421        if ( !$opts || is_string( $opts ) ) {
422            $opts = [
423                'version' => $opts ?: 'latest',
424                'language' => $services->getContentLanguage(),
425                'multilang' => false,
426                'extmetadatafilter' => [],
427                'revdelUser' => null,
428            ];
429        }
430        $version = $opts['version'];
431        $vals = [
432            ApiResult::META_TYPE => 'assoc',
433        ];
434
435        // Some information will be unavailable if the file does not exist. T221812
436        $exists = $file->exists();
437
438        // Timestamp is shown even if the file is revdelete'd in interface
439        // so do same here.
440        if ( isset( $prop['timestamp'] ) && $exists ) {
441            $vals['timestamp'] = wfTimestamp( TS::ISO_8601, $file->getTimestamp() );
442        }
443
444        // Handle external callers who don't pass revdelUser
445        if ( isset( $opts['revdelUser'] ) && $opts['revdelUser'] ) {
446            $revdelUser = $opts['revdelUser'];
447            $canShowField = static function ( $field ) use ( $file, $revdelUser ) {
448                return $file->userCan( $field, $revdelUser );
449            };
450        } else {
451            $canShowField = static function ( $field ) use ( $file ) {
452                return !$file->isDeleted( $field );
453            };
454        }
455
456        $user = isset( $prop['user'] );
457        $userid = isset( $prop['userid'] );
458
459        if ( ( $user || $userid ) && $exists ) {
460            if ( $file->isDeleted( File::DELETED_USER ) ) {
461                $vals['userhidden'] = true;
462                $anyHidden = true;
463            }
464            if ( $canShowField( File::DELETED_USER ) ) {
465                // Already checked if the field can be show
466                $uploader = $file->getUploader( File::RAW );
467                if ( $user ) {
468                    $vals['user'] = $uploader ? $uploader->getName() : '';
469                }
470                if ( $userid ) {
471                    $vals['userid'] = $uploader ? $uploader->getId() : 0;
472                }
473                if ( $uploader && $services->getUserNameUtils()->isTemp( $uploader->getName() ) ) {
474                    $vals['temp'] = true;
475                }
476                if ( $uploader && !$uploader->isRegistered() ) {
477                    $vals['anon'] = true;
478                }
479            }
480        }
481
482        // This is shown even if the file is revdelete'd in interface
483        // so do same here.
484        if ( ( isset( $prop['size'] ) || isset( $prop['dimensions'] ) ) && $exists ) {
485            $vals['size'] = (int)$file->getSize();
486            $vals['width'] = (int)$file->getWidth();
487            $vals['height'] = (int)$file->getHeight();
488
489            $pageCount = $file->pageCount();
490            if ( $pageCount !== false ) {
491                $vals['pagecount'] = $pageCount;
492            }
493
494            // length as in how many seconds long a video is.
495            $length = $file->getLength();
496            if ( $length ) {
497                // Call it duration, because "length" can be ambiguous.
498                $vals['duration'] = (float)$length;
499            }
500        }
501
502        $pcomment = isset( $prop['parsedcomment'] );
503        $comment = isset( $prop['comment'] );
504
505        if ( ( $pcomment || $comment ) && $exists ) {
506            if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
507                $vals['commenthidden'] = true;
508                $anyHidden = true;
509            }
510            if ( $canShowField( File::DELETED_COMMENT ) ) {
511                if ( $pcomment ) {
512                    $vals['parsedcomment'] = $services->getCommentFormatter()->format(
513                        $file->getDescription( File::RAW ), $file->getTitle() );
514                }
515                if ( $comment ) {
516                    $vals['comment'] = $file->getDescription( File::RAW );
517                }
518            }
519        }
520
521        $canonicaltitle = isset( $prop['canonicaltitle'] );
522        $url = isset( $prop['url'] );
523        $sha1 = isset( $prop['sha1'] );
524        $meta = isset( $prop['metadata'] );
525        $extmetadata = isset( $prop['extmetadata'] );
526        $commonmeta = isset( $prop['commonmetadata'] );
527        $mime = isset( $prop['mime'] );
528        $mediatype = isset( $prop['mediatype'] );
529        $archive = isset( $prop['archivename'] );
530        $bitdepth = isset( $prop['bitdepth'] );
531        $uploadwarning = isset( $prop['uploadwarning'] );
532
533        if ( $uploadwarning ) {
534            $vals['html'] = SpecialUpload::getExistsWarning( UploadBase::getExistsWarning( $file ) );
535        }
536
537        if ( $file->isDeleted( File::DELETED_FILE ) ) {
538            $vals['filehidden'] = true;
539            $anyHidden = true;
540        }
541
542        if ( $anyHidden && $file->isDeleted( File::DELETED_RESTRICTED ) ) {
543            $vals['suppressed'] = true;
544        }
545
546        // Early return, tidier than indenting all following things one level
547        if ( isset( $opts['revdelUser'] ) && $opts['revdelUser']
548            && !$file->userCan( File::DELETED_FILE, $opts['revdelUser'] )
549        ) {
550            return $vals;
551        } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
552            return $vals;
553        }
554
555        if ( $canonicaltitle ) {
556            $vals['canonicaltitle'] = $file->getTitle()->getPrefixedText();
557        }
558
559        if ( $url ) {
560            $urlUtils = $services->getUrlUtils();
561
562            if ( $exists ) {
563                if ( $thumbParams !== null ) {
564                    $thumbParams['requestProvenance'] = 'imageinfo';
565                    $mto = $file->transform( $thumbParams );
566                    self::$transformCount++;
567                    if ( $mto && !$mto->isError() ) {
568                        $vals['thumburl'] = (string)$urlUtils->expand( $mto->getUrl(), PROTO_CURRENT );
569
570                        // T25834 - If the URLs are the same, we haven't resized it, so shouldn't give the wanted
571                        // thumbnail sizes for the thumbnail actual size
572                        if ( $mto->getUrl() !== $file->getUrl() ) {
573                            $vals['thumbwidth'] = (int)$mto->getWidth();
574                            $vals['thumbheight'] = (int)$mto->getHeight();
575                        } else {
576                            $vals['thumbwidth'] = (int)$file->getWidth();
577                            $vals['thumbheight'] = (int)$file->getHeight();
578                        }
579
580                        if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
581                            [ , $mime ] = $file->getHandler()->getThumbType(
582                                $mto->getExtension(), $file->getMimeType(), $thumbParams );
583                            $vals['thumbmime'] = $mime;
584                        }
585                        // Report srcset parameters
586                        Linker::processResponsiveImages( $file, $mto, [
587                            'width' => $vals['thumbwidth'],
588                            'height' => $vals['thumbheight']
589                        ] + $thumbParams );
590                        foreach ( $mto->responsiveUrls as $density => $url ) {
591                            $vals['responsiveUrls'][$density] = (string)$urlUtils->expand( $url, PROTO_CURRENT );
592                        }
593                    } elseif ( $mto && $mto->isError() ) {
594                        /** @var MediaTransformError $mto */
595                        '@phan-var MediaTransformError $mto';
596                        $vals['thumberror'] = $mto->toText();
597                    }
598                }
599                $vals['url'] = (string)$urlUtils->expand( $file->appendRequestProvenance( $file->getFullUrl(), [
600                    'format' => 'original',
601                    'generator' => 'imageinfo',
602                ] ), PROTO_CURRENT );
603            }
604            $vals['descriptionurl'] = (string)$urlUtils->expand( $file->getDescriptionUrl(), PROTO_CURRENT );
605
606            $shortDescriptionUrl = $file->getDescriptionShortUrl();
607            if ( $shortDescriptionUrl !== null ) {
608                $vals['descriptionshorturl'] = (string)$urlUtils->expand( $shortDescriptionUrl, PROTO_CURRENT );
609            }
610        }
611
612        if ( !$exists ) {
613            $vals['filemissing'] = true;
614        }
615
616        if ( $sha1 && $exists ) {
617            $vals['sha1'] = \Wikimedia\base_convert( $file->getSha1(), 36, 16, 40 );
618        }
619
620        if ( $meta && $exists ) {
621            $metadata = $file->getMetadataArray();
622            if ( $metadata && $version !== 'latest' ) {
623                $metadata = $file->convertMetadataVersion( $metadata, $version );
624            }
625            $vals['metadata'] = $metadata ? static::processMetaData( $metadata, $result ) : null;
626        }
627        if ( $commonmeta && $exists ) {
628            $metaArray = $file->getCommonMetaArray();
629            $vals['commonmetadata'] = $metaArray ? static::processMetaData( $metaArray, $result ) : [];
630        }
631
632        if ( $extmetadata && $exists ) {
633            // Note, this should return an array where all the keys
634            // start with a letter, and all the values are strings.
635            // Thus there should be no issue with format=xml.
636            $format = new FormatMetadata;
637            $format->setSingleLanguage( !$opts['multilang'] );
638            // @phan-suppress-next-line PhanUndeclaredMethod
639            $format->getContext()->setLanguage( $opts['language'] );
640            $extmetaArray = $format->fetchExtendedMetadata( $file );
641            if ( $opts['extmetadatafilter'] ) {
642                $extmetaArray = array_intersect_key(
643                    $extmetaArray, array_fill_keys( $opts['extmetadatafilter'], true )
644                );
645            }
646            $vals['extmetadata'] = $extmetaArray;
647        }
648
649        if ( $mime && $exists ) {
650            $vals['mime'] = $file->getMimeType();
651        }
652
653        if ( $mediatype && $exists ) {
654            $vals['mediatype'] = $file->getMediaType();
655        }
656
657        if ( $archive && $file->isOld() ) {
658            /** @var OldLocalFile $file */
659            '@phan-var OldLocalFile $file';
660            $vals['archivename'] = $file->getArchiveName();
661        }
662
663        if ( $bitdepth && $exists ) {
664            $vals['bitdepth'] = $file->getBitDepth();
665        }
666
667        return $vals;
668    }
669
670    /**
671     * Get the count of image transformations performed
672     *
673     * If this is >= TRANSFORM_LIMIT, you should probably stop processing images.
674     *
675     * @return int Count
676     */
677    protected static function getTransformCount() {
678        return self::$transformCount;
679    }
680
681    /**
682     * @param array $metadata
683     * @param ApiResult $result
684     * @return array[]
685     */
686    public static function processMetaData( $metadata, $result ) {
687        $retval = [];
688        if ( is_array( $metadata ) ) {
689            foreach ( $metadata as $key => $value ) {
690                $r = [
691                    'name' => $key,
692                    ApiResult::META_BC_BOOLS => [ 'value' ],
693                ];
694                if ( is_array( $value ) ) {
695                    $r['value'] = static::processMetaData( $value, $result );
696                } else {
697                    $r['value'] = $value;
698                }
699                $retval[] = $r;
700            }
701        }
702        ApiResult::setIndexedTagName( $retval, 'metadata' );
703
704        return $retval;
705    }
706
707    /** @inheritDoc */
708    public function getCacheMode( $params ) {
709        if ( $this->userCanSeeRevDel() ) {
710            return 'private';
711        }
712
713        return 'public';
714    }
715
716    /**
717     * @param File $img
718     * @param string|null $start
719     * @return string
720     */
721    protected function getContinueStr( $img, $start = null ) {
722        return $img->getOriginalTitle()->getDBkey() . '|' . ( $start ?? $img->getTimestamp() );
723    }
724
725    /** @inheritDoc */
726    public function getAllowedParams() {
727        return [
728            'prop' => [
729                ParamValidator::PARAM_ISMULTI => true,
730                ParamValidator::PARAM_DEFAULT => 'timestamp|user',
731                ParamValidator::PARAM_TYPE => static::getPropertyNames(),
732                ApiBase::PARAM_HELP_MSG_PER_VALUE => static::getPropertyMessages(),
733            ],
734            'limit' => [
735                ParamValidator::PARAM_TYPE => 'limit',
736                ParamValidator::PARAM_DEFAULT => 1,
737                IntegerDef::PARAM_MIN => 1,
738                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
739                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
740            ],
741            'start' => [
742                ParamValidator::PARAM_TYPE => 'timestamp'
743            ],
744            'end' => [
745                ParamValidator::PARAM_TYPE => 'timestamp'
746            ],
747            'urlwidth' => [
748                ParamValidator::PARAM_TYPE => 'integer',
749                ParamValidator::PARAM_DEFAULT => -1,
750                ApiBase::PARAM_HELP_MSG => [
751                    'apihelp-query+imageinfo-param-urlwidth',
752                    self::TRANSFORM_LIMIT,
753                ],
754            ],
755            'urlheight' => [
756                ParamValidator::PARAM_TYPE => 'integer',
757                ParamValidator::PARAM_DEFAULT => -1
758            ],
759            'metadataversion' => [
760                ParamValidator::PARAM_TYPE => 'string',
761                ParamValidator::PARAM_DEFAULT => '1',
762            ],
763            'extmetadatalanguage' => [
764                ParamValidator::PARAM_TYPE => 'string',
765                ParamValidator::PARAM_DEFAULT =>
766                    $this->contentLanguage->getCode(),
767            ],
768            'extmetadatamultilang' => [
769                ParamValidator::PARAM_TYPE => 'boolean',
770                ParamValidator::PARAM_DEFAULT => false,
771            ],
772            'extmetadatafilter' => [
773                ParamValidator::PARAM_TYPE => 'string',
774                ParamValidator::PARAM_ISMULTI => true,
775            ],
776            'urlparam' => [
777                ParamValidator::PARAM_DEFAULT => '',
778                ParamValidator::PARAM_TYPE => 'string',
779            ],
780            'badfilecontexttitle' => [
781                ParamValidator::PARAM_TYPE => 'string',
782            ],
783            'continue' => [
784                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
785            ],
786            'localonly' => [
787                ParamValidator::PARAM_TYPE => 'boolean',
788                ParamValidator::PARAM_DEFAULT => false,
789            ],
790        ];
791    }
792
793    /**
794     * Returns all possible parameters to iiprop
795     *
796     * @param string[] $filter List of properties to filter out
797     * @return string[]
798     */
799    public static function getPropertyNames( $filter = [] ) {
800        return array_keys( static::getPropertyMessages( $filter ) );
801    }
802
803    /**
804     * Returns messages for all possible parameters to iiprop
805     *
806     * @param string[] $filter List of properties to filter out
807     * @return array<string,string>
808     */
809    public static function getPropertyMessages( $filter = [] ) {
810        return array_diff_key(
811            [
812                'timestamp' => 'apihelp-query+imageinfo-paramvalue-prop-timestamp',
813                'user' => 'apihelp-query+imageinfo-paramvalue-prop-user',
814                'userid' => 'apihelp-query+imageinfo-paramvalue-prop-userid',
815                'comment' => 'apihelp-query+imageinfo-paramvalue-prop-comment',
816                'parsedcomment' => 'apihelp-query+imageinfo-paramvalue-prop-parsedcomment',
817                'canonicaltitle' => 'apihelp-query+imageinfo-paramvalue-prop-canonicaltitle',
818                'url' => 'apihelp-query+imageinfo-paramvalue-prop-url',
819                'size' => 'apihelp-query+imageinfo-paramvalue-prop-size',
820                'dimensions' => 'apihelp-query+imageinfo-paramvalue-prop-dimensions',
821                'sha1' => 'apihelp-query+imageinfo-paramvalue-prop-sha1',
822                'mime' => 'apihelp-query+imageinfo-paramvalue-prop-mime',
823                'thumbmime' => 'apihelp-query+imageinfo-paramvalue-prop-thumbmime',
824                'mediatype' => 'apihelp-query+imageinfo-paramvalue-prop-mediatype',
825                'metadata' => 'apihelp-query+imageinfo-paramvalue-prop-metadata',
826                'commonmetadata' => 'apihelp-query+imageinfo-paramvalue-prop-commonmetadata',
827                'extmetadata' => 'apihelp-query+imageinfo-paramvalue-prop-extmetadata',
828                'archivename' => 'apihelp-query+imageinfo-paramvalue-prop-archivename',
829                'bitdepth' => 'apihelp-query+imageinfo-paramvalue-prop-bitdepth',
830                'uploadwarning' => 'apihelp-query+imageinfo-paramvalue-prop-uploadwarning',
831                'badfile' => 'apihelp-query+imageinfo-paramvalue-prop-badfile',
832            ],
833            array_fill_keys( $filter, true )
834        );
835    }
836
837    /** @inheritDoc */
838    protected function getExamplesMessages() {
839        return [
840            'action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo'
841                => 'apihelp-query+imageinfo-example-simple',
842            'action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&' .
843                'iiend=2007-12-31T23:59:59Z&iiprop=timestamp|user|url'
844                => 'apihelp-query+imageinfo-example-dated',
845        ];
846    }
847
848    /** @inheritDoc */
849    public function getHelpUrls() {
850        return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Imageinfo';
851    }
852}
853
854/** @deprecated class alias since 1.43 */
855class_alias( ApiQueryImageInfo::class, 'ApiQueryImageInfo' );