5 * Created on July 6, 2007
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * A query action to get image information and upload history.
32 class ApiQueryImageInfo
extends ApiQueryBase
{
33 const TRANSFORM_LIMIT
= 50;
34 private static $transformCount = 0;
36 public function __construct( ApiQuery
$query, $moduleName, $prefix = 'ii' ) {
37 // We allow a subclass to override the prefix, to create a related API
38 // module. Some other parts of MediaWiki construct this with a null
39 // $prefix, which used to be ignored when this only took two arguments
40 if ( is_null( $prefix ) ) {
43 parent
::__construct( $query, $moduleName, $prefix );
46 public function execute() {
47 $params = $this->extractRequestParams();
49 $prop = array_flip( $params['prop'] );
51 $scale = $this->getScale( $params );
54 'version' => $params['metadataversion'],
55 'language' => $params['extmetadatalanguage'],
56 'multilang' => $params['extmetadatamultilang'],
57 'extmetadatafilter' => $params['extmetadatafilter'],
58 'revdelUser' => $this->getUser(),
61 $pageIds = $this->getPageSet()->getAllTitlesByNamespace();
62 if ( !empty( $pageIds[NS_FILE
] ) ) {
63 $titles = array_keys( $pageIds[NS_FILE
] );
64 asort( $titles ); // Ensure the order is always the same
67 if ( !is_null( $params['continue'] ) ) {
68 $cont = explode( '|', $params['continue'] );
69 $this->dieContinueUsageIf( count( $cont ) != 2 );
70 $fromTitle = strval( $cont[0] );
71 $fromTimestamp = $cont[1];
72 // Filter out any titles before $fromTitle
73 foreach ( $titles as $key => $title ) {
74 if ( $title < $fromTitle ) {
75 unset( $titles[$key] );
82 $user = $this->getUser();
83 $findTitles = array_map( function ( $title ) use ( $user ) {
90 if ( $params['localonly'] ) {
91 $images = RepoGroup
::singleton()->getLocalRepo()->findFiles( $findTitles );
93 $images = RepoGroup
::singleton()->findFiles( $findTitles );
96 $result = $this->getResult();
97 foreach ( $titles as $title ) {
98 $pageId = $pageIds[NS_FILE
][$title];
99 $start = $title === $fromTitle ?
$fromTimestamp : $params['start'];
101 if ( !isset( $images[$title] ) ) {
102 if ( isset( $prop['uploadwarning'] ) ) {
103 // Uploadwarning needs info about non-existing files
104 $images[$title] = wfLocalFile( $title );
107 array( 'query', 'pages', intval( $pageId ) ),
108 'imagerepository', ''
110 // The above can't fail because it doesn't increase the result size
115 /** @var $img File */
116 $img = $images[$title];
118 if ( self
::getTransformCount() >= self
::TRANSFORM_LIMIT
) {
119 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
120 // See the 'the user is screwed' comment below
121 $this->setContinueEnumParameter( 'start',
122 $start !== null ?
$start : wfTimestamp( TS_ISO_8601
, $img->getTimestamp() )
125 $this->setContinueEnumParameter( 'continue',
126 $this->getContinueStr( $img, $start ) );
131 $fit = $result->addValue(
132 array( 'query', 'pages', intval( $pageId ) ),
133 'imagerepository', $img->getRepoName()
136 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
137 // The user is screwed. imageinfo can't be solely
138 // responsible for exceeding the limit in this case,
139 // so set a query-continue that just returns the same
140 // thing again. When the violating queries have been
141 // out-continued, the result will get through
142 $this->setContinueEnumParameter( 'start',
143 $start !== null ?
$start : wfTimestamp( TS_ISO_8601
, $img->getTimestamp() )
146 $this->setContinueEnumParameter( 'continue',
147 $this->getContinueStr( $img, $start ) );
152 // Check if we can make the requested thumbnail, and get transform parameters.
153 $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
155 // Get information about the current version first
156 // Check that the current version is within the start-end boundaries
159 ( is_null( $start ) ||
$img->getTimestamp() <= $start ) &&
160 ( is_null( $params['end'] ) ||
$img->getTimestamp() >= $params['end'] )
164 $fit = $this->addPageSubItem( $pageId,
165 self
::getInfo( $img, $prop, $result,
166 $finalThumbParams, $opts
170 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
171 // See the 'the user is screwed' comment above
172 $this->setContinueEnumParameter( 'start',
173 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
175 $this->setContinueEnumParameter( 'continue',
176 $this->getContinueStr( $img ) );
182 // Now get the old revisions
183 // Get one more to facilitate query-continue functionality
184 $count = ( $gotOne ?
1 : 0 );
185 $oldies = $img->getHistory( $params['limit'] - $count +
1, $start, $params['end'] );
186 /** @var $oldie File */
187 foreach ( $oldies as $oldie ) {
188 if ( ++
$count > $params['limit'] ) {
189 // We've reached the extra one which shows that there are
190 // additional pages to be had. Stop here...
191 // Only set a query-continue if there was only one title
192 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
193 $this->setContinueEnumParameter( 'start',
194 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
198 $fit = self
::getTransformCount() < self
::TRANSFORM_LIMIT
&&
199 $this->addPageSubItem( $pageId,
200 self
::getInfo( $oldie, $prop, $result,
201 $finalThumbParams, $opts
205 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
206 $this->setContinueEnumParameter( 'start',
207 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
209 $this->setContinueEnumParameter( 'continue',
210 $this->getContinueStr( $oldie ) );
223 * From parameters, construct a 'scale' array
224 * @param array $params Parameters passed to api.
225 * @return array|null Key-val array of 'width' and 'height', or null
227 public function getScale( $params ) {
228 $p = $this->getModulePrefix();
230 if ( $params['urlwidth'] != -1 ) {
232 $scale['width'] = $params['urlwidth'];
233 $scale['height'] = $params['urlheight'];
234 } elseif ( $params['urlheight'] != -1 ) {
235 // Height is specified but width isn't
236 // Don't set $scale['width']; this signals mergeThumbParams() to fill it with the image's width
238 $scale['height'] = $params['urlheight'];
241 if ( $params['urlparam'] ) {
242 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
249 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
251 * We do this later than getScale, since we need the image
252 * to know which handler, since handlers can make their own parameters.
253 * @param File $image Image that params are for.
254 * @param array $thumbParams Thumbnail parameters from getScale
255 * @param string $otherParams String of otherParams (iiurlparam).
256 * @return array Array of parameters for transform.
258 protected function mergeThumbParams( $image, $thumbParams, $otherParams ) {
259 if ( !isset( $thumbParams['width'] ) && isset( $thumbParams['height'] ) ) {
260 // We want to limit only by height in this situation, so pass the
261 // image's full width as the limiting width. But some file types
262 // don't have a width of their own, so pick something arbitrary so
263 // thumbnailing the default icon works.
264 if ( $image->getWidth() <= 0 ) {
265 $thumbParams['width'] = max( $this->getConfig()->get( 'ThumbLimits' ) );
267 $thumbParams['width'] = $image->getWidth();
271 if ( !$otherParams ) {
274 $p = $this->getModulePrefix();
276 $h = $image->getHandler();
278 $this->setWarning( 'Could not create thumbnail because ' .
279 $image->getName() . ' does not have an associated image handler' );
284 $paramList = $h->parseParamString( $otherParams );
286 // Just set a warning (instead of dieUsage), as in many cases
287 // we could still render the image using width and height parameters,
288 // and this type of thing could happen between different versions of
290 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
291 . '. Using only width and height' );
296 if ( isset( $paramList['width'] ) ) {
297 if ( intval( $paramList['width'] ) != intval( $thumbParams['width'] ) ) {
298 $this->setWarning( "Ignoring width value set in {$p}urlparam ({$paramList['width']}) "
299 . "in favor of width value derived from {$p}urlwidth/{$p}urlheight "
300 . "({$thumbParams['width']})" );
304 foreach ( $paramList as $name => $value ) {
305 if ( !$h->validateParam( $name, $value ) ) {
306 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
310 return $thumbParams +
$paramList;
314 * Get result information for an image revision
317 * @param array $prop Array of properties to get (in the keys)
318 * @param ApiResult $result
319 * @param array $thumbParams Containing 'width' and 'height' items, or null
320 * @param array|bool|string $opts Options for data fetching.
321 * This is an array consisting of the keys:
322 * 'version': The metadata version for the metadata option
323 * 'language': The language for extmetadata property
324 * 'multilang': Return all translations in extmetadata property
325 * 'revdelUser': User to use when checking whether to show revision-deleted fields.
326 * @return array Result array
328 static function getInfo( $file, $prop, $result, $thumbParams = null, $opts = false ) {
333 if ( !$opts ||
is_string( $opts ) ) {
335 'version' => $opts ?
: 'latest',
336 'language' => $wgContLang,
337 'multilang' => false,
338 'extmetadatafilter' => array(),
339 'revdelUser' => null,
342 $version = $opts['version'];
344 // Timestamp is shown even if the file is revdelete'd in interface
346 if ( isset( $prop['timestamp'] ) ) {
347 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
350 // Handle external callers who don't pass revdelUser
351 if ( isset( $opts['revdelUser'] ) && $opts['revdelUser'] ) {
352 $revdelUser = $opts['revdelUser'];
353 $canShowField = function ( $field ) use ( $file, $revdelUser ) {
354 return $file->userCan( $field, $revdelUser );
357 $canShowField = function ( $field ) use ( $file ) {
358 return !$file->isDeleted( $field );
362 $user = isset( $prop['user'] );
363 $userid = isset( $prop['userid'] );
365 if ( $user ||
$userid ) {
366 if ( $file->isDeleted( File
::DELETED_USER
) ) {
367 $vals['userhidden'] = '';
370 if ( $canShowField( File
::DELETED_USER
) ) {
372 $vals['user'] = $file->getUser();
375 $vals['userid'] = $file->getUser( 'id' );
377 if ( !$file->getUser( 'id' ) ) {
383 // This is shown even if the file is revdelete'd in interface
385 if ( isset( $prop['size'] ) ||
isset( $prop['dimensions'] ) ) {
386 $vals['size'] = intval( $file->getSize() );
387 $vals['width'] = intval( $file->getWidth() );
388 $vals['height'] = intval( $file->getHeight() );
390 $pageCount = $file->pageCount();
391 if ( $pageCount !== false ) {
392 $vals['pagecount'] = $pageCount;
395 // length as in how many seconds long a video is.
396 $length = $file->getLength();
398 // Call it duration, because "length" can be ambiguous.
399 $vals['duration'] = (float)$length;
403 $pcomment = isset( $prop['parsedcomment'] );
404 $comment = isset( $prop['comment'] );
406 if ( $pcomment ||
$comment ) {
407 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
408 $vals['commenthidden'] = '';
411 if ( $canShowField( File
::DELETED_COMMENT
) ) {
413 $vals['parsedcomment'] = Linker
::formatComment(
414 $file->getDescription( File
::RAW
), $file->getTitle() );
417 $vals['comment'] = $file->getDescription( File
::RAW
);
422 $canonicaltitle = isset( $prop['canonicaltitle'] );
423 $url = isset( $prop['url'] );
424 $sha1 = isset( $prop['sha1'] );
425 $meta = isset( $prop['metadata'] );
426 $extmetadata = isset( $prop['extmetadata'] );
427 $commonmeta = isset( $prop['commonmetadata'] );
428 $mime = isset( $prop['mime'] );
429 $mediatype = isset( $prop['mediatype'] );
430 $archive = isset( $prop['archivename'] );
431 $bitdepth = isset( $prop['bitdepth'] );
432 $uploadwarning = isset( $prop['uploadwarning'] );
434 if ( $uploadwarning ) {
435 $vals['html'] = SpecialUpload
::getExistsWarning( UploadBase
::getExistsWarning( $file ) );
438 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
439 $vals['filehidden'] = '';
443 if ( $anyHidden && $file->isDeleted( File
::DELETED_RESTRICTED
) ) {
444 $vals['suppressed'] = true;
447 if ( !$canShowField( File
::DELETED_FILE
) ) {
448 //Early return, tidier than indenting all following things one level
452 if ( $canonicaltitle ) {
453 $vals['canonicaltitle'] = $file->getTitle()->getPrefixedText();
457 if ( !is_null( $thumbParams ) ) {
458 $mto = $file->transform( $thumbParams );
459 self
::$transformCount++
;
460 if ( $mto && !$mto->isError() ) {
461 $vals['thumburl'] = wfExpandUrl( $mto->getUrl(), PROTO_CURRENT
);
463 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
464 // thumbnail sizes for the thumbnail actual size
465 if ( $mto->getUrl() !== $file->getUrl() ) {
466 $vals['thumbwidth'] = intval( $mto->getWidth() );
467 $vals['thumbheight'] = intval( $mto->getHeight() );
469 $vals['thumbwidth'] = intval( $file->getWidth() );
470 $vals['thumbheight'] = intval( $file->getHeight() );
473 if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
474 list( , $mime ) = $file->getHandler()->getThumbType(
475 $mto->getExtension(), $file->getMimeType(), $thumbParams );
476 $vals['thumbmime'] = $mime;
478 } elseif ( $mto && $mto->isError() ) {
479 $vals['thumberror'] = $mto->toText();
482 $vals['url'] = wfExpandUrl( $file->getFullURL(), PROTO_CURRENT
);
483 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl(), PROTO_CURRENT
);
487 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
491 wfSuppressWarnings();
492 $metadata = unserialize( $file->getMetadata() );
494 if ( $metadata && $version !== 'latest' ) {
495 $metadata = $file->convertMetadataVersion( $metadata, $version );
497 $vals['metadata'] = $metadata ? self
::processMetaData( $metadata, $result ) : null;
500 $metaArray = $file->getCommonMetaArray();
501 $vals['commonmetadata'] = $metaArray ? self
::processMetaData( $metaArray, $result ) : array();
504 if ( $extmetadata ) {
505 // Note, this should return an array where all the keys
506 // start with a letter, and all the values are strings.
507 // Thus there should be no issue with format=xml.
508 $format = new FormatMetadata
;
509 $format->setSingleLanguage( !$opts['multilang'] );
510 $format->getContext()->setLanguage( $opts['language'] );
511 $extmetaArray = $format->fetchExtendedMetadata( $file );
512 if ( $opts['extmetadatafilter'] ) {
513 $extmetaArray = array_intersect_key(
514 $extmetaArray, array_flip( $opts['extmetadatafilter'] )
517 $vals['extmetadata'] = $extmetaArray;
521 $vals['mime'] = $file->getMimeType();
525 $vals['mediatype'] = $file->getMediaType();
528 if ( $archive && $file->isOld() ) {
529 $vals['archivename'] = $file->getArchiveName();
533 $vals['bitdepth'] = $file->getBitDepth();
540 * Get the count of image transformations performed
542 * If this is >= TRANSFORM_LIMIT, you should probably stop processing images.
546 static function getTransformCount() {
547 return self
::$transformCount;
552 * @param array $metadata
553 * @param ApiResult $result
556 public static function processMetaData( $metadata, $result ) {
558 if ( is_array( $metadata ) ) {
559 foreach ( $metadata as $key => $value ) {
560 $r = array( 'name' => $key );
561 if ( is_array( $value ) ) {
562 $r['value'] = self
::processMetaData( $value, $result );
564 $r['value'] = $value;
569 $result->setIndexedTagName( $retval, 'metadata' );
574 public function getCacheMode( $params ) {
575 if ( $this->userCanSeeRevDel() ) {
584 * @param null|string $start
587 protected function getContinueStr( $img, $start = null ) {
588 if ( $start === null ) {
589 $start = $img->getTimestamp();
592 return $img->getOriginalTitle()->getDBkey() . '|' . $start;
595 public function getAllowedParams() {
600 ApiBase
::PARAM_ISMULTI
=> true,
601 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
602 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
605 ApiBase
::PARAM_TYPE
=> 'limit',
606 ApiBase
::PARAM_DFLT
=> 1,
607 ApiBase
::PARAM_MIN
=> 1,
608 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
609 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
612 ApiBase
::PARAM_TYPE
=> 'timestamp'
615 ApiBase
::PARAM_TYPE
=> 'timestamp'
618 ApiBase
::PARAM_TYPE
=> 'integer',
619 ApiBase
::PARAM_DFLT
=> -1
621 'urlheight' => array(
622 ApiBase
::PARAM_TYPE
=> 'integer',
623 ApiBase
::PARAM_DFLT
=> -1
625 'metadataversion' => array(
626 ApiBase
::PARAM_TYPE
=> 'string',
627 ApiBase
::PARAM_DFLT
=> '1',
629 'extmetadatalanguage' => array(
630 ApiBase
::PARAM_TYPE
=> 'string',
631 ApiBase
::PARAM_DFLT
=> $wgContLang->getCode(),
633 'extmetadatamultilang' => array(
634 ApiBase
::PARAM_TYPE
=> 'boolean',
635 ApiBase
::PARAM_DFLT
=> false,
637 'extmetadatafilter' => array(
638 ApiBase
::PARAM_TYPE
=> 'string',
639 ApiBase
::PARAM_ISMULTI
=> true,
642 ApiBase
::PARAM_DFLT
=> '',
643 ApiBase
::PARAM_TYPE
=> 'string',
646 'localonly' => false,
651 * Returns all possible parameters to iiprop
653 * @param array $filter List of properties to filter out
657 public static function getPropertyNames( $filter = array() ) {
658 return array_diff( array_keys( self
::getProperties() ), $filter );
662 * Returns array key value pairs of properties and their descriptions
664 * @param string $modulePrefix
667 private static function getProperties( $modulePrefix = '' ) {
669 'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
670 'user' => ' user - Adds the user who uploaded the image version',
671 'userid' => ' userid - Add the user ID that uploaded the image version',
672 'comment' => ' comment - Comment on the version',
673 'parsedcomment' => ' parsedcomment - Parse the comment on the version',
674 'canonicaltitle' => ' canonicaltitle - Adds the canonical title of the image file',
675 'url' => ' url - Gives URL to the image and the description page',
676 'size' => ' size - Adds the size of the image in bytes, ' .
677 'its height and its width. Page count and duration are added if applicable',
678 'dimensions' => ' dimensions - Alias for size', // B/C with Allimages
679 'sha1' => ' sha1 - Adds SHA-1 hash for the image',
680 'mime' => ' mime - Adds MIME type of the image',
681 'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail' .
682 ' (requires url and param ' . $modulePrefix . 'urlwidth)',
683 'mediatype' => ' mediatype - Adds the media type of the image',
684 'metadata' => ' metadata - Lists Exif metadata for the version of the image',
685 'commonmetadata' => ' commonmetadata - Lists file format generic metadata ' .
686 'for the version of the image',
687 'extmetadata' => ' extmetadata - Lists formatted metadata combined ' .
688 'from multiple sources. Results are HTML formatted.',
689 'archivename' => ' archivename - Adds the file name of the archive ' .
690 'version for non-latest versions',
691 'bitdepth' => ' bitdepth - Adds the bit depth of the version',
692 'uploadwarning' => ' uploadwarning - Used by the Special:Upload page to ' .
693 'get information about an existing file. Not intended for use outside MediaWiki core',
698 * Returns the descriptions for the properties provided by getPropertyNames()
700 * @param array $filter List of properties to filter out
701 * @param string $modulePrefix
704 public static function getPropertyDescriptions( $filter = array(), $modulePrefix = '' ) {
706 array( 'What image information to get:' ),
707 array_values( array_diff_key( self
::getProperties( $modulePrefix ), array_flip( $filter ) ) )
712 * Return the API documentation for the parameters.
713 * @return array Parameter documentation.
715 public function getParamDescription() {
716 $p = $this->getModulePrefix();
719 'prop' => self
::getPropertyDescriptions( array(), $p ),
721 "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
722 'For performance reasons if this option is used, ' .
723 'no more than ' . self
::TRANSFORM_LIMIT
. ' scaled images will be returned.'
725 'urlheight' => "Similar to {$p}urlwidth.",
726 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
727 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
728 'limit' => 'How many image revisions to return per image',
729 'start' => 'Timestamp to start listing from',
730 'end' => 'Timestamp to stop listing at',
732 => array( "Version of metadata to use. if 'latest' is specified, use latest version.",
733 "Defaults to '1' for backwards compatibility" ),
734 'extmetadatalanguage' => array(
735 'What language to fetch extmetadata in. This affects both which',
736 'translation to fetch, if multiple are available, as well as how things',
737 'like numbers and various values are formatted.'
739 'extmetadatamultilang'
740 =>'If translations for extmetadata property are available, fetch all of them.',
742 => "If specified and non-empty, only these keys will be returned for {$p}prop=extmetadata",
743 'continue' => 'If the query response includes a continue value, ' .
744 'use it here to get another page of results',
745 'localonly' => 'Look only for files in the local repository',
749 public function getDescription() {
750 return 'Returns image information and upload history.';
753 public function getExamples() {
755 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
756 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&' .
757 'iiend=20071231235959&iiprop=timestamp|user|url',
761 public function getHelpUrls() {
762 return 'https://www.mediawiki.org/wiki/API:Properties#imageinfo_.2F_ii';