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] ) ) {
86 array( 'query', 'pages', intval( $pageId ) ),
89 // The above can't fail because it doesn't increase the result size
93 $img = $images[$title];
95 if ( self
::getTransformCount() >= self
::TRANSFORM_LIMIT
) {
96 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
97 // See the 'the user is screwed' comment below
98 $this->setContinueEnumParameter( 'start',
99 $start !== null ?
$start : wfTimestamp( TS_ISO_8601
, $img->getTimestamp() )
102 $this->setContinueEnumParameter( 'continue',
103 $this->getContinueStr( $img, $start ) );
108 $fit = $result->addValue(
109 array( 'query', 'pages', intval( $pageId ) ),
110 'imagerepository', $img->getRepoName()
113 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
114 // The user is screwed. imageinfo can't be solely
115 // responsible for exceeding the limit in this case,
116 // so set a query-continue that just returns the same
117 // thing again. When the violating queries have been
118 // out-continued, the result will get through
119 $this->setContinueEnumParameter( 'start',
120 $start !== null ?
$start : wfTimestamp( TS_ISO_8601
, $img->getTimestamp() )
123 $this->setContinueEnumParameter( 'continue',
124 $this->getContinueStr( $img, $start ) );
129 // Check if we can make the requested thumbnail, and get transform parameters.
130 $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
132 // Get information about the current version first
133 // Check that the current version is within the start-end boundaries
136 ( is_null( $start ) ||
$img->getTimestamp() <= $start ) &&
137 ( is_null( $params['end'] ) ||
$img->getTimestamp() >= $params['end'] )
141 $fit = $this->addPageSubItem( $pageId,
142 self
::getInfo( $img, $prop, $result,
143 $finalThumbParams, $params['metadataversion'] ) );
145 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
146 // See the 'the user is screwed' comment above
147 $this->setContinueEnumParameter( 'start',
148 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
150 $this->setContinueEnumParameter( 'continue',
151 $this->getContinueStr( $img ) );
157 // Now get the old revisions
158 // Get one more to facilitate query-continue functionality
159 $count = ( $gotOne ?
1 : 0 );
160 $oldies = $img->getHistory( $params['limit'] - $count +
1, $start, $params['end'] );
161 foreach ( $oldies as $oldie ) {
162 if ( ++
$count > $params['limit'] ) {
163 // We've reached the extra one which shows that there are additional pages to be had. Stop here...
164 // Only set a query-continue if there was only one title
165 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
166 $this->setContinueEnumParameter( 'start',
167 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
171 $fit = $this->addPageSubItem( $pageId,
172 self
::getInfo( $oldie, $prop, $result,
173 $finalThumbParams, $params['metadataversion'] ) );
175 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
176 $this->setContinueEnumParameter( 'start',
177 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
179 $this->setContinueEnumParameter( 'continue',
180 $this->getContinueStr( $oldie ) );
193 * From parameters, construct a 'scale' array
194 * @param $params Array: Parameters passed to api.
195 * @return Array or Null: key-val array of 'width' and 'height', or null
197 public function getScale( $params ) {
198 $p = $this->getModulePrefix();
201 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
202 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
205 if ( $params['urlwidth'] != -1 ) {
207 $scale['width'] = $params['urlwidth'];
208 $scale['height'] = $params['urlheight'];
211 if ( $params['urlparam'] ) {
212 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
220 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
222 * We do this later than getScale, since we need the image
223 * to know which handler, since handlers can make their own parameters.
224 * @param File $image Image that params are for.
225 * @param Array $thumbParams thumbnail parameters from getScale
226 * @param String $otherParams of otherParams (iiurlparam).
227 * @return Array of parameters for transform.
229 protected function mergeThumbParams ( $image, $thumbParams, $otherParams ) {
230 if ( !$otherParams ) {
233 $p = $this->getModulePrefix();
235 $h = $image->getHandler();
237 $this->setWarning( 'Could not create thumbnail because ' .
238 $image->getName() . ' does not have an associated image handler' );
242 $paramList = $h->parseParamString( $otherParams );
244 // Just set a warning (instead of dieUsage), as in many cases
245 // we could still render the image using width and height parameters,
246 // and this type of thing could happen between different versions of
248 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
249 . '. Using only width and height' );
253 if ( isset( $paramList['width'] ) ) {
254 if ( intval( $paramList['width'] ) != intval( $thumbParams['width'] ) ) {
255 $this->dieUsage( "{$p}urlparam had width of {$paramList['width']} but "
256 . "{$p}urlwidth was {$thumbParams['width']}", "urlparam_urlwidth_mismatch" );
260 foreach ( $paramList as $name => $value ) {
261 if ( !$h->validateParam( $name, $value ) ) {
262 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
266 return $thumbParams +
$paramList;
270 * Get result information for an image revision
272 * @param $file File object
273 * @param $prop Array of properties to get (in the keys)
274 * @param $result ApiResult object
275 * @param $thumbParams Array containing 'width' and 'height' items, or null
276 * @param $version string Version of image metadata (for things like jpeg which have different versions).
277 * @return Array: result array
279 static function getInfo( $file, $prop, $result, $thumbParams = null, $version = 'latest' ) {
281 // Timestamp is shown even if the file is revdelete'd in interface
283 if ( isset( $prop['timestamp'] ) ) {
284 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
287 $user = isset( $prop['user'] );
288 $userid = isset( $prop['userid'] );
290 if ( $user ||
$userid ) {
291 if ( $file->isDeleted( File
::DELETED_USER
) ) {
292 $vals['userhidden'] = '';
295 $vals['user'] = $file->getUser();
298 $vals['userid'] = $file->getUser( 'id' );
300 if ( !$file->getUser( 'id' ) ) {
306 // This is shown even if the file is revdelete'd in interface
308 if ( isset( $prop['size'] ) ||
isset( $prop['dimensions'] ) ) {
309 $vals['size'] = intval( $file->getSize() );
310 $vals['width'] = intval( $file->getWidth() );
311 $vals['height'] = intval( $file->getHeight() );
313 $pageCount = $file->pageCount();
314 if ( $pageCount !== false ) {
315 $vals['pagecount'] = $pageCount;
319 $pcomment = isset( $prop['parsedcomment'] );
320 $comment = isset( $prop['comment'] );
322 if ( $pcomment ||
$comment ) {
323 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
324 $vals['commenthidden'] = '';
327 $vals['parsedcomment'] = Linker
::formatComment(
328 $file->getDescription(), $file->getTitle() );
331 $vals['comment'] = $file->getDescription();
336 $url = isset( $prop['url'] );
337 $sha1 = isset( $prop['sha1'] );
338 $meta = isset( $prop['metadata'] );
339 $mime = isset( $prop['mime'] );
340 $mediatype = isset( $prop['mediatype'] );
341 $archive = isset( $prop['archivename'] );
342 $bitdepth = isset( $prop['bitdepth'] );
344 if ( ( $url ||
$sha1 ||
$meta ||
$mime ||
$mediatype ||
$archive ||
$bitdepth )
345 && $file->isDeleted( File
::DELETED_FILE
) ) {
346 $vals['filehidden'] = '';
348 //Early return, tidier than indenting all following things one level
353 if ( !is_null( $thumbParams ) ) {
354 $mto = $file->transform( $thumbParams );
355 self
::$transformCount++
;
356 if ( $mto && !$mto->isError() ) {
357 $vals['thumburl'] = wfExpandUrl( $mto->getUrl(), PROTO_CURRENT
);
359 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
360 // thumbnail sizes for the thumbnail actual size
361 if ( $mto->getUrl() !== $file->getUrl() ) {
362 $vals['thumbwidth'] = intval( $mto->getWidth() );
363 $vals['thumbheight'] = intval( $mto->getHeight() );
365 $vals['thumbwidth'] = intval( $file->getWidth() );
366 $vals['thumbheight'] = intval( $file->getHeight() );
369 if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
370 list( $ext, $mime ) = $file->getHandler()->getThumbType(
371 $mto->getExtension(), $file->getMimeType(), $thumbParams );
372 $vals['thumbmime'] = $mime;
374 } elseif ( $mto && $mto->isError() ) {
375 $vals['thumberror'] = $mto->toText();
378 $vals['url'] = wfExpandUrl( $file->getFullURL(), PROTO_CURRENT
);
379 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl(), PROTO_CURRENT
);
383 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
387 wfSuppressWarnings();
388 $metadata = unserialize( $file->getMetadata() );
390 if ( $metadata && $version !== 'latest' ) {
391 $metadata = $file->convertMetadataVersion( $metadata, $version );
393 $vals['metadata'] = $metadata ? self
::processMetaData( $metadata, $result ) : null;
397 $vals['mime'] = $file->getMimeType();
401 $vals['mediatype'] = $file->getMediaType();
404 if ( $archive && $file->isOld() ) {
405 $vals['archivename'] = $file->getArchiveName();
409 $vals['bitdepth'] = $file->getBitDepth();
416 * Get the count of image transformations performed
418 * If this is >= TRANSFORM_LIMIT, you should probably stop processing images.
420 * @return integer count
422 static function getTransformCount() {
423 return self
::$transformCount;
428 * @param $metadata Array
429 * @param $result ApiResult
432 public static function processMetaData( $metadata, $result ) {
434 if ( is_array( $metadata ) ) {
435 foreach ( $metadata as $key => $value ) {
436 $r = array( 'name' => $key );
437 if ( is_array( $value ) ) {
438 $r['value'] = self
::processMetaData( $value, $result );
440 $r['value'] = $value;
445 $result->setIndexedTagName( $retval, 'metadata' );
449 public function getCacheMode( $params ) {
457 protected function getContinueStr( $img, $start = null ) {
458 if ( $start === null ) {
459 $start = $img->getTimestamp();
461 return $img->getOriginalTitle()->getText() . '|' . $start;
464 public function getAllowedParams() {
467 ApiBase
::PARAM_ISMULTI
=> true,
468 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
469 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
472 ApiBase
::PARAM_TYPE
=> 'limit',
473 ApiBase
::PARAM_DFLT
=> 1,
474 ApiBase
::PARAM_MIN
=> 1,
475 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
476 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
479 ApiBase
::PARAM_TYPE
=> 'timestamp'
482 ApiBase
::PARAM_TYPE
=> 'timestamp'
485 ApiBase
::PARAM_TYPE
=> 'integer',
486 ApiBase
::PARAM_DFLT
=> -1
488 'urlheight' => array(
489 ApiBase
::PARAM_TYPE
=> 'integer',
490 ApiBase
::PARAM_DFLT
=> -1
492 'metadataversion' => array(
493 ApiBase
::PARAM_TYPE
=> 'string',
494 ApiBase
::PARAM_DFLT
=> '1',
497 ApiBase
::PARAM_DFLT
=> '',
498 ApiBase
::PARAM_TYPE
=> 'string',
501 'localonly' => false,
506 * Returns all possible parameters to iiprop
508 * @param array $filter List of properties to filter out
512 public static function getPropertyNames( $filter = array() ) {
513 return array_diff( array_keys( self
::getProperties() ), $filter );
517 * Returns array key value pairs of properties and their descriptions
521 private static function getProperties( $modulePrefix = '' ) {
523 'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
524 'user' => ' user - Adds the user who uploaded the image version',
525 'userid' => ' userid - Add the user ID that uploaded the image version',
526 'comment' => ' comment - Comment on the version',
527 'parsedcomment' => ' parsedcomment - Parse the comment on the version',
528 'url' => ' url - Gives URL to the image and the description page',
529 'size' => ' size - Adds the size of the image in bytes and the height, width and page count (if applicable)',
530 'dimensions' => ' dimensions - Alias for size', // For backwards compatibility with Allimages
531 'sha1' => ' sha1 - Adds SHA-1 hash for the image',
532 'mime' => ' mime - Adds MIME type of the image',
533 'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail' .
534 ' (requires url and param ' . $modulePrefix . 'urlwidth)',
535 'mediatype' => ' mediatype - Adds the media type of the image',
536 'metadata' => ' metadata - Lists EXIF metadata for the version of the image',
537 'archivename' => ' archivename - Adds the file name of the archive version for non-latest versions',
538 'bitdepth' => ' bitdepth - Adds the bit depth of the version',
543 * Returns the descriptions for the properties provided by getPropertyNames()
545 * @param array $filter List of properties to filter out
549 public static function getPropertyDescriptions( $filter = array(), $modulePrefix = '' ) {
551 array( 'What image information to get:' ),
552 array_values( array_diff_key( self
::getProperties( $modulePrefix ), array_flip( $filter ) ) )
557 * Return the API documentation for the parameters.
558 * @return Array parameter documentation.
560 public function getParamDescription() {
561 $p = $this->getModulePrefix();
563 'prop' => self
::getPropertyDescriptions( array(), $p ),
564 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
565 'Only the current version of the image can be scaled' ),
566 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
567 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
568 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
569 'limit' => 'How many image revisions to return',
570 'start' => 'Timestamp to start listing from',
571 'end' => 'Timestamp to stop listing at',
572 'metadataversion' => array( "Version of metadata to use. if 'latest' is specified, use latest version.",
573 "Defaults to '1' for backwards compatibility" ),
574 'continue' => 'If the query response includes a continue value, use it here to get another page of results',
575 'localonly' => 'Look only for files in the local repository',
579 public static function getResultPropertiesFiltered( $filter = array() ) {
581 'timestamp' => array(
582 'timestamp' => 'timestamp'
585 'userhidden' => 'boolean',
590 'userhidden' => 'boolean',
591 'userid' => 'integer',
596 'width' => 'integer',
597 'height' => 'integer',
598 'pagecount' => array(
599 ApiBase
::PROP_TYPE
=> 'integer',
600 ApiBase
::PROP_NULLABLE
=> true
603 'dimensions' => array(
605 'width' => 'integer',
606 'height' => 'integer',
607 'pagecount' => array(
608 ApiBase
::PROP_TYPE
=> 'integer',
609 ApiBase
::PROP_NULLABLE
=> true
613 'commenthidden' => 'boolean',
615 ApiBase
::PROP_TYPE
=> 'string',
616 ApiBase
::PROP_NULLABLE
=> true
619 'parsedcomment' => array(
620 'commenthidden' => 'boolean',
621 'parsedcomment' => array(
622 ApiBase
::PROP_TYPE
=> 'string',
623 ApiBase
::PROP_NULLABLE
=> true
627 'filehidden' => 'boolean',
629 ApiBase
::PROP_TYPE
=> 'string',
630 ApiBase
::PROP_NULLABLE
=> true
632 'thumbwidth' => array(
633 ApiBase
::PROP_TYPE
=> 'integer',
634 ApiBase
::PROP_NULLABLE
=> true
636 'thumbheight' => array(
637 ApiBase
::PROP_TYPE
=> 'integer',
638 ApiBase
::PROP_NULLABLE
=> true
640 'thumberror' => array(
641 ApiBase
::PROP_TYPE
=> 'string',
642 ApiBase
::PROP_NULLABLE
=> true
645 ApiBase
::PROP_TYPE
=> 'string',
646 ApiBase
::PROP_NULLABLE
=> true
648 'descriptionurl' => array(
649 ApiBase
::PROP_TYPE
=> 'string',
650 ApiBase
::PROP_NULLABLE
=> true
654 'filehidden' => 'boolean',
656 ApiBase
::PROP_TYPE
=> 'string',
657 ApiBase
::PROP_NULLABLE
=> true
661 'filehidden' => 'boolean',
663 ApiBase
::PROP_TYPE
=> 'string',
664 ApiBase
::PROP_NULLABLE
=> true
667 'thumbmime' => array(
668 'filehidden' => 'boolean',
669 'thumbmime' => array(
670 ApiBase
::PROP_TYPE
=> 'string',
671 ApiBase
::PROP_NULLABLE
=> true
674 'mediatype' => array(
675 'filehidden' => 'boolean',
676 'mediatype' => array(
677 ApiBase
::PROP_TYPE
=> 'string',
678 ApiBase
::PROP_NULLABLE
=> true
681 'archivename' => array(
682 'filehidden' => 'boolean',
683 'archivename' => array(
684 ApiBase
::PROP_TYPE
=> 'string',
685 ApiBase
::PROP_NULLABLE
=> true
689 'filehidden' => 'boolean',
691 ApiBase
::PROP_TYPE
=> 'integer',
692 ApiBase
::PROP_NULLABLE
=> true
696 return array_diff_key( $props, array_flip( $filter ) );
699 public function getResultProperties() {
700 return self
::getResultPropertiesFiltered();
703 public function getDescription() {
704 return 'Returns image information and upload history';
707 public function getPossibleErrors() {
708 $p = $this->getModulePrefix();
709 return array_merge( parent
::getPossibleErrors(), array(
710 array( 'code' => "{$p}urlwidth", 'info' => "{$p}urlheight cannot be used without {$p}urlwidth" ),
711 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
712 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
713 array( 'code' => 'urlparam_urlwidth_mismatch', 'info' => "The width set in {$p}urlparm doesnt't " .
714 "match the one in {$p}urlwidth" ),
718 public function getExamples() {
720 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
721 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
725 public function getHelpUrls() {
726 return 'https://www.mediawiki.org/wiki/API:Properties#imageinfo_.2F_ii';