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