Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
76.36% covered (warning)
76.36%
378 / 495
37.50% covered (danger)
37.50%
6 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryImageInfo
76.52% covered (warning)
76.52%
378 / 494
37.50% covered (danger)
37.50%
6 / 16
522.79
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
60.68% covered (warning)
60.68%
71 / 117
0.00% covered (danger)
0.00%
0 / 1
114.76
 getScale
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
4.05
 mergeThumbParams
61.54% covered (warning)
61.54%
24 / 39
0.00% covered (danger)
0.00%
0 / 1
30.57
 checkParameterNormalise
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
3.58
 getInfo
86.60% covered (warning)
86.60%
168 / 194
0.00% covered (danger)
0.00%
0 / 1
110.93
 getTransformCount
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 resetTransformCountForUnitTest
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%
26 / 26
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            // Handlers require a trailing "-<n>px" width (e.g. "langde-40px").
347            // Synthesise the default thumbnail size so width-less variants parse;
348            // it is discarded again per-size for thumburls.
349            $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
350            $thumbKey = $userOptionsLookup->getDefaultOption( 'thumbsize' ) ?: 0;
351            $thumbWidth = $this->getConfig()->get( MainConfigNames::ThumbLimits )[ $thumbKey ];
352            $width = $thumbParams['width'] ?? $thumbWidth;
353            $paramList = $h->parseParamString( $otherParams . "-{$width}px" );
354        }
355        if ( !$paramList ) {
356            // Just set a warning (instead of dieWithError), as in many cases
357            // we could still render the image using width and height parameters,
358            // and this type of thing could happen between different versions of
359            // handlers.
360            $this->addWarning( [ 'apiwarn-badurlparam', $p, wfEscapeWikiText( $image->getName() ) ] );
361            $this->checkParameterNormalise( $image, $thumbParams );
362            return $thumbParams;
363        }
364
365        if (
366            isset( $paramList['width'] ) && isset( $thumbParams['width'] ) &&
367            (int)$paramList['width'] != (int)$thumbParams['width']
368        ) {
369            $this->addWarning(
370                [ 'apiwarn-urlparamwidth', $p, $paramList['width'], $thumbParams['width'] ]
371            );
372        }
373
374        foreach ( $paramList as $name => $value ) {
375            if ( !$h->validateParam( $name, $value ) ) {
376                $this->dieWithError(
377                    [ 'apierror-invalidurlparam', $p, wfEscapeWikiText( $name ), wfEscapeWikiText( $value ) ]
378                );
379            }
380        }
381
382        $finalParams = $thumbParams + $paramList;
383        $this->checkParameterNormalise( $image, $finalParams );
384        return $finalParams;
385    }
386
387    /**
388     * Verify that the final image parameters can be normalised.
389     *
390     * This doesn't use the normalised parameters, since $file->transform
391     * expects the pre-normalised parameters, but doing the normalisation
392     * allows us to catch certain error conditions early (such as missing
393     * required parameter).
394     *
395     * @param File $image
396     * @param array $finalParams List of parameters to transform image with
397     */
398    protected function checkParameterNormalise( $image, $finalParams ) {
399        $h = $image->getHandler();
400        if ( !$h ) {
401            return;
402        }
403        // Note: normaliseParams modifies the array in place, but we aren't interested
404        // in the actual normalised version, only if we can actually normalise them,
405        // so we use the functions scope to throw away the normalisations.
406        if ( !$h->normaliseParams( $image, $finalParams ) ) {
407            $this->dieWithError( [ 'apierror-urlparamnormal', wfEscapeWikiText( $image->getName() ) ] );
408        }
409    }
410
411    /**
412     * Get result information for an image revision
413     *
414     * @param File $file
415     * @param array<string,true> $prop Array of properties to get (in the keys)
416     * @param ApiResult $result
417     * @param array|null $thumbParams Containing 'width' and 'height' items, or null
418     * @param array|false|string $opts Options for data fetching.
419     *   This is an array consisting of the keys:
420     *    'version': The metadata version for the metadata option
421     *    'language': The language for extmetadata property
422     *    'multilang': Return all translations in extmetadata property
423     *    'revdelUser': Authority to use when checking whether to show revision-deleted fields.
424     * @return array
425     */
426    public static function getInfo( $file, $prop, $result, $thumbParams = null, $opts = false ) {
427        $anyHidden = false;
428
429        $services = MediaWikiServices::getInstance();
430
431        if ( !$opts || is_string( $opts ) ) {
432            $opts = [
433                'version' => $opts ?: 'latest',
434                'language' => $services->getContentLanguage(),
435                'multilang' => false,
436                'extmetadatafilter' => [],
437                'revdelUser' => null,
438            ];
439        }
440        $version = $opts['version'];
441        $vals = [
442            ApiResult::META_TYPE => 'assoc',
443        ];
444
445        // Some information will be unavailable if the file does not exist. T221812
446        $exists = $file->exists();
447
448        // A file may have DB metadata even when the storage blob is missing
449        // (e.g. old file revisions with empty archive names). T221812 T239213 T426802
450        $hasDbMetadata = $exists
451            || ( $file instanceof OldLocalFile && $file->hasDbRecord() );
452
453        // Timestamp is shown even if the file is revdelete'd in interface
454        // so do same here.
455        if ( isset( $prop['timestamp'] ) && $hasDbMetadata ) {
456            $vals['timestamp'] = wfTimestamp( TS::ISO_8601, $file->getTimestamp() );
457        }
458
459        // Handle external callers who don't pass revdelUser
460        if ( isset( $opts['revdelUser'] ) && $opts['revdelUser'] ) {
461            $revdelUser = $opts['revdelUser'];
462            $canShowField = static function ( $field ) use ( $file, $revdelUser ) {
463                return $file->userCan( $field, $revdelUser );
464            };
465        } else {
466            $canShowField = static function ( $field ) use ( $file ) {
467                return !$file->isDeleted( $field );
468            };
469        }
470
471        $user = isset( $prop['user'] );
472        $userid = isset( $prop['userid'] );
473
474        if ( ( $user || $userid ) && $hasDbMetadata ) {
475            if ( $file->isDeleted( File::DELETED_USER ) ) {
476                $vals['userhidden'] = true;
477                $anyHidden = true;
478            }
479            if ( $canShowField( File::DELETED_USER ) ) {
480                // Already checked if the field can be show
481                $uploader = $file->getUploader( File::RAW );
482                if ( $user ) {
483                    $vals['user'] = $uploader ? $uploader->getName() : '';
484                }
485                if ( $userid ) {
486                    $vals['userid'] = $uploader ? $uploader->getId() : 0;
487                }
488                if ( $uploader && $services->getUserNameUtils()->isTemp( $uploader->getName() ) ) {
489                    $vals['temp'] = true;
490                }
491                if ( $uploader && !$uploader->isRegistered() ) {
492                    $vals['anon'] = true;
493                }
494            }
495        }
496
497        // This is shown even if the file is revdelete'd in interface
498        // so do same here.
499        if ( ( isset( $prop['size'] ) || isset( $prop['dimensions'] ) ) && $hasDbMetadata ) {
500            $vals['size'] = (int)$file->getSize();
501            $vals['width'] = (int)$file->getWidth();
502            $vals['height'] = (int)$file->getHeight();
503
504            // pageCount and duration require the file handler which may
505            // access the file blob, so they need the file to exist. T221812
506            if ( $exists ) {
507                $pageCount = $file->pageCount();
508                if ( $pageCount !== false ) {
509                    $vals['pagecount'] = $pageCount;
510                }
511
512                // length as in how many seconds long a video is.
513                $length = $file->getLength();
514                if ( $length ) {
515                    // Call it duration, because "length" can be ambiguous.
516                    $vals['duration'] = (float)$length;
517                }
518            }
519        }
520
521        $pcomment = isset( $prop['parsedcomment'] );
522        $comment = isset( $prop['comment'] );
523
524        if ( ( $pcomment || $comment ) && $hasDbMetadata ) {
525            if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
526                $vals['commenthidden'] = true;
527                $anyHidden = true;
528            }
529            if ( $canShowField( File::DELETED_COMMENT ) ) {
530                if ( $pcomment ) {
531                    $vals['parsedcomment'] = $services->getCommentFormatter()->format(
532                        $file->getDescription( File::RAW ), $file->getTitle() );
533                }
534                if ( $comment ) {
535                    $vals['comment'] = $file->getDescription( File::RAW );
536                }
537            }
538        }
539
540        $canonicaltitle = isset( $prop['canonicaltitle'] );
541        $url = isset( $prop['url'] );
542        $sha1 = isset( $prop['sha1'] );
543        $meta = isset( $prop['metadata'] );
544        $extmetadata = isset( $prop['extmetadata'] );
545        $commonmeta = isset( $prop['commonmetadata'] );
546        $mime = isset( $prop['mime'] );
547        $mediatype = isset( $prop['mediatype'] );
548        $archive = isset( $prop['archivename'] );
549        $bitdepth = isset( $prop['bitdepth'] );
550        $uploadwarning = isset( $prop['uploadwarning'] );
551
552        if ( $uploadwarning ) {
553            $vals['html'] = SpecialUpload::getExistsWarning( UploadBase::getExistsWarning( $file ) );
554        }
555
556        if ( $file->isDeleted( File::DELETED_FILE ) ) {
557            $vals['filehidden'] = true;
558            $anyHidden = true;
559        }
560
561        if ( $anyHidden && $file->isDeleted( File::DELETED_RESTRICTED ) ) {
562            $vals['suppressed'] = true;
563        }
564
565        // Early return, tidier than indenting all following things one level
566        if ( isset( $opts['revdelUser'] ) && $opts['revdelUser']
567            && !$file->userCan( File::DELETED_FILE, $opts['revdelUser'] )
568        ) {
569            return $vals;
570        } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
571            return $vals;
572        }
573
574        if ( $canonicaltitle ) {
575            $vals['canonicaltitle'] = $file->getTitle()->getPrefixedText();
576        }
577
578        if ( $url ) {
579            $urlUtils = $services->getUrlUtils();
580
581            if ( $exists ) {
582                if ( $thumbParams !== null ) {
583                    $thumbParams['requestProvenance'] = 'imageinfo';
584                    $mto = $file->transform( $thumbParams );
585                    self::$transformCount++;
586                    if ( $mto && !$mto->isError() ) {
587                        $vals['thumburl'] = (string)$urlUtils->expand( $mto->getUrl(), PROTO_CURRENT );
588
589                        // T25834 - If the URLs are the same, we haven't resized it, so shouldn't give the wanted
590                        // thumbnail sizes for the thumbnail actual size
591                        if ( $mto->getUrl() !== $file->getUrl() ) {
592                            $vals['thumbwidth'] = (int)$mto->getWidth();
593                            $vals['thumbheight'] = (int)$mto->getHeight();
594                        } else {
595                            $vals['thumbwidth'] = (int)$file->getWidth();
596                            $vals['thumbheight'] = (int)$file->getHeight();
597                        }
598
599                        if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
600                            [ , $mime ] = $file->getHandler()->getThumbType(
601                                $mto->getExtension(), $file->getMimeType(), $thumbParams );
602                            $vals['thumbmime'] = $mime;
603                        }
604                        // Report srcset parameters
605                        Linker::processResponsiveImages( $file, $mto, [
606                            'width' => $vals['thumbwidth'],
607                            'height' => $vals['thumbheight']
608                        ] + $thumbParams );
609                        foreach ( $mto->responsiveUrls as $density => $url ) {
610                            $vals['responsiveUrls'][$density] = (string)$urlUtils->expand( $url, PROTO_CURRENT );
611                        }
612
613                        // Report HTML attributes (including 'extra' attributes
614                        // like for lazy loading)
615                        $vals['thumbattribs'] = $mto->getAttribs();
616                    } elseif ( $mto && $mto->isError() ) {
617                        /** @var MediaTransformError $mto */
618                        '@phan-var MediaTransformError $mto';
619                        $vals['thumberror'] = $mto->toText();
620                    }
621                }
622                $vals['url'] = (string)$urlUtils->expand( $file->appendRequestProvenance( $file->getFullUrl(), [
623                    'format' => 'original',
624                    'generator' => 'imageinfo',
625                ] ), PROTO_CURRENT );
626            }
627            $vals['descriptionurl'] = (string)$urlUtils->expand( $file->getDescriptionUrl(), PROTO_CURRENT );
628
629            $shortDescriptionUrl = $file->getDescriptionShortUrl();
630            if ( $shortDescriptionUrl !== null ) {
631                $vals['descriptionshorturl'] = (string)$urlUtils->expand( $shortDescriptionUrl, PROTO_CURRENT );
632            }
633        }
634
635        if ( $exists && isset( $prop['thumburls'] ) ) {
636            $urlUtils = $services->getUrlUtils();
637            $config = $services->getMainConfig();
638            $thumbnailSteps = $config->get( MainConfigNames::ThumbnailSteps );
639            $sizes = [];
640            if ( is_array( $thumbnailSteps ) ) {
641                // When $wgThumbnailSteps is enabled
642                foreach ( $thumbnailSteps as $width ) {
643                    $sizes[] = [ 'width' => $width ];
644                }
645            } else {
646                // Default to union of the default thumbnail size and $wgImageLimits
647                $userOptionsLookup = $services->getUserOptionsLookup();
648                $thumbKey = $userOptionsLookup->getDefaultOption( 'thumbsize' ) ?: 0;
649                $thumbWidth = $config->get( MainConfigNames::ThumbLimits )[ $thumbKey ];
650                $sizes[] = [ 'width' => $thumbWidth ];
651                if ( $config->get( MainConfigNames::ResponsiveImages ) ) {
652                    $sizes[] = [ 'width' => $thumbWidth * 2 ];
653                }
654                foreach ( $config->get( MainConfigNames::ImageLimits ) as [ $width, $height ] ) {
655                    $sizes[] = [ 'width' => $width, 'height' => $height ];
656                }
657            }
658            // Carry handler params (e.g. SVG "lang", PDF "page") into every
659            // suggested URL so they share the variant; only width/height vary.
660            $handlerParams = $thumbParams ? array_diff_key(
661                $thumbParams,
662                [ 'width' => true, 'height' => true, 'requestProvenance' => true ]
663            ) : [];
664            $vals['thumburls'] = [];
665            foreach ( $sizes as $size ) {
666                $size += $handlerParams;
667                $size['requestProvenance'] = 'imageinfo';
668                $size['usePhysicalSize'] = true;
669                $mto = $file->transform( $size );
670                if ( !$mto || $mto->isError() ) {
671                    continue;
672                }
673                if ( isset( $vals['thumburls'][$mto->getWidth()] ) ) {
674                    continue;
675                }
676                self::$transformCount++;
677                $thumburl = (string)$urlUtils->expand( $mto->getUrl(), PROTO_CURRENT );
678                $vals['thumburls'][$mto->getWidth()] = [
679                    'url' => $thumburl,
680                    'width' => $mto->getWidth(),
681                    'height' => $mto->getHeight(),
682                ] + $mto->getAttribs();
683            }
684        }
685
686        if ( !$exists ) {
687            $vals['filemissing'] = true;
688        }
689
690        if ( $sha1 && $exists ) {
691            $vals['sha1'] = \Wikimedia\base_convert( $file->getSha1(), 36, 16, 40 );
692        }
693
694        if ( $meta && $exists ) {
695            $metadata = $file->getMetadataArray();
696            if ( $metadata && $version !== 'latest' ) {
697                $metadata = $file->convertMetadataVersion( $metadata, $version );
698            }
699            $vals['metadata'] = $metadata ? static::processMetaData( $metadata, $result ) : null;
700        }
701        if ( $commonmeta && $exists ) {
702            $metaArray = $file->getCommonMetaArray();
703            $vals['commonmetadata'] = $metaArray ? static::processMetaData( $metaArray, $result ) : [];
704        }
705
706        if ( $extmetadata && $exists ) {
707            // Note, this should return an array where all the keys
708            // start with a letter, and all the values are strings.
709            // Thus there should be no issue with format=xml.
710            $format = new FormatMetadata;
711            $format->setSingleLanguage( !$opts['multilang'] );
712            // @phan-suppress-next-line PhanUndeclaredMethod
713            $format->getContext()->setLanguage( $opts['language'] );
714            $extmetaArray = $format->fetchExtendedMetadata( $file );
715            if ( $opts['extmetadatafilter'] ) {
716                $extmetaArray = array_intersect_key(
717                    $extmetaArray, array_fill_keys( $opts['extmetadatafilter'], true )
718                );
719            }
720            $vals['extmetadata'] = $extmetaArray;
721        }
722
723        if ( $mime && $exists ) {
724            $vals['mime'] = $file->getMimeType();
725        }
726
727        if ( $mediatype && $exists ) {
728            $vals['mediatype'] = $file->getMediaType();
729        }
730
731        if ( $archive && $file->isOld() ) {
732            /** @var OldLocalFile $file */
733            '@phan-var OldLocalFile $file';
734            $vals['archivename'] = $file->getArchiveName();
735        }
736
737        if ( $bitdepth && $exists ) {
738            $vals['bitdepth'] = $file->getBitDepth();
739        }
740
741        return $vals;
742    }
743
744    /**
745     * Get the count of image transformations performed
746     *
747     * If this is >= TRANSFORM_LIMIT, you should probably stop processing images.
748     *
749     * @return int Count
750     */
751    protected static function getTransformCount() {
752        return self::$transformCount;
753    }
754
755    /**
756     * Reset the count of image transformations performed. Solely used for phpunit.
757     */
758    public static function resetTransformCountForUnitTest() {
759        self::$transformCount = 0;
760    }
761
762    /**
763     * @param array $metadata
764     * @param ApiResult $result
765     * @return array[]
766     */
767    public static function processMetaData( $metadata, $result ) {
768        $retval = [];
769        if ( is_array( $metadata ) ) {
770            foreach ( $metadata as $key => $value ) {
771                $r = [
772                    'name' => $key,
773                    ApiResult::META_BC_BOOLS => [ 'value' ],
774                ];
775                if ( is_array( $value ) ) {
776                    $r['value'] = static::processMetaData( $value, $result );
777                } else {
778                    $r['value'] = $value;
779                }
780                $retval[] = $r;
781            }
782        }
783        ApiResult::setIndexedTagName( $retval, 'metadata' );
784
785        return $retval;
786    }
787
788    /** @inheritDoc */
789    public function getCacheMode( $params ) {
790        if ( $this->userCanSeeRevDel() ) {
791            return 'private';
792        }
793
794        return 'public';
795    }
796
797    /**
798     * @param File $img
799     * @param string|null $start
800     * @return string
801     */
802    protected function getContinueStr( $img, $start = null ) {
803        return $img->getOriginalTitle()->getDBkey() . '|' . ( $start ?? $img->getTimestamp() );
804    }
805
806    /** @inheritDoc */
807    public function getAllowedParams() {
808        return [
809            'prop' => [
810                ParamValidator::PARAM_ISMULTI => true,
811                ParamValidator::PARAM_DEFAULT => 'timestamp|user',
812                ParamValidator::PARAM_TYPE => static::getPropertyNames(),
813                ApiBase::PARAM_HELP_MSG_PER_VALUE => static::getPropertyMessages(),
814            ],
815            'limit' => [
816                ParamValidator::PARAM_TYPE => 'limit',
817                ParamValidator::PARAM_DEFAULT => 1,
818                IntegerDef::PARAM_MIN => 1,
819                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
820                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
821            ],
822            'start' => [
823                ParamValidator::PARAM_TYPE => 'timestamp'
824            ],
825            'end' => [
826                ParamValidator::PARAM_TYPE => 'timestamp'
827            ],
828            'urlwidth' => [
829                ParamValidator::PARAM_TYPE => 'integer',
830                ParamValidator::PARAM_DEFAULT => -1,
831                ApiBase::PARAM_HELP_MSG => [
832                    'apihelp-query+imageinfo-param-urlwidth',
833                    self::TRANSFORM_LIMIT,
834                ],
835            ],
836            'urlheight' => [
837                ParamValidator::PARAM_TYPE => 'integer',
838                ParamValidator::PARAM_DEFAULT => -1
839            ],
840            'metadataversion' => [
841                ParamValidator::PARAM_TYPE => 'string',
842                ParamValidator::PARAM_DEFAULT => '1',
843            ],
844            'extmetadatalanguage' => [
845                ParamValidator::PARAM_TYPE => 'string',
846                ParamValidator::PARAM_DEFAULT =>
847                    $this->contentLanguage->getCode(),
848            ],
849            'extmetadatamultilang' => [
850                ParamValidator::PARAM_TYPE => 'boolean',
851                ParamValidator::PARAM_DEFAULT => false,
852            ],
853            'extmetadatafilter' => [
854                ParamValidator::PARAM_TYPE => 'string',
855                ParamValidator::PARAM_ISMULTI => true,
856            ],
857            'urlparam' => [
858                ParamValidator::PARAM_DEFAULT => '',
859                ParamValidator::PARAM_TYPE => 'string',
860            ],
861            'badfilecontexttitle' => [
862                ParamValidator::PARAM_TYPE => 'string',
863            ],
864            'continue' => [
865                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
866            ],
867            'localonly' => [
868                ParamValidator::PARAM_TYPE => 'boolean',
869                ParamValidator::PARAM_DEFAULT => false,
870            ],
871        ];
872    }
873
874    /**
875     * Returns all possible parameters to iiprop
876     *
877     * @param string[] $filter List of properties to filter out
878     * @return string[]
879     */
880    public static function getPropertyNames( $filter = [] ) {
881        return array_keys( static::getPropertyMessages( $filter ) );
882    }
883
884    /**
885     * Returns messages for all possible parameters to iiprop
886     *
887     * @param string[] $filter List of properties to filter out
888     * @return array<string,string>
889     */
890    public static function getPropertyMessages( $filter = [] ) {
891        return array_diff_key(
892            [
893                'timestamp' => 'apihelp-query+imageinfo-paramvalue-prop-timestamp',
894                'user' => 'apihelp-query+imageinfo-paramvalue-prop-user',
895                'userid' => 'apihelp-query+imageinfo-paramvalue-prop-userid',
896                'comment' => 'apihelp-query+imageinfo-paramvalue-prop-comment',
897                'parsedcomment' => 'apihelp-query+imageinfo-paramvalue-prop-parsedcomment',
898                'canonicaltitle' => 'apihelp-query+imageinfo-paramvalue-prop-canonicaltitle',
899                'url' => 'apihelp-query+imageinfo-paramvalue-prop-url',
900                'size' => 'apihelp-query+imageinfo-paramvalue-prop-size',
901                'dimensions' => 'apihelp-query+imageinfo-paramvalue-prop-dimensions',
902                'sha1' => 'apihelp-query+imageinfo-paramvalue-prop-sha1',
903                'mime' => 'apihelp-query+imageinfo-paramvalue-prop-mime',
904                'thumbmime' => 'apihelp-query+imageinfo-paramvalue-prop-thumbmime',
905                'thumburls' => 'apihelp-query+imageinfo-paramvalue-prop-thumburls',
906                'mediatype' => 'apihelp-query+imageinfo-paramvalue-prop-mediatype',
907                'metadata' => 'apihelp-query+imageinfo-paramvalue-prop-metadata',
908                'commonmetadata' => 'apihelp-query+imageinfo-paramvalue-prop-commonmetadata',
909                'extmetadata' => 'apihelp-query+imageinfo-paramvalue-prop-extmetadata',
910                'archivename' => 'apihelp-query+imageinfo-paramvalue-prop-archivename',
911                'bitdepth' => 'apihelp-query+imageinfo-paramvalue-prop-bitdepth',
912                'uploadwarning' => 'apihelp-query+imageinfo-paramvalue-prop-uploadwarning',
913                'badfile' => 'apihelp-query+imageinfo-paramvalue-prop-badfile',
914            ],
915            array_fill_keys( $filter, true )
916        );
917    }
918
919    /** @inheritDoc */
920    protected function getExamplesMessages() {
921        return [
922            'action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo'
923                => 'apihelp-query+imageinfo-example-simple',
924            'action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&' .
925                'iiend=2007-12-31T23:59:59Z&iiprop=timestamp|user|url'
926                => 'apihelp-query+imageinfo-example-dated',
927        ];
928    }
929
930    /** @inheritDoc */
931    public function getHelpUrls() {
932        return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Imageinfo';
933    }
934}
935
936/** @deprecated class alias since 1.43 */
937class_alias( ApiQueryImageInfo::class, 'ApiQueryImageInfo' );