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