MediaWiki master
ApiQueryImageInfo.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Api;
10
26use Wikimedia\Timestamp\TimestampFormat as TS;
27
34 public const TRANSFORM_LIMIT = 50;
36 private static $transformCount = 0;
37
38 private RepoGroup $repoGroup;
39 private Language $contentLanguage;
40 private BadFileLookup $badFileLookup;
41
50 public function __construct(
51 ApiQuery $query,
52 string $moduleName,
53 $prefixOrRepoGroup = null,
54 $repoGroupOrContentLanguage = null,
55 $contentLanguageOrBadFileLookup = null,
56 $badFileLookupOrUnused = null
57 ) {
58 // We allow a subclass to override the prefix, to create a related API module.
59 // The ObjectFactory is injecting the services without the prefix.
60 if ( !is_string( $prefixOrRepoGroup ) ) {
61 $prefix = 'ii';
62 $repoGroup = $prefixOrRepoGroup;
63 $contentLanguage = $repoGroupOrContentLanguage;
64 $badFileLookup = $contentLanguageOrBadFileLookup;
65 // $badFileLookupOrUnused is null in this case
66 } else {
67 $prefix = $prefixOrRepoGroup;
68 $repoGroup = $repoGroupOrContentLanguage;
69 $contentLanguage = $contentLanguageOrBadFileLookup;
70 $badFileLookup = $badFileLookupOrUnused;
71 }
72 parent::__construct( $query, $moduleName, $prefix );
73 // This class is extended and therefor fallback to global state - T259960
75 $this->repoGroup = $repoGroup ?? $services->getRepoGroup();
76 $this->contentLanguage = $contentLanguage ?? $services->getContentLanguage();
77 $this->badFileLookup = $badFileLookup ?? $services->getBadFileLookup();
78 }
79
80 public function execute() {
81 $params = $this->extractRequestParams();
82
84 $prop = array_fill_keys( $params['prop'], true );
85
86 $scale = $this->getScale( $params );
87
88 $opts = [
89 'version' => $params['metadataversion'],
90 'language' => $params['extmetadatalanguage'],
91 'multilang' => $params['extmetadatamultilang'],
92 'extmetadatafilter' => $params['extmetadatafilter'],
93 'revdelUser' => $this->getAuthority(),
94 ];
95
96 if ( isset( $params['badfilecontexttitle'] ) ) {
97 $badFileContextTitle = Title::newFromText( $params['badfilecontexttitle'] );
98 if ( !$badFileContextTitle || $badFileContextTitle->isExternal() ) {
99 $p = $this->getModulePrefix();
100 $this->dieWithError( [ 'apierror-bad-badfilecontexttitle', $p ], 'invalid-title' );
101 }
102 } else {
103 $badFileContextTitle = null;
104 }
105
106 $pageIds = $this->getPageSet()->getGoodAndMissingTitlesByNamespace();
107 if ( !empty( $pageIds[NS_FILE] ) ) {
108 $titles = array_keys( $pageIds[NS_FILE] );
109 asort( $titles ); // Ensure the order is always the same
110
111 $fromTitle = null;
112 if ( $params['continue'] !== null ) {
113 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'string' ] );
114 $fromTitle = $cont[0];
115 $fromTimestamp = $cont[1];
116 // Filter out any titles before $fromTitle
117 foreach ( $titles as $key => $title ) {
118 if ( $title < $fromTitle ) {
119 unset( $titles[$key] );
120 } else {
121 break;
122 }
123 }
124 }
125
126 $performer = $this->getAuthority();
127 $findTitles = array_map( static function ( $title ) use ( $performer ) {
128 return [
129 'title' => $title,
130 'private' => $performer,
131 ];
132 }, $titles );
133
134 if ( $params['localonly'] ) {
135 $images = $this->repoGroup->getLocalRepo()->findFiles( $findTitles );
136 } else {
137 $images = $this->repoGroup->findFiles( $findTitles );
138 }
139
140 $result = $this->getResult();
141 foreach ( $titles as $title ) {
142 $info = [];
143 $pageId = $pageIds[NS_FILE][$title];
144 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
145 // $fromTimestamp declared when $fromTitle notnull
146 $start = $title === $fromTitle ? $fromTimestamp : $params['start'];
147
148 if ( !isset( $images[$title] ) ) {
149 if ( isset( $prop['uploadwarning'] ) || isset( $prop['badfile'] ) ) {
150 // uploadwarning and badfile need info about non-existing files
151 $images[$title] = $this->repoGroup->getLocalRepo()->newFile( $title );
152 // Doesn't exist, so set an empty image repository
153 $info['imagerepository'] = '';
154 } else {
155 $result->addValue(
156 [ 'query', 'pages', (int)$pageId ],
157 'imagerepository', ''
158 );
159 // The above can't fail because it doesn't increase the result size
160 continue;
161 }
162 }
163
165 $img = $images[$title];
166
167 if ( self::getTransformCount() >= self::TRANSFORM_LIMIT ) {
168 if ( count( $pageIds[NS_FILE] ) == 1 ) {
169 // See the 'the user is screwed' comment below
170 $this->setContinueEnumParameter( 'start',
171 $start ?? wfTimestamp( TS::ISO_8601, $img->getTimestamp() )
172 );
173 } else {
174 $this->setContinueEnumParameter( 'continue',
175 $this->getContinueStr( $img, $start ) );
176 }
177 break;
178 }
179
180 if ( !isset( $info['imagerepository'] ) ) {
181 $info['imagerepository'] = $img->getRepoName();
182 }
183 if ( isset( $prop['badfile'] ) ) {
184 $info['badfile'] = (bool)$this->badFileLookup->isBadFile( $title, $badFileContextTitle );
185 }
186
187 // Use ApiResult::IGNORE_CONFLICT_KEYS, the module is extended and the value can be set twice (T402438)
188 $fit = $result->addValue( [ 'query', 'pages' ], (int)$pageId, $info, ApiResult::IGNORE_CONFLICT_KEYS );
189 if ( !$fit ) {
190 if ( count( $pageIds[NS_FILE] ) == 1 ) {
191 // The user is screwed. imageinfo can't be solely
192 // responsible for exceeding the limit in this case,
193 // so set a query-continue that just returns the same
194 // thing again. When the violating queries have been
195 // out-continued, the result will get through
196 $this->setContinueEnumParameter( 'start',
197 $start ?? wfTimestamp( TS::ISO_8601, $img->getTimestamp() )
198 );
199 } else {
200 $this->setContinueEnumParameter( 'continue',
201 $this->getContinueStr( $img, $start ) );
202 }
203 break;
204 }
205
206 // Check if we can make the requested thumbnail, and get transform parameters.
207 $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
208
209 // Parser::makeImage always sets a targetlang, usually based on the language
210 // the content is in. To support Parsoid's standalone mode, overload the badfilecontexttitle
211 // to also set the targetlang based on the page language. Don't add this unless we're
212 // already scaling since a set $finalThumbParams usually expects a width.
213 if ( $badFileContextTitle && $finalThumbParams ) {
214 $finalThumbParams['targetlang'] = $badFileContextTitle->getPageLanguage()->getCode();
215 }
216
217 // Get information about the current version first
218 // Check that the current version is within the start-end boundaries
219 $gotOne = false;
220 if (
221 ( $start === null || $img->getTimestamp() <= $start ) &&
222 ( $params['end'] === null || $img->getTimestamp() >= $params['end'] )
223 ) {
224 $gotOne = true;
225
226 $fit = $this->addPageSubItem( $pageId,
227 static::getInfo( $img, $prop, $result,
228 $finalThumbParams, $opts
229 )
230 );
231 if ( !$fit ) {
232 if ( count( $pageIds[NS_FILE] ) == 1 ) {
233 // See the 'the user is screwed' comment above
234 $this->setContinueEnumParameter( 'start',
235 wfTimestamp( TS::ISO_8601, $img->getTimestamp() ) );
236 } else {
237 $this->setContinueEnumParameter( 'continue',
238 $this->getContinueStr( $img ) );
239 }
240 break;
241 }
242 }
243
244 // Now get the old revisions
245 // Get one more to facilitate query-continue functionality
246 $count = ( $gotOne ? 1 : 0 );
247 $oldies = $img->getHistory( $params['limit'] - $count + 1, $start, $params['end'] );
249 foreach ( $oldies as $oldie ) {
250 if ( ++$count > $params['limit'] ) {
251 // We've reached the extra one which shows that there are
252 // additional pages to be had. Stop here...
253 // Only set a query-continue if there was only one title
254 if ( count( $pageIds[NS_FILE] ) == 1 ) {
255 $this->setContinueEnumParameter( 'start',
256 wfTimestamp( TS::ISO_8601, $oldie->getTimestamp() ) );
257 }
258 break;
259 }
260 $fit = self::getTransformCount() < self::TRANSFORM_LIMIT &&
261 $this->addPageSubItem( $pageId,
262 static::getInfo( $oldie, $prop, $result,
263 $finalThumbParams, $opts
264 )
265 );
266 if ( !$fit ) {
267 if ( count( $pageIds[NS_FILE] ) == 1 ) {
268 $this->setContinueEnumParameter( 'start',
269 wfTimestamp( TS::ISO_8601, $oldie->getTimestamp() ) );
270 } else {
271 $this->setContinueEnumParameter( 'continue',
272 $this->getContinueStr( $oldie ) );
273 }
274 break;
275 }
276 }
277 if ( !$fit ) {
278 break;
279 }
280 }
281 }
282 }
283
289 public function getScale( $params ) {
290 if ( $params['urlwidth'] != -1 ) {
291 return [ 'width' => $params['urlwidth'], 'height' => $params['urlheight'] ];
292 } elseif ( $params['urlheight'] != -1 ) {
293 // Height is specified but width isn't
294 // Don't set $scale['width']; this signals mergeThumbParams() to fill it with the image's width
295 return [ 'height' => $params['urlheight'] ];
296 } elseif ( $params['urlparam'] ) {
297 // Audio files might not have a width/height.
298 return [];
299 } else {
300 return null;
301 }
302 }
303
313 protected function mergeThumbParams( $image, $thumbParams, $otherParams ) {
314 if ( $thumbParams === null ) {
315 // No scaling requested
316 return null;
317 }
318 if ( !isset( $thumbParams['width'] ) && isset( $thumbParams['height'] ) ) {
319 // We want to limit only by height in this situation, so pass the
320 // image's full width as the limiting width. But some file types
321 // don't have a width of their own, or are scalable, so pick
322 // something arbitrary so thumbnailing the default icon works.
323 if ( $image->getWidth() <= 0 || $image->isVectorized() ) {
324 $thumbParams['width'] =
325 max( $this->getConfig()->get( MainConfigNames::ThumbLimits ) );
326 } else {
327 $thumbParams['width'] = $image->getWidth();
328 }
329 }
330
331 if ( !$otherParams ) {
332 $this->checkParameterNormalise( $image, $thumbParams );
333 return $thumbParams;
334 }
335 $p = $this->getModulePrefix();
336
337 $h = $image->getHandler();
338 if ( !$h ) {
339 $this->addWarning( [ 'apiwarn-nothumb-noimagehandler', wfEscapeWikiText( $image->getName() ) ] );
340
341 return $thumbParams;
342 }
343
344 $paramList = $h->parseParamString( $otherParams );
345 if ( !$paramList ) {
346 // Handlers require a trailing "-<n>px" width (e.g. "langde-40px").
347 // Synthesise the default thumbnail size so width-less variants parse;
348 // it is discarded again per-size for thumburls.
349 $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
350 $thumbKey = $userOptionsLookup->getDefaultOption( 'thumbsize' ) ?: 0;
351 $thumbWidth = $this->getConfig()->get( MainConfigNames::ThumbLimits )[ $thumbKey ];
352 $width = $thumbParams['width'] ?? $thumbWidth;
353 $paramList = $h->parseParamString( $otherParams . "-{$width}px" );
354 }
355 if ( !$paramList ) {
356 // Just set a warning (instead of dieWithError), as in many cases
357 // we could still render the image using width and height parameters,
358 // and this type of thing could happen between different versions of
359 // handlers.
360 $this->addWarning( [ 'apiwarn-badurlparam', $p, wfEscapeWikiText( $image->getName() ) ] );
361 $this->checkParameterNormalise( $image, $thumbParams );
362 return $thumbParams;
363 }
364
365 if (
366 isset( $paramList['width'] ) && isset( $thumbParams['width'] ) &&
367 (int)$paramList['width'] != (int)$thumbParams['width']
368 ) {
369 $this->addWarning(
370 [ 'apiwarn-urlparamwidth', $p, $paramList['width'], $thumbParams['width'] ]
371 );
372 }
373
374 foreach ( $paramList as $name => $value ) {
375 if ( !$h->validateParam( $name, $value ) ) {
376 $this->dieWithError(
377 [ 'apierror-invalidurlparam', $p, wfEscapeWikiText( $name ), wfEscapeWikiText( $value ) ]
378 );
379 }
380 }
381
382 $finalParams = $thumbParams + $paramList;
383 $this->checkParameterNormalise( $image, $finalParams );
384 return $finalParams;
385 }
386
398 protected function checkParameterNormalise( $image, $finalParams ) {
399 $h = $image->getHandler();
400 if ( !$h ) {
401 return;
402 }
403 // Note: normaliseParams modifies the array in place, but we aren't interested
404 // in the actual normalised version, only if we can actually normalise them,
405 // so we use the functions scope to throw away the normalisations.
406 if ( !$h->normaliseParams( $image, $finalParams ) ) {
407 $this->dieWithError( [ 'apierror-urlparamnormal', wfEscapeWikiText( $image->getName() ) ] );
408 }
409 }
410
426 public static function getInfo( $file, $prop, $result, $thumbParams = null, $opts = false ) {
427 $anyHidden = false;
428
429 $services = MediaWikiServices::getInstance();
430
431 if ( !$opts || is_string( $opts ) ) {
432 $opts = [
433 'version' => $opts ?: 'latest',
434 'language' => $services->getContentLanguage(),
435 'multilang' => false,
436 'extmetadatafilter' => [],
437 'revdelUser' => null,
438 ];
439 }
440 $version = $opts['version'];
441 $vals = [
442 ApiResult::META_TYPE => 'assoc',
443 ];
444
445 // Some information will be unavailable if the file does not exist. T221812
446 $exists = $file->exists();
447
448 // A file may have DB metadata even when the storage blob is missing
449 // (e.g. old file revisions with empty archive names). T221812 T239213 T426802
450 $hasDbMetadata = $exists
451 || ( $file instanceof OldLocalFile && $file->hasDbRecord() );
452
453 // Timestamp is shown even if the file is revdelete'd in interface
454 // so do same here.
455 if ( isset( $prop['timestamp'] ) && $hasDbMetadata ) {
456 $vals['timestamp'] = wfTimestamp( TS::ISO_8601, $file->getTimestamp() );
457 }
458
459 // Handle external callers who don't pass revdelUser
460 if ( isset( $opts['revdelUser'] ) && $opts['revdelUser'] ) {
461 $revdelUser = $opts['revdelUser'];
462 $canShowField = static function ( $field ) use ( $file, $revdelUser ) {
463 return $file->userCan( $field, $revdelUser );
464 };
465 } else {
466 $canShowField = static function ( $field ) use ( $file ) {
467 return !$file->isDeleted( $field );
468 };
469 }
470
471 $user = isset( $prop['user'] );
472 $userid = isset( $prop['userid'] );
473
474 if ( ( $user || $userid ) && $hasDbMetadata ) {
475 if ( $file->isDeleted( File::DELETED_USER ) ) {
476 $vals['userhidden'] = true;
477 $anyHidden = true;
478 }
479 if ( $canShowField( File::DELETED_USER ) ) {
480 // Already checked if the field can be show
481 $uploader = $file->getUploader( File::RAW );
482 if ( $user ) {
483 $vals['user'] = $uploader ? $uploader->getName() : '';
484 }
485 if ( $userid ) {
486 $vals['userid'] = $uploader ? $uploader->getId() : 0;
487 }
488 if ( $uploader && $services->getUserNameUtils()->isTemp( $uploader->getName() ) ) {
489 $vals['temp'] = true;
490 }
491 if ( $uploader && !$uploader->isRegistered() ) {
492 $vals['anon'] = true;
493 }
494 }
495 }
496
497 // This is shown even if the file is revdelete'd in interface
498 // so do same here.
499 if ( ( isset( $prop['size'] ) || isset( $prop['dimensions'] ) ) && $hasDbMetadata ) {
500 $vals['size'] = (int)$file->getSize();
501 $vals['width'] = (int)$file->getWidth();
502 $vals['height'] = (int)$file->getHeight();
503
504 // pageCount and duration require the file handler which may
505 // access the file blob, so they need the file to exist. T221812
506 if ( $exists ) {
507 $pageCount = $file->pageCount();
508 if ( $pageCount !== false ) {
509 $vals['pagecount'] = $pageCount;
510 }
511
512 // length as in how many seconds long a video is.
513 $length = $file->getLength();
514 if ( $length ) {
515 // Call it duration, because "length" can be ambiguous.
516 $vals['duration'] = (float)$length;
517 }
518 }
519 }
520
521 $pcomment = isset( $prop['parsedcomment'] );
522 $comment = isset( $prop['comment'] );
523
524 if ( ( $pcomment || $comment ) && $hasDbMetadata ) {
525 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
526 $vals['commenthidden'] = true;
527 $anyHidden = true;
528 }
529 if ( $canShowField( File::DELETED_COMMENT ) ) {
530 if ( $pcomment ) {
531 $vals['parsedcomment'] = $services->getCommentFormatter()->format(
532 $file->getDescription( File::RAW ), $file->getTitle() );
533 }
534 if ( $comment ) {
535 $vals['comment'] = $file->getDescription( File::RAW );
536 }
537 }
538 }
539
540 $canonicaltitle = isset( $prop['canonicaltitle'] );
541 $url = isset( $prop['url'] );
542 $sha1 = isset( $prop['sha1'] );
543 $meta = isset( $prop['metadata'] );
544 $extmetadata = isset( $prop['extmetadata'] );
545 $commonmeta = isset( $prop['commonmetadata'] );
546 $mime = isset( $prop['mime'] );
547 $mediatype = isset( $prop['mediatype'] );
548 $archive = isset( $prop['archivename'] );
549 $bitdepth = isset( $prop['bitdepth'] );
550 $uploadwarning = isset( $prop['uploadwarning'] );
551
552 if ( $uploadwarning ) {
553 $vals['html'] = SpecialUpload::getExistsWarning( UploadBase::getExistsWarning( $file ) );
554 }
555
556 if ( $file->isDeleted( File::DELETED_FILE ) ) {
557 $vals['filehidden'] = true;
558 $anyHidden = true;
559 }
560
561 if ( $anyHidden && $file->isDeleted( File::DELETED_RESTRICTED ) ) {
562 $vals['suppressed'] = true;
563 }
564
565 // Early return, tidier than indenting all following things one level
566 if ( isset( $opts['revdelUser'] ) && $opts['revdelUser']
567 && !$file->userCan( File::DELETED_FILE, $opts['revdelUser'] )
568 ) {
569 return $vals;
570 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
571 return $vals;
572 }
573
574 if ( $canonicaltitle ) {
575 $vals['canonicaltitle'] = $file->getTitle()->getPrefixedText();
576 }
577
578 if ( $url ) {
579 $urlUtils = $services->getUrlUtils();
580
581 if ( $exists ) {
582 if ( $thumbParams !== null ) {
583 $thumbParams['requestProvenance'] = 'imageinfo';
584 $mto = $file->transform( $thumbParams );
585 self::$transformCount++;
586 if ( $mto && !$mto->isError() ) {
587 $vals['thumburl'] = (string)$urlUtils->expand( $mto->getUrl(), PROTO_CURRENT );
588
589 // T25834 - If the URLs are the same, we haven't resized it, so shouldn't give the wanted
590 // thumbnail sizes for the thumbnail actual size
591 if ( $mto->getUrl() !== $file->getUrl() ) {
592 $vals['thumbwidth'] = (int)$mto->getWidth();
593 $vals['thumbheight'] = (int)$mto->getHeight();
594 } else {
595 $vals['thumbwidth'] = (int)$file->getWidth();
596 $vals['thumbheight'] = (int)$file->getHeight();
597 }
598
599 if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
600 [ , $mime ] = $file->getHandler()->getThumbType(
601 $mto->getExtension(), $file->getMimeType(), $thumbParams );
602 $vals['thumbmime'] = $mime;
603 }
604 // Report srcset parameters
605 Linker::processResponsiveImages( $file, $mto, [
606 'width' => $vals['thumbwidth'],
607 'height' => $vals['thumbheight']
608 ] + $thumbParams );
609 foreach ( $mto->responsiveUrls as $density => $url ) {
610 $vals['responsiveUrls'][$density] = (string)$urlUtils->expand( $url, PROTO_CURRENT );
611 }
612
613 // Report HTML attributes (including 'extra' attributes
614 // like for lazy loading)
615 $vals['thumbattribs'] = $mto->getAttribs();
616 } elseif ( $mto && $mto->isError() ) {
618 '@phan-var MediaTransformError $mto';
619 $vals['thumberror'] = $mto->toText();
620 }
621 }
622 $vals['url'] = (string)$urlUtils->expand( $file->appendRequestProvenance( $file->getFullUrl(), [
623 'format' => 'original',
624 'generator' => 'imageinfo',
625 ] ), PROTO_CURRENT );
626 }
627 $vals['descriptionurl'] = (string)$urlUtils->expand( $file->getDescriptionUrl(), PROTO_CURRENT );
628
629 $shortDescriptionUrl = $file->getDescriptionShortUrl();
630 if ( $shortDescriptionUrl !== null ) {
631 $vals['descriptionshorturl'] = (string)$urlUtils->expand( $shortDescriptionUrl, PROTO_CURRENT );
632 }
633 }
634
635 if ( $exists && isset( $prop['thumburls'] ) ) {
636 $urlUtils = $services->getUrlUtils();
637 $config = $services->getMainConfig();
638 $thumbnailSteps = $config->get( MainConfigNames::ThumbnailSteps );
639 $sizes = [];
640 if ( is_array( $thumbnailSteps ) ) {
641 // When $wgThumbnailSteps is enabled
642 foreach ( $thumbnailSteps as $width ) {
643 $sizes[] = [ 'width' => $width ];
644 }
645 } else {
646 // Default to union of the default thumbnail size and $wgImageLimits
647 $userOptionsLookup = $services->getUserOptionsLookup();
648 $thumbKey = $userOptionsLookup->getDefaultOption( 'thumbsize' ) ?: 0;
649 $thumbWidth = $config->get( MainConfigNames::ThumbLimits )[ $thumbKey ];
650 $sizes[] = [ 'width' => $thumbWidth ];
651 if ( $config->get( MainConfigNames::ResponsiveImages ) ) {
652 $sizes[] = [ 'width' => $thumbWidth * 2 ];
653 }
654 foreach ( $config->get( MainConfigNames::ImageLimits ) as [ $width, $height ] ) {
655 $sizes[] = [ 'width' => $width, 'height' => $height ];
656 }
657 }
658 // Carry handler params (e.g. SVG "lang", PDF "page") into every
659 // suggested URL so they share the variant; only width/height vary.
660 $handlerParams = $thumbParams ? array_diff_key(
661 $thumbParams,
662 [ 'width' => true, 'height' => true, 'requestProvenance' => true ]
663 ) : [];
664 $vals['thumburls'] = [];
665 foreach ( $sizes as $size ) {
666 $size += $handlerParams;
667 $size['requestProvenance'] = 'imageinfo';
668 $size['usePhysicalSize'] = true;
669 $mto = $file->transform( $size );
670 if ( !$mto || $mto->isError() ) {
671 continue;
672 }
673 if ( isset( $vals['thumburls'][$mto->getWidth()] ) ) {
674 continue;
675 }
676 self::$transformCount++;
677 $thumburl = (string)$urlUtils->expand( $mto->getUrl(), PROTO_CURRENT );
678 $vals['thumburls'][$mto->getWidth()] = [
679 'url' => $thumburl,
680 'width' => $mto->getWidth(),
681 'height' => $mto->getHeight(),
682 ] + $mto->getAttribs();
683 }
684 }
685
686 if ( !$exists ) {
687 $vals['filemissing'] = true;
688 }
689
690 if ( $sha1 && $exists ) {
691 $vals['sha1'] = \Wikimedia\base_convert( $file->getSha1(), 36, 16, 40 );
692 }
693
694 if ( $meta && $exists ) {
695 $metadata = $file->getMetadataArray();
696 if ( $metadata && $version !== 'latest' ) {
697 $metadata = $file->convertMetadataVersion( $metadata, $version );
698 }
699 $vals['metadata'] = $metadata ? static::processMetaData( $metadata, $result ) : null;
700 }
701 if ( $commonmeta && $exists ) {
702 $metaArray = $file->getCommonMetaArray();
703 $vals['commonmetadata'] = $metaArray ? static::processMetaData( $metaArray, $result ) : [];
704 }
705
706 if ( $extmetadata && $exists ) {
707 // Note, this should return an array where all the keys
708 // start with a letter, and all the values are strings.
709 // Thus there should be no issue with format=xml.
710 $format = new FormatMetadata;
711 $format->setSingleLanguage( !$opts['multilang'] );
712 // @phan-suppress-next-line PhanUndeclaredMethod
713 $format->getContext()->setLanguage( $opts['language'] );
714 $extmetaArray = $format->fetchExtendedMetadata( $file );
715 if ( $opts['extmetadatafilter'] ) {
716 $extmetaArray = array_intersect_key(
717 $extmetaArray, array_fill_keys( $opts['extmetadatafilter'], true )
718 );
719 }
720 $vals['extmetadata'] = $extmetaArray;
721 }
722
723 if ( $mime && $exists ) {
724 $vals['mime'] = $file->getMimeType();
725 }
726
727 if ( $mediatype && $exists ) {
728 $vals['mediatype'] = $file->getMediaType();
729 }
730
731 if ( $archive && $file->isOld() ) {
733 '@phan-var OldLocalFile $file';
734 $vals['archivename'] = $file->getArchiveName();
735 }
736
737 if ( $bitdepth && $exists ) {
738 $vals['bitdepth'] = $file->getBitDepth();
739 }
740
741 return $vals;
742 }
743
751 protected static function getTransformCount() {
752 return self::$transformCount;
753 }
754
758 public static function resetTransformCountForUnitTest() {
759 self::$transformCount = 0;
760 }
761
767 public static function processMetaData( $metadata, $result ) {
768 $retval = [];
769 if ( is_array( $metadata ) ) {
770 foreach ( $metadata as $key => $value ) {
771 $r = [
772 'name' => $key,
773 ApiResult::META_BC_BOOLS => [ 'value' ],
774 ];
775 if ( is_array( $value ) ) {
776 $r['value'] = static::processMetaData( $value, $result );
777 } else {
778 $r['value'] = $value;
779 }
780 $retval[] = $r;
781 }
782 }
783 ApiResult::setIndexedTagName( $retval, 'metadata' );
784
785 return $retval;
786 }
787
789 public function getCacheMode( $params ) {
790 if ( $this->userCanSeeRevDel() ) {
791 return 'private';
792 }
793
794 return 'public';
795 }
796
802 protected function getContinueStr( $img, $start = null ) {
803 return $img->getOriginalTitle()->getDBkey() . '|' . ( $start ?? $img->getTimestamp() );
804 }
805
807 public function getAllowedParams() {
808 return [
809 'prop' => [
810 ParamValidator::PARAM_ISMULTI => true,
811 ParamValidator::PARAM_DEFAULT => 'timestamp|user',
812 ParamValidator::PARAM_TYPE => static::getPropertyNames(),
813 ApiBase::PARAM_HELP_MSG_PER_VALUE => static::getPropertyMessages(),
814 ],
815 'limit' => [
816 ParamValidator::PARAM_TYPE => 'limit',
817 ParamValidator::PARAM_DEFAULT => 1,
818 IntegerDef::PARAM_MIN => 1,
819 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
820 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
821 ],
822 'start' => [
823 ParamValidator::PARAM_TYPE => 'timestamp'
824 ],
825 'end' => [
826 ParamValidator::PARAM_TYPE => 'timestamp'
827 ],
828 'urlwidth' => [
829 ParamValidator::PARAM_TYPE => 'integer',
830 ParamValidator::PARAM_DEFAULT => -1,
832 'apihelp-query+imageinfo-param-urlwidth',
834 ],
835 ],
836 'urlheight' => [
837 ParamValidator::PARAM_TYPE => 'integer',
838 ParamValidator::PARAM_DEFAULT => -1
839 ],
840 'metadataversion' => [
841 ParamValidator::PARAM_TYPE => 'string',
842 ParamValidator::PARAM_DEFAULT => '1',
843 ],
844 'extmetadatalanguage' => [
845 ParamValidator::PARAM_TYPE => 'string',
846 ParamValidator::PARAM_DEFAULT =>
847 $this->contentLanguage->getCode(),
848 ],
849 'extmetadatamultilang' => [
850 ParamValidator::PARAM_TYPE => 'boolean',
851 ParamValidator::PARAM_DEFAULT => false,
852 ],
853 'extmetadatafilter' => [
854 ParamValidator::PARAM_TYPE => 'string',
855 ParamValidator::PARAM_ISMULTI => true,
856 ],
857 'urlparam' => [
858 ParamValidator::PARAM_DEFAULT => '',
859 ParamValidator::PARAM_TYPE => 'string',
860 ],
861 'badfilecontexttitle' => [
862 ParamValidator::PARAM_TYPE => 'string',
863 ],
864 'continue' => [
865 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
866 ],
867 'localonly' => [
868 ParamValidator::PARAM_TYPE => 'boolean',
869 ParamValidator::PARAM_DEFAULT => false,
870 ],
871 ];
872 }
873
880 public static function getPropertyNames( $filter = [] ) {
881 return array_keys( static::getPropertyMessages( $filter ) );
882 }
883
890 public static function getPropertyMessages( $filter = [] ) {
891 return array_diff_key(
892 [
893 'timestamp' => 'apihelp-query+imageinfo-paramvalue-prop-timestamp',
894 'user' => 'apihelp-query+imageinfo-paramvalue-prop-user',
895 'userid' => 'apihelp-query+imageinfo-paramvalue-prop-userid',
896 'comment' => 'apihelp-query+imageinfo-paramvalue-prop-comment',
897 'parsedcomment' => 'apihelp-query+imageinfo-paramvalue-prop-parsedcomment',
898 'canonicaltitle' => 'apihelp-query+imageinfo-paramvalue-prop-canonicaltitle',
899 'url' => 'apihelp-query+imageinfo-paramvalue-prop-url',
900 'size' => 'apihelp-query+imageinfo-paramvalue-prop-size',
901 'dimensions' => 'apihelp-query+imageinfo-paramvalue-prop-dimensions',
902 'sha1' => 'apihelp-query+imageinfo-paramvalue-prop-sha1',
903 'mime' => 'apihelp-query+imageinfo-paramvalue-prop-mime',
904 'thumbmime' => 'apihelp-query+imageinfo-paramvalue-prop-thumbmime',
905 'thumburls' => 'apihelp-query+imageinfo-paramvalue-prop-thumburls',
906 'mediatype' => 'apihelp-query+imageinfo-paramvalue-prop-mediatype',
907 'metadata' => 'apihelp-query+imageinfo-paramvalue-prop-metadata',
908 'commonmetadata' => 'apihelp-query+imageinfo-paramvalue-prop-commonmetadata',
909 'extmetadata' => 'apihelp-query+imageinfo-paramvalue-prop-extmetadata',
910 'archivename' => 'apihelp-query+imageinfo-paramvalue-prop-archivename',
911 'bitdepth' => 'apihelp-query+imageinfo-paramvalue-prop-bitdepth',
912 'uploadwarning' => 'apihelp-query+imageinfo-paramvalue-prop-uploadwarning',
913 'badfile' => 'apihelp-query+imageinfo-paramvalue-prop-badfile',
914 ],
915 array_fill_keys( $filter, true )
916 );
917 }
918
920 protected function getExamplesMessages() {
921 return [
922 'action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo'
923 => 'apihelp-query+imageinfo-example-simple',
924 'action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&' .
925 'iiend=2007-12-31T23:59:59Z&iiprop=timestamp|user|url'
926 => 'apihelp-query+imageinfo-example-dated',
927 ];
928 }
929
931 public function getHelpUrls() {
932 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Imageinfo';
933 }
934}
935
937class_alias( ApiQueryImageInfo::class, 'ApiQueryImageInfo' );
const NS_FILE
Definition Defines.php:57
const PROTO_CURRENT
Definition Defines.php:222
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1488
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:565
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1673
getResult()
Get the result object.
Definition ApiBase.php:695
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:205
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1405
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:165
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:232
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:836
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:230
This is a base class for all Query modules.
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
getPageSet()
Get the PageSet object to work on.
userCanSeeRevDel()
Check whether the current user has permission to view revision-deleted fields.
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
A query action to get image information and upload history.
checkParameterNormalise( $image, $finalParams)
Verify that the final image parameters can be normalised.
getHelpUrls()
Return links to more detailed help pages about the module.1.25, returning boolean false is deprecated...
mergeThumbParams( $image, $thumbParams, $otherParams)
Validate and merge scale parameters with handler thumb parameters, give error if invalid.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
static getPropertyNames( $filter=[])
Returns all possible parameters to iiprop.
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
static processMetaData( $metadata, $result)
__construct(ApiQuery $query, string $moduleName, $prefixOrRepoGroup=null, $repoGroupOrContentLanguage=null, $contentLanguageOrBadFileLookup=null, $badFileLookupOrUnused=null)
static getInfo( $file, $prop, $result, $thumbParams=null, $opts=false)
Get result information for an image revision.
static getPropertyMessages( $filter=[])
Returns messages for all possible parameters to iiprop.
static resetTransformCountForUnitTest()
Reset the count of image transformations performed.
getScale( $params)
From parameters, construct a 'scale' array.
static getTransformCount()
Get the count of image transformations performed.
getCacheMode( $params)
Get the cache mode for the data generated by this module.Override this in the module subclass....
This is the main query class.
Definition ApiQuery.php:36
const IGNORE_CONFLICT_KEYS
For addValue(), setValue() and similar functions, do allow override of conflicting keys.
Definition ApiResult.php:72
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
const META_BC_BOOLS
Key for the 'BC bools' metadata item.
const META_TYPE
Key for the 'type' metadata item.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:80
Old file in the oldimage table.
hasDbRecord()
Whether this file has a database record in the file metadata tables.
Prioritized list of file repositories.
Definition RepoGroup.php:30
Base class for language-specific code.
Definition Language.php:65
Some internal bits split of from Skin.php.
Definition Linker.php:48
A class containing constants representing the names of configuration variables.
const ImageLimits
Name constant for the ImageLimits setting, for use with Config::get()
const ResponsiveImages
Name constant for the ResponsiveImages setting, for use with Config::get()
const ThumbLimits
Name constant for the ThumbLimits setting, for use with Config::get()
const ThumbnailSteps
Name constant for the ThumbnailSteps setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Format Image metadata values into a human readable form.
setSingleLanguage( $val)
Trigger only outputting single language for multilanguage fields.
Basic media transform error class.
Form for uploading media files.
Represents a title within MediaWiki.
Definition Title.php:69
UploadBase and subclasses are the backend of MediaWiki's file uploads.
getDefaultOption(string $opt, ?UserIdentity $userIdentity=null)
Get a given default option value.
Service for formatting and validating API parameters.
Type definition for integer types.