Debian Codegraph @

includes/api/ApiQueryImageInfo.php

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