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( $query, $moduleName, $prefix = 'ii' ) {
37 // We allow a subclass to override the prefix, to create a related API module.
38 // Some other parts of MediaWiki construct this with a null $prefix, which used to be ignored when this only took two arguments
39 if ( is_null( $prefix ) ) {
42 parent
::__construct( $query, $moduleName, $prefix );
45 public function execute() {
46 $params = $this->extractRequestParams();
48 $prop = array_flip( $params['prop'] );
50 $scale = $this->getScale( $params );
52 $pageIds = $this->getPageSet()->getAllTitlesByNamespace();
53 if ( !empty( $pageIds[NS_FILE
] ) ) {
54 $titles = array_keys( $pageIds[NS_FILE
] );
55 asort( $titles ); // Ensure the order is always the same
58 if ( !is_null( $params['continue'] ) ) {
59 $cont = explode( '|', $params['continue'] );
60 $this->dieContinueUsageIf( count( $cont ) != 2 );
61 $fromTitle = strval( $cont[0] );
62 $fromTimestamp = $cont[1];
63 // Filter out any titles before $fromTitle
64 foreach ( $titles as $key => $title ) {
65 if ( $title < $fromTitle ) {
66 unset( $titles[$key] );
73 $result = $this->getResult();
74 //search only inside the local repo
75 if ( $params['localonly'] ) {
76 $images = RepoGroup
::singleton()->getLocalRepo()->findFiles( $titles );
78 $images = RepoGroup
::singleton()->findFiles( $titles );
80 foreach ( $titles as $title ) {
81 $pageId = $pageIds[NS_FILE
][$title];
82 $start = $title === $fromTitle ?
$fromTimestamp : $params['start'];
84 if ( !isset( $images[$title] ) ) {
85 if ( isset( $prop['uploadwarning'] ) ) {
86 // Uploadwarning needs info about non-existing files
87 $images[$title] = wfLocalFile( $title );
90 array( 'query', 'pages', intval( $pageId ) ),
93 // The above can't fail because it doesn't increase the result size
99 $img = $images[$title];
101 if ( self
::getTransformCount() >= self
::TRANSFORM_LIMIT
) {
102 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
103 // See the 'the user is screwed' comment below
104 $this->setContinueEnumParameter( 'start',
105 $start !== null ?
$start : wfTimestamp( TS_ISO_8601
, $img->getTimestamp() )
108 $this->setContinueEnumParameter( 'continue',
109 $this->getContinueStr( $img, $start ) );
114 $fit = $result->addValue(
115 array( 'query', 'pages', intval( $pageId ) ),
116 'imagerepository', $img->getRepoName()
119 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
120 // The user is screwed. imageinfo can't be solely
121 // responsible for exceeding the limit in this case,
122 // so set a query-continue that just returns the same
123 // thing again. When the violating queries have been
124 // out-continued, the result will get through
125 $this->setContinueEnumParameter( 'start',
126 $start !== null ?
$start : wfTimestamp( TS_ISO_8601
, $img->getTimestamp() )
129 $this->setContinueEnumParameter( 'continue',
130 $this->getContinueStr( $img, $start ) );
135 // Check if we can make the requested thumbnail, and get transform parameters.
136 $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
138 // Get information about the current version first
139 // Check that the current version is within the start-end boundaries
142 ( is_null( $start ) ||
$img->getTimestamp() <= $start ) &&
143 ( is_null( $params['end'] ) ||
$img->getTimestamp() >= $params['end'] )
147 $fit = $this->addPageSubItem( $pageId,
148 self
::getInfo( $img, $prop, $result,
149 $finalThumbParams, $params['metadataversion'] ) );
151 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
152 // See the 'the user is screwed' comment above
153 $this->setContinueEnumParameter( 'start',
154 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
156 $this->setContinueEnumParameter( 'continue',
157 $this->getContinueStr( $img ) );
163 // Now get the old revisions
164 // Get one more to facilitate query-continue functionality
165 $count = ( $gotOne ?
1 : 0 );
166 $oldies = $img->getHistory( $params['limit'] - $count +
1, $start, $params['end'] );
167 /** @var $oldie File */
168 foreach ( $oldies as $oldie ) {
169 if ( ++
$count > $params['limit'] ) {
170 // We've reached the extra one which shows that there are additional pages to be had. Stop here...
171 // Only set a query-continue if there was only one title
172 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
173 $this->setContinueEnumParameter( 'start',
174 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
178 $fit = self
::getTransformCount() < self
::TRANSFORM_LIMIT
&&
179 $this->addPageSubItem( $pageId,
180 self
::getInfo( $oldie, $prop, $result,
181 $finalThumbParams, $params['metadataversion']
185 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
186 $this->setContinueEnumParameter( 'start',
187 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
189 $this->setContinueEnumParameter( 'continue',
190 $this->getContinueStr( $oldie ) );
203 * From parameters, construct a 'scale' array
204 * @param array $params Parameters passed to api.
205 * @return Array or Null: key-val array of 'width' and 'height', or null
207 public function getScale( $params ) {
208 $p = $this->getModulePrefix();
210 if ( $params['urlwidth'] != -1 ) {
212 $scale['width'] = $params['urlwidth'];
213 $scale['height'] = $params['urlheight'];
214 } elseif ( $params['urlheight'] != -1 ) {
215 // Height is specified but width isn't
216 // Don't set $scale['width']; this signals mergeThumbParams() to fill it with the image's width
218 $scale['height'] = $params['urlheight'];
221 if ( $params['urlparam'] ) {
222 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
229 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
231 * We do this later than getScale, since we need the image
232 * to know which handler, since handlers can make their own parameters.
233 * @param File $image Image that params are for.
234 * @param array $thumbParams thumbnail parameters from getScale
235 * @param string $otherParams of otherParams (iiurlparam).
236 * @return Array of parameters for transform.
238 protected function mergeThumbParams( $image, $thumbParams, $otherParams ) {
239 global $wgThumbLimits;
241 if ( !isset( $thumbParams['width'] ) && isset( $thumbParams['height'] ) ) {
242 // We want to limit only by height in this situation, so pass the
243 // image's full width as the limiting width. But some file types
244 // don't have a width of their own, so pick something arbitrary so
245 // thumbnailing the default icon works.
246 if ( $image->getWidth() <= 0 ) {
247 $thumbParams['width'] = max( $wgThumbLimits );
249 $thumbParams['width'] = $image->getWidth();
253 if ( !$otherParams ) {
256 $p = $this->getModulePrefix();
258 $h = $image->getHandler();
260 $this->setWarning( 'Could not create thumbnail because ' .
261 $image->getName() . ' does not have an associated image handler' );
265 $paramList = $h->parseParamString( $otherParams );
267 // Just set a warning (instead of dieUsage), as in many cases
268 // we could still render the image using width and height parameters,
269 // and this type of thing could happen between different versions of
271 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
272 . '. Using only width and height' );
276 if ( isset( $paramList['width'] ) ) {
277 if ( intval( $paramList['width'] ) != intval( $thumbParams['width'] ) ) {
278 $this->setWarning( "Ignoring width value set in {$p}urlparam ({$paramList['width']}) "
279 . "in favor of width value derived from {$p}urlwidth/{$p}urlheight ({$thumbParams['width']})" );
283 foreach ( $paramList as $name => $value ) {
284 if ( !$h->validateParam( $name, $value ) ) {
285 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
289 return $thumbParams +
$paramList;
293 * Get result information for an image revision
295 * @param $file File object
296 * @param array $prop of properties to get (in the keys)
297 * @param $result ApiResult object
298 * @param array $thumbParams containing 'width' and 'height' items, or null
299 * @param string $version Version of image metadata (for things like jpeg which have different versions).
300 * @return Array: result array
302 static function getInfo( $file, $prop, $result, $thumbParams = null, $version = 'latest' ) {
304 // Timestamp is shown even if the file is revdelete'd in interface
306 if ( isset( $prop['timestamp'] ) ) {
307 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
310 $user = isset( $prop['user'] );
311 $userid = isset( $prop['userid'] );
313 if ( $user ||
$userid ) {
314 if ( $file->isDeleted( File
::DELETED_USER
) ) {
315 $vals['userhidden'] = '';
318 $vals['user'] = $file->getUser();
321 $vals['userid'] = $file->getUser( 'id' );
323 if ( !$file->getUser( 'id' ) ) {
329 // This is shown even if the file is revdelete'd in interface
331 if ( isset( $prop['size'] ) ||
isset( $prop['dimensions'] ) ) {
332 $vals['size'] = intval( $file->getSize() );
333 $vals['width'] = intval( $file->getWidth() );
334 $vals['height'] = intval( $file->getHeight() );
336 $pageCount = $file->pageCount();
337 if ( $pageCount !== false ) {
338 $vals['pagecount'] = $pageCount;
342 $pcomment = isset( $prop['parsedcomment'] );
343 $comment = isset( $prop['comment'] );
345 if ( $pcomment ||
$comment ) {
346 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
347 $vals['commenthidden'] = '';
350 $vals['parsedcomment'] = Linker
::formatComment(
351 $file->getDescription(), $file->getTitle() );
354 $vals['comment'] = $file->getDescription();
359 $url = isset( $prop['url'] );
360 $sha1 = isset( $prop['sha1'] );
361 $meta = isset( $prop['metadata'] );
362 $mime = isset( $prop['mime'] );
363 $mediatype = isset( $prop['mediatype'] );
364 $archive = isset( $prop['archivename'] );
365 $bitdepth = isset( $prop['bitdepth'] );
366 $uploadwarning = isset( $prop['uploadwarning'] );
368 if ( ( $url ||
$sha1 ||
$meta ||
$mime ||
$mediatype ||
$archive ||
$bitdepth )
369 && $file->isDeleted( File
::DELETED_FILE
) ) {
370 $vals['filehidden'] = '';
372 //Early return, tidier than indenting all following things one level
377 if ( !is_null( $thumbParams ) ) {
378 $mto = $file->transform( $thumbParams );
379 self
::$transformCount++
;
380 if ( $mto && !$mto->isError() ) {
381 $vals['thumburl'] = wfExpandUrl( $mto->getUrl(), PROTO_CURRENT
);
383 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
384 // thumbnail sizes for the thumbnail actual size
385 if ( $mto->getUrl() !== $file->getUrl() ) {
386 $vals['thumbwidth'] = intval( $mto->getWidth() );
387 $vals['thumbheight'] = intval( $mto->getHeight() );
389 $vals['thumbwidth'] = intval( $file->getWidth() );
390 $vals['thumbheight'] = intval( $file->getHeight() );
393 if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
394 list( , $mime ) = $file->getHandler()->getThumbType(
395 $mto->getExtension(), $file->getMimeType(), $thumbParams );
396 $vals['thumbmime'] = $mime;
398 } elseif ( $mto && $mto->isError() ) {
399 $vals['thumberror'] = $mto->toText();
402 $vals['url'] = wfExpandUrl( $file->getFullURL(), PROTO_CURRENT
);
403 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl(), PROTO_CURRENT
);
407 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
411 wfSuppressWarnings();
412 $metadata = unserialize( $file->getMetadata() );
414 if ( $metadata && $version !== 'latest' ) {
415 $metadata = $file->convertMetadataVersion( $metadata, $version );
417 $vals['metadata'] = $metadata ? self
::processMetaData( $metadata, $result ) : null;
421 $vals['mime'] = $file->getMimeType();
425 $vals['mediatype'] = $file->getMediaType();
428 if ( $archive && $file->isOld() ) {
429 $vals['archivename'] = $file->getArchiveName();
433 $vals['bitdepth'] = $file->getBitDepth();
436 if ( $uploadwarning ) {
437 $vals['html'] = SpecialUpload
::getExistsWarning( UploadBase
::getExistsWarning( $file ) );
444 * Get the count of image transformations performed
446 * If this is >= TRANSFORM_LIMIT, you should probably stop processing images.
448 * @return integer count
450 static function getTransformCount() {
451 return self
::$transformCount;
456 * @param $metadata Array
457 * @param $result ApiResult
460 public static function processMetaData( $metadata, $result ) {
462 if ( is_array( $metadata ) ) {
463 foreach ( $metadata as $key => $value ) {
464 $r = array( 'name' => $key );
465 if ( is_array( $value ) ) {
466 $r['value'] = self
::processMetaData( $value, $result );
468 $r['value'] = $value;
473 $result->setIndexedTagName( $retval, 'metadata' );
477 public function getCacheMode( $params ) {
483 * @param null|string $start
486 protected function getContinueStr( $img, $start = null ) {
487 if ( $start === null ) {
488 $start = $img->getTimestamp();
490 return $img->getOriginalTitle()->getDBkey() . '|' . $start;
493 public function getAllowedParams() {
496 ApiBase
::PARAM_ISMULTI
=> true,
497 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
498 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
501 ApiBase
::PARAM_TYPE
=> 'limit',
502 ApiBase
::PARAM_DFLT
=> 1,
503 ApiBase
::PARAM_MIN
=> 1,
504 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
505 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
508 ApiBase
::PARAM_TYPE
=> 'timestamp'
511 ApiBase
::PARAM_TYPE
=> 'timestamp'
514 ApiBase
::PARAM_TYPE
=> 'integer',
515 ApiBase
::PARAM_DFLT
=> -1
517 'urlheight' => array(
518 ApiBase
::PARAM_TYPE
=> 'integer',
519 ApiBase
::PARAM_DFLT
=> -1
521 'metadataversion' => array(
522 ApiBase
::PARAM_TYPE
=> 'string',
523 ApiBase
::PARAM_DFLT
=> '1',
526 ApiBase
::PARAM_DFLT
=> '',
527 ApiBase
::PARAM_TYPE
=> 'string',
530 'localonly' => false,
535 * Returns all possible parameters to iiprop
537 * @param array $filter List of properties to filter out
541 public static function getPropertyNames( $filter = array() ) {
542 return array_diff( array_keys( self
::getProperties() ), $filter );
546 * Returns array key value pairs of properties and their descriptions
548 * @param string $modulePrefix
551 private static function getProperties( $modulePrefix = '' ) {
553 'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
554 'user' => ' user - Adds the user who uploaded the image version',
555 'userid' => ' userid - Add the user ID that uploaded the image version',
556 'comment' => ' comment - Comment on the version',
557 'parsedcomment' => ' parsedcomment - Parse the comment on the version',
558 'url' => ' url - Gives URL to the image and the description page',
559 'size' => ' size - Adds the size of the image in bytes and the height, width and page count (if applicable)',
560 'dimensions' => ' dimensions - Alias for size', // For backwards compatibility with Allimages
561 'sha1' => ' sha1 - Adds SHA-1 hash for the image',
562 'mime' => ' mime - Adds MIME type of the image',
563 'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail' .
564 ' (requires url and param ' . $modulePrefix . 'urlwidth)',
565 'mediatype' => ' mediatype - Adds the media type of the image',
566 'metadata' => ' metadata - Lists Exif metadata for the version of the image',
567 'archivename' => ' archivename - Adds the file name of the archive version for non-latest versions',
568 'bitdepth' => ' bitdepth - Adds the bit depth of the version',
569 'uploadwarning' => ' uploadwarning - Used by the Special:Upload page to get information about an existing file. Not intended for use outside MediaWiki core',
574 * Returns the descriptions for the properties provided by getPropertyNames()
576 * @param array $filter List of properties to filter out
577 * @param string $modulePrefix
580 public static function getPropertyDescriptions( $filter = array(), $modulePrefix = '' ) {
582 array( 'What image information to get:' ),
583 array_values( array_diff_key( self
::getProperties( $modulePrefix ), array_flip( $filter ) ) )
588 * Return the API documentation for the parameters.
589 * @return Array parameter documentation.
591 public function getParamDescription() {
592 $p = $this->getModulePrefix();
594 'prop' => self
::getPropertyDescriptions( array(), $p ),
595 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
596 'For performance reasons if this option is used, ' .
597 'no more than ' . self
::TRANSFORM_LIMIT
. ' scaled images will be returned.' ),
598 'urlheight' => "Similar to {$p}urlwidth.",
599 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
600 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
601 'limit' => 'How many image revisions to return per image',
602 'start' => 'Timestamp to start listing from',
603 'end' => 'Timestamp to stop listing at',
604 'metadataversion' => array( "Version of metadata to use. if 'latest' is specified, use latest version.",
605 "Defaults to '1' for backwards compatibility" ),
606 'continue' => 'If the query response includes a continue value, use it here to get another page of results',
607 'localonly' => 'Look only for files in the local repository',
611 public static function getResultPropertiesFiltered( $filter = array() ) {
613 'timestamp' => array(
614 'timestamp' => 'timestamp'
617 'userhidden' => 'boolean',
622 'userhidden' => 'boolean',
623 'userid' => 'integer',
628 'width' => 'integer',
629 'height' => 'integer',
630 'pagecount' => array(
631 ApiBase
::PROP_TYPE
=> 'integer',
632 ApiBase
::PROP_NULLABLE
=> true
635 'dimensions' => array(
637 'width' => 'integer',
638 'height' => 'integer',
639 'pagecount' => array(
640 ApiBase
::PROP_TYPE
=> 'integer',
641 ApiBase
::PROP_NULLABLE
=> true
645 'commenthidden' => 'boolean',
647 ApiBase
::PROP_TYPE
=> 'string',
648 ApiBase
::PROP_NULLABLE
=> true
651 'parsedcomment' => array(
652 'commenthidden' => 'boolean',
653 'parsedcomment' => array(
654 ApiBase
::PROP_TYPE
=> 'string',
655 ApiBase
::PROP_NULLABLE
=> true
659 'filehidden' => 'boolean',
661 ApiBase
::PROP_TYPE
=> 'string',
662 ApiBase
::PROP_NULLABLE
=> true
664 'thumbwidth' => array(
665 ApiBase
::PROP_TYPE
=> 'integer',
666 ApiBase
::PROP_NULLABLE
=> true
668 'thumbheight' => array(
669 ApiBase
::PROP_TYPE
=> 'integer',
670 ApiBase
::PROP_NULLABLE
=> true
672 'thumberror' => array(
673 ApiBase
::PROP_TYPE
=> 'string',
674 ApiBase
::PROP_NULLABLE
=> true
677 ApiBase
::PROP_TYPE
=> 'string',
678 ApiBase
::PROP_NULLABLE
=> true
680 'descriptionurl' => array(
681 ApiBase
::PROP_TYPE
=> 'string',
682 ApiBase
::PROP_NULLABLE
=> true
686 'filehidden' => 'boolean',
688 ApiBase
::PROP_TYPE
=> 'string',
689 ApiBase
::PROP_NULLABLE
=> true
693 'filehidden' => 'boolean',
695 ApiBase
::PROP_TYPE
=> 'string',
696 ApiBase
::PROP_NULLABLE
=> true
699 'thumbmime' => array(
700 'filehidden' => 'boolean',
701 'thumbmime' => array(
702 ApiBase
::PROP_TYPE
=> 'string',
703 ApiBase
::PROP_NULLABLE
=> true
706 'mediatype' => array(
707 'filehidden' => 'boolean',
708 'mediatype' => array(
709 ApiBase
::PROP_TYPE
=> 'string',
710 ApiBase
::PROP_NULLABLE
=> true
713 'archivename' => array(
714 'filehidden' => 'boolean',
715 'archivename' => array(
716 ApiBase
::PROP_TYPE
=> 'string',
717 ApiBase
::PROP_NULLABLE
=> true
721 'filehidden' => 'boolean',
723 ApiBase
::PROP_TYPE
=> 'integer',
724 ApiBase
::PROP_NULLABLE
=> true
728 return array_diff_key( $props, array_flip( $filter ) );
731 public function getResultProperties() {
732 return self
::getResultPropertiesFiltered();
735 public function getDescription() {
736 return 'Returns image information and upload history';
739 public function getPossibleErrors() {
740 $p = $this->getModulePrefix();
741 return array_merge( parent
::getPossibleErrors(), array(
742 array( 'code' => "{$p}urlwidth", 'info' => "{$p}urlheight cannot be used without {$p}urlwidth" ),
743 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
744 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
748 public function getExamples() {
750 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
751 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
755 public function getHelpUrls() {
756 return 'https://www.mediawiki.org/wiki/API:Properties#imageinfo_.2F_ii';