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