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
{
34 public function __construct( $query, $moduleName, $prefix = 'ii' ) {
35 // We allow a subclass to override the prefix, to create a related API module.
36 // Some other parts of MediaWiki construct this with a null $prefix, which used to be ignored when this only took two arguments
37 if ( is_null( $prefix ) ) {
40 parent
::__construct( $query, $moduleName, $prefix );
43 public function execute() {
44 $params = $this->extractRequestParams();
46 $prop = array_flip( $params['prop'] );
48 $scale = $this->getScale( $params );
50 $pageIds = $this->getPageSet()->getAllTitlesByNamespace();
51 if ( !empty( $pageIds[NS_FILE
] ) ) {
52 $titles = array_keys( $pageIds[NS_FILE
] );
53 asort( $titles ); // Ensure the order is always the same
56 if ( !is_null( $params['continue'] ) ) {
58 $cont = explode( '|', $params['continue'] );
59 $this->dieContinueUsageIf( count( $cont ) != 2 );
60 $fromTitle = strval( $cont[0] );
61 $fromTimestamp = $cont[1];
62 // Filter out any titles before $fromTitle
63 foreach ( $titles as $key => $title ) {
64 if ( $title < $fromTitle ) {
65 unset( $titles[$key] );
72 $result = $this->getResult();
73 //search only inside the local repo
74 if( $params['localonly'] ) {
75 $images = RepoGroup
::singleton()->getLocalRepo()->findFiles( $titles );
77 $images = RepoGroup
::singleton()->findFiles( $titles );
79 foreach ( $titles as $title ) {
80 if ( !isset( $images[$title] ) ) {
84 $start = $skip ?
$fromTimestamp : $params['start'];
85 $pageId = $pageIds[NS_FILE
][$title];
86 $img = $images[$title];
88 $fit = $result->addValue(
89 array( 'query', 'pages', intval( $pageId ) ),
90 'imagerepository', $img->getRepoName()
93 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
94 // The user is screwed. imageinfo can't be solely
95 // responsible for exceeding the limit in this case,
96 // so set a query-continue that just returns the same
97 // thing again. When the violating queries have been
98 // out-continued, the result will get through
99 $this->setContinueEnumParameter( 'start',
100 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
102 $this->setContinueEnumParameter( 'continue',
103 $this->getContinueStr( $img ) );
108 // Check if we can make the requested thumbnail, and get transform parameters.
109 $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
111 // Get information about the current version first
112 // Check that the current version is within the start-end boundaries
115 ( is_null( $start ) ||
$img->getTimestamp() <= $start ) &&
116 ( is_null( $params['end'] ) ||
$img->getTimestamp() >= $params['end'] )
120 $fit = $this->addPageSubItem( $pageId,
121 self
::getInfo( $img, $prop, $result,
122 $finalThumbParams, $params['metadataversion'] ) );
124 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
125 // See the 'the user is screwed' comment above
126 $this->setContinueEnumParameter( 'start',
127 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
129 $this->setContinueEnumParameter( 'continue',
130 $this->getContinueStr( $img ) );
136 // Now get the old revisions
137 // Get one more to facilitate query-continue functionality
138 $count = ( $gotOne ?
1 : 0 );
139 $oldies = $img->getHistory( $params['limit'] - $count +
1, $start, $params['end'] );
140 foreach ( $oldies as $oldie ) {
141 if ( ++
$count > $params['limit'] ) {
142 // We've reached the extra one which shows that there are additional pages to be had. Stop here...
143 // Only set a query-continue if there was only one title
144 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
145 $this->setContinueEnumParameter( 'start',
146 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
150 $fit = $this->addPageSubItem( $pageId,
151 self
::getInfo( $oldie, $prop, $result,
152 $finalThumbParams, $params['metadataversion'] ) );
154 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
155 $this->setContinueEnumParameter( 'start',
156 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
158 $this->setContinueEnumParameter( 'continue',
159 $this->getContinueStr( $oldie ) );
170 $data = $this->getResultData();
171 foreach ( $data['query']['pages'] as $pageid => $arr ) {
172 if ( is_array( $arr ) && !isset( $arr['imagerepository'] ) ) {
174 array( 'query', 'pages', $pageid ),
175 'imagerepository', ''
178 // The above can't fail because it doesn't increase the result size
184 * From parameters, construct a 'scale' array
185 * @param $params Array: Parameters passed to api.
186 * @return Array or Null: key-val array of 'width' and 'height', or null
188 public function getScale( $params ) {
189 $p = $this->getModulePrefix();
192 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
193 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
196 if ( $params['urlwidth'] != -1 ) {
198 $scale['width'] = $params['urlwidth'];
199 $scale['height'] = $params['urlheight'];
202 if ( $params['urlparam'] ) {
203 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
211 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
213 * We do this later than getScale, since we need the image
214 * to know which handler, since handlers can make their own parameters.
215 * @param File $image Image that params are for.
216 * @param Array $thumbParams thumbnail parameters from getScale
217 * @param String $otherParams of otherParams (iiurlparam).
218 * @return Array of parameters for transform.
220 protected function mergeThumbParams ( $image, $thumbParams, $otherParams ) {
221 if ( !$otherParams ) {
224 $p = $this->getModulePrefix();
226 $h = $image->getHandler();
228 $this->setWarning( 'Could not create thumbnail because ' .
229 $image->getName() . ' does not have an associated image handler' );
233 $paramList = $h->parseParamString( $otherParams );
235 // Just set a warning (instead of dieUsage), as in many cases
236 // we could still render the image using width and height parameters,
237 // and this type of thing could happen between different versions of
239 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
240 . '. Using only width and height' );
244 if ( isset( $paramList['width'] ) ) {
245 if ( intval( $paramList['width'] ) != intval( $thumbParams['width'] ) ) {
246 $this->dieUsage( "{$p}urlparam had width of {$paramList['width']} but "
247 . "{$p}urlwidth was {$thumbParams['width']}", "urlparam_urlwidth_mismatch" );
251 foreach ( $paramList as $name => $value ) {
252 if ( !$h->validateParam( $name, $value ) ) {
253 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
257 return $thumbParams +
$paramList;
261 * Get result information for an image revision
263 * @param $file File object
264 * @param $prop Array of properties to get (in the keys)
265 * @param $result ApiResult object
266 * @param $thumbParams Array containing 'width' and 'height' items, or null
267 * @param $version string Version of image metadata (for things like jpeg which have different versions).
268 * @return Array: result array
270 static function getInfo( $file, $prop, $result, $thumbParams = null, $version = 'latest' ) {
272 // Timestamp is shown even if the file is revdelete'd in interface
274 if ( isset( $prop['timestamp'] ) ) {
275 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
278 $user = isset( $prop['user'] );
279 $userid = isset( $prop['userid'] );
281 if ( $user ||
$userid ) {
282 if ( $file->isDeleted( File
::DELETED_USER
) ) {
283 $vals['userhidden'] = '';
286 $vals['user'] = $file->getUser();
289 $vals['userid'] = $file->getUser( 'id' );
291 if ( !$file->getUser( 'id' ) ) {
297 // This is shown even if the file is revdelete'd in interface
299 if ( isset( $prop['size'] ) ||
isset( $prop['dimensions'] ) ) {
300 $vals['size'] = intval( $file->getSize() );
301 $vals['width'] = intval( $file->getWidth() );
302 $vals['height'] = intval( $file->getHeight() );
304 $pageCount = $file->pageCount();
305 if ( $pageCount !== false ) {
306 $vals['pagecount'] = $pageCount;
310 $pcomment = isset( $prop['parsedcomment'] );
311 $comment = isset( $prop['comment'] );
313 if ( $pcomment ||
$comment ) {
314 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
315 $vals['commenthidden'] = '';
318 $vals['parsedcomment'] = Linker
::formatComment(
319 $file->getDescription(), $file->getTitle() );
322 $vals['comment'] = $file->getDescription();
327 $url = isset( $prop['url'] );
328 $sha1 = isset( $prop['sha1'] );
329 $meta = isset( $prop['metadata'] );
330 $mime = isset( $prop['mime'] );
331 $mediatype = isset( $prop['mediatype'] );
332 $archive = isset( $prop['archivename'] );
333 $bitdepth = isset( $prop['bitdepth'] );
335 if ( ( $url ||
$sha1 ||
$meta ||
$mime ||
$mediatype ||
$archive ||
$bitdepth )
336 && $file->isDeleted( File
::DELETED_FILE
) ) {
337 $vals['filehidden'] = '';
339 //Early return, tidier than indenting all following things one level
344 if ( !is_null( $thumbParams ) ) {
345 $mto = $file->transform( $thumbParams );
346 if ( $mto && !$mto->isError() ) {
347 $vals['thumburl'] = wfExpandUrl( $mto->getUrl(), PROTO_CURRENT
);
349 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
350 // thumbnail sizes for the thumbnail actual size
351 if ( $mto->getUrl() !== $file->getUrl() ) {
352 $vals['thumbwidth'] = intval( $mto->getWidth() );
353 $vals['thumbheight'] = intval( $mto->getHeight() );
355 $vals['thumbwidth'] = intval( $file->getWidth() );
356 $vals['thumbheight'] = intval( $file->getHeight() );
359 if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
360 list( $ext, $mime ) = $file->getHandler()->getThumbType(
361 $mto->getExtension(), $file->getMimeType(), $thumbParams );
362 $vals['thumbmime'] = $mime;
364 } elseif ( $mto && $mto->isError() ) {
365 $vals['thumberror'] = $mto->toText();
368 $vals['url'] = wfExpandUrl( $file->getFullURL(), PROTO_CURRENT
);
369 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl(), PROTO_CURRENT
);
373 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
377 wfSuppressWarnings();
378 $metadata = unserialize( $file->getMetadata() );
380 if ( $metadata && $version !== 'latest' ) {
381 $metadata = $file->convertMetadataVersion( $metadata, $version );
383 $vals['metadata'] = $metadata ? self
::processMetaData( $metadata, $result ) : null;
387 $vals['mime'] = $file->getMimeType();
391 $vals['mediatype'] = $file->getMediaType();
394 if ( $archive && $file->isOld() ) {
395 $vals['archivename'] = $file->getArchiveName();
399 $vals['bitdepth'] = $file->getBitDepth();
407 * @param $metadata Array
408 * @param $result ApiResult
411 public static function processMetaData( $metadata, $result ) {
413 if ( is_array( $metadata ) ) {
414 foreach ( $metadata as $key => $value ) {
415 $r = array( 'name' => $key );
416 if ( is_array( $value ) ) {
417 $r['value'] = self
::processMetaData( $value, $result );
419 $r['value'] = $value;
424 $result->setIndexedTagName( $retval, 'metadata' );
428 public function getCacheMode( $params ) {
436 protected function getContinueStr( $img ) {
437 return $img->getOriginalTitle()->getText() .
438 '|' . $img->getTimestamp();
441 public function getAllowedParams() {
444 ApiBase
::PARAM_ISMULTI
=> true,
445 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
446 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
449 ApiBase
::PARAM_TYPE
=> 'limit',
450 ApiBase
::PARAM_DFLT
=> 1,
451 ApiBase
::PARAM_MIN
=> 1,
452 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
453 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
456 ApiBase
::PARAM_TYPE
=> 'timestamp'
459 ApiBase
::PARAM_TYPE
=> 'timestamp'
462 ApiBase
::PARAM_TYPE
=> 'integer',
463 ApiBase
::PARAM_DFLT
=> -1
465 'urlheight' => array(
466 ApiBase
::PARAM_TYPE
=> 'integer',
467 ApiBase
::PARAM_DFLT
=> -1
469 'metadataversion' => array(
470 ApiBase
::PARAM_TYPE
=> 'string',
471 ApiBase
::PARAM_DFLT
=> '1',
474 ApiBase
::PARAM_DFLT
=> '',
475 ApiBase
::PARAM_TYPE
=> 'string',
478 'localonly' => false,
483 * Returns all possible parameters to iiprop
485 * @param array $filter List of properties to filter out
489 public static function getPropertyNames( $filter = array() ) {
490 return array_diff( array_keys( self
::getProperties() ), $filter );
494 * Returns array key value pairs of properties and their descriptions
498 private static function getProperties( $modulePrefix = '' ) {
500 'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
501 'user' => ' user - Adds the user who uploaded the image version',
502 'userid' => ' userid - Add the user ID that uploaded the image version',
503 'comment' => ' comment - Comment on the version',
504 'parsedcomment' => ' parsedcomment - Parse the comment on the version',
505 'url' => ' url - Gives URL to the image and the description page',
506 'size' => ' size - Adds the size of the image in bytes and the height, width and page count (if applicable)',
507 'dimensions' => ' dimensions - Alias for size', // For backwards compatibility with Allimages
508 'sha1' => ' sha1 - Adds SHA-1 hash for the image',
509 'mime' => ' mime - Adds MIME type of the image',
510 'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail' .
511 ' (requires url and param ' . $modulePrefix . 'urlwidth)',
512 'mediatype' => ' mediatype - Adds the media type of the image',
513 'metadata' => ' metadata - Lists EXIF metadata for the version of the image',
514 'archivename' => ' archivename - Adds the file name of the archive version for non-latest versions',
515 'bitdepth' => ' bitdepth - Adds the bit depth of the version',
520 * Returns the descriptions for the properties provided by getPropertyNames()
522 * @param array $filter List of properties to filter out
526 public static function getPropertyDescriptions( $filter = array(), $modulePrefix = '' ) {
528 array( 'What image information to get:' ),
529 array_values( array_diff_key( self
::getProperties( $modulePrefix ), array_flip( $filter ) ) )
534 * Return the API documentation for the parameters.
535 * @return Array parameter documentation.
537 public function getParamDescription() {
538 $p = $this->getModulePrefix();
540 'prop' => self
::getPropertyDescriptions( array(), $p ),
541 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
542 'Only the current version of the image can be scaled' ),
543 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
544 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
545 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
546 'limit' => 'How many image revisions to return',
547 'start' => 'Timestamp to start listing from',
548 'end' => 'Timestamp to stop listing at',
549 'metadataversion' => array( "Version of metadata to use. if 'latest' is specified, use latest version.",
550 "Defaults to '1' for backwards compatibility" ),
551 'continue' => 'If the query response includes a continue value, use it here to get another page of results',
552 'localonly' => 'Look only for files in the local repository',
556 public static function getResultPropertiesFiltered( $filter = array() ) {
558 'timestamp' => array(
559 'timestamp' => 'timestamp'
562 'userhidden' => 'boolean',
567 'userhidden' => 'boolean',
568 'userid' => 'integer',
573 'width' => 'integer',
574 'height' => 'integer',
575 'pagecount' => array(
576 ApiBase
::PROP_TYPE
=> 'integer',
577 ApiBase
::PROP_NULLABLE
=> true
580 'dimensions' => array(
582 'width' => 'integer',
583 'height' => 'integer',
584 'pagecount' => array(
585 ApiBase
::PROP_TYPE
=> 'integer',
586 ApiBase
::PROP_NULLABLE
=> true
590 'commenthidden' => 'boolean',
592 ApiBase
::PROP_TYPE
=> 'string',
593 ApiBase
::PROP_NULLABLE
=> true
596 'parsedcomment' => array(
597 'commenthidden' => 'boolean',
598 'parsedcomment' => array(
599 ApiBase
::PROP_TYPE
=> 'string',
600 ApiBase
::PROP_NULLABLE
=> true
604 'filehidden' => 'boolean',
606 ApiBase
::PROP_TYPE
=> 'string',
607 ApiBase
::PROP_NULLABLE
=> true
609 'thumbwidth' => array(
610 ApiBase
::PROP_TYPE
=> 'integer',
611 ApiBase
::PROP_NULLABLE
=> true
613 'thumbheight' => array(
614 ApiBase
::PROP_TYPE
=> 'integer',
615 ApiBase
::PROP_NULLABLE
=> true
617 'thumberror' => array(
618 ApiBase
::PROP_TYPE
=> 'string',
619 ApiBase
::PROP_NULLABLE
=> true
622 ApiBase
::PROP_TYPE
=> 'string',
623 ApiBase
::PROP_NULLABLE
=> true
625 'descriptionurl' => array(
626 ApiBase
::PROP_TYPE
=> 'string',
627 ApiBase
::PROP_NULLABLE
=> true
631 'filehidden' => 'boolean',
633 ApiBase
::PROP_TYPE
=> 'string',
634 ApiBase
::PROP_NULLABLE
=> true
638 'filehidden' => 'boolean',
640 ApiBase
::PROP_TYPE
=> 'string',
641 ApiBase
::PROP_NULLABLE
=> true
644 'thumbmime' => array(
645 'filehidden' => 'boolean',
646 'thumbmime' => array(
647 ApiBase
::PROP_TYPE
=> 'string',
648 ApiBase
::PROP_NULLABLE
=> true
651 'mediatype' => array(
652 'filehidden' => 'boolean',
653 'mediatype' => array(
654 ApiBase
::PROP_TYPE
=> 'string',
655 ApiBase
::PROP_NULLABLE
=> true
658 'archivename' => array(
659 'filehidden' => 'boolean',
660 'archivename' => array(
661 ApiBase
::PROP_TYPE
=> 'string',
662 ApiBase
::PROP_NULLABLE
=> true
666 'filehidden' => 'boolean',
668 ApiBase
::PROP_TYPE
=> 'integer',
669 ApiBase
::PROP_NULLABLE
=> true
673 return array_diff_key( $props, array_flip( $filter ) );
676 public function getResultProperties() {
677 return self
::getResultPropertiesFiltered();
680 public function getDescription() {
681 return 'Returns image information and upload history';
684 public function getPossibleErrors() {
685 $p = $this->getModulePrefix();
686 return array_merge( parent
::getPossibleErrors(), array(
687 array( 'code' => "{$p}urlwidth", 'info' => "{$p}urlheight cannot be used without {$p}urlwidth" ),
688 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
689 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
690 array( 'code' => 'urlparam_urlwidth_mismatch', 'info' => "The width set in {$p}urlparm doesnt't " .
691 "match the one in {$p}urlwidth" ),
695 public function getExamples() {
697 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
698 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
702 public function getHelpUrls() {
703 return 'https://www.mediawiki.org/wiki/API:Properties#imageinfo_.2F_ii';