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 $resolveRedirects = $this->getPageSet()->isResolvingRedirects();
80 foreach ( $images as $img ) {
82 if ( $img->getOriginalTitle()->isRedirect() && !$resolveRedirects ) {
86 $start = $skip ?
$fromTimestamp : $params['start'];
87 $pageId = $pageIds[NS_FILE
][$img->getTitle()->getDBkey()];
89 $fit = $result->addValue(
90 array( 'query', 'pages', intval( $pageId ) ),
91 'imagerepository', $img->getRepoName()
94 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
95 // The user is screwed. imageinfo can't be solely
96 // responsible for exceeding the limit in this case,
97 // so set a query-continue that just returns the same
98 // thing again. When the violating queries have been
99 // out-continued, the result will get through
100 $this->setContinueEnumParameter( 'start',
101 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
103 $this->setContinueEnumParameter( 'continue',
104 $this->getContinueStr( $img ) );
109 // Check if we can make the requested thumbnail, and get transform parameters.
110 $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
112 // Get information about the current version first
113 // Check that the current version is within the start-end boundaries
116 ( is_null( $start ) ||
$img->getTimestamp() <= $start ) &&
117 ( is_null( $params['end'] ) ||
$img->getTimestamp() >= $params['end'] )
121 $fit = $this->addPageSubItem( $pageId,
122 self
::getInfo( $img, $prop, $result,
123 $finalThumbParams, $params['metadataversion'] ) );
125 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
126 // See the 'the user is screwed' comment above
127 $this->setContinueEnumParameter( 'start',
128 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
130 $this->setContinueEnumParameter( 'continue',
131 $this->getContinueStr( $img ) );
137 // Now get the old revisions
138 // Get one more to facilitate query-continue functionality
139 $count = ( $gotOne ?
1 : 0 );
140 $oldies = $img->getHistory( $params['limit'] - $count +
1, $start, $params['end'] );
141 foreach ( $oldies as $oldie ) {
142 if ( ++
$count > $params['limit'] ) {
143 // We've reached the extra one which shows that there are additional pages to be had. Stop here...
144 // Only set a query-continue if there was only one title
145 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
146 $this->setContinueEnumParameter( 'start',
147 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
151 $fit = $this->addPageSubItem( $pageId,
152 self
::getInfo( $oldie, $prop, $result,
153 $finalThumbParams, $params['metadataversion'] ) );
155 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
156 $this->setContinueEnumParameter( 'start',
157 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
159 $this->setContinueEnumParameter( 'continue',
160 $this->getContinueStr( $oldie ) );
171 $data = $this->getResultData();
172 foreach ( $data['query']['pages'] as $pageid => $arr ) {
173 if ( is_array( $arr ) && !isset( $arr['imagerepository'] ) ) {
175 array( 'query', 'pages', $pageid ),
176 'imagerepository', ''
179 // The above can't fail because it doesn't increase the result size
185 * From parameters, construct a 'scale' array
186 * @param $params Array: Parameters passed to api.
187 * @return Array or Null: key-val array of 'width' and 'height', or null
189 public function getScale( $params ) {
190 $p = $this->getModulePrefix();
193 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
194 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
197 if ( $params['urlwidth'] != -1 ) {
199 $scale['width'] = $params['urlwidth'];
200 $scale['height'] = $params['urlheight'];
203 if ( $params['urlparam'] ) {
204 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
212 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
214 * We do this later than getScale, since we need the image
215 * to know which handler, since handlers can make their own parameters.
216 * @param File $image Image that params are for.
217 * @param Array $thumbParams thumbnail parameters from getScale
218 * @param String $otherParams of otherParams (iiurlparam).
219 * @return Array of parameters for transform.
221 protected function mergeThumbParams ( $image, $thumbParams, $otherParams ) {
222 if ( !$otherParams ) {
225 $p = $this->getModulePrefix();
227 $h = $image->getHandler();
229 $this->setWarning( 'Could not create thumbnail because ' .
230 $image->getName() . ' does not have an associated image handler' );
234 $paramList = $h->parseParamString( $otherParams );
236 // Just set a warning (instead of dieUsage), as in many cases
237 // we could still render the image using width and height parameters,
238 // and this type of thing could happen between different versions of
240 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
241 . '. Using only width and height' );
245 if ( isset( $paramList['width'] ) ) {
246 if ( intval( $paramList['width'] ) != intval( $thumbParams['width'] ) ) {
247 $this->dieUsage( "{$p}urlparam had width of {$paramList['width']} but "
248 . "{$p}urlwidth was {$thumbParams['width']}", "urlparam_urlwidth_mismatch" );
252 foreach ( $paramList as $name => $value ) {
253 if ( !$h->validateParam( $name, $value ) ) {
254 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
258 return $thumbParams +
$paramList;
262 * Get result information for an image revision
264 * @param $file File object
265 * @param $prop Array of properties to get (in the keys)
266 * @param $result ApiResult object
267 * @param $thumbParams Array containing 'width' and 'height' items, or null
268 * @param $version string Version of image metadata (for things like jpeg which have different versions).
269 * @return Array: result array
271 static function getInfo( $file, $prop, $result, $thumbParams = null, $version = 'latest' ) {
273 // Timestamp is shown even if the file is revdelete'd in interface
275 if ( isset( $prop['timestamp'] ) ) {
276 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
279 $user = isset( $prop['user'] );
280 $userid = isset( $prop['userid'] );
282 if ( $user ||
$userid ) {
283 if ( $file->isDeleted( File
::DELETED_USER
) ) {
284 $vals['userhidden'] = '';
287 $vals['user'] = $file->getUser();
290 $vals['userid'] = $file->getUser( 'id' );
292 if ( !$file->getUser( 'id' ) ) {
298 // This is shown even if the file is revdelete'd in interface
300 if ( isset( $prop['size'] ) ||
isset( $prop['dimensions'] ) ) {
301 $vals['size'] = intval( $file->getSize() );
302 $vals['width'] = intval( $file->getWidth() );
303 $vals['height'] = intval( $file->getHeight() );
305 $pageCount = $file->pageCount();
306 if ( $pageCount !== false ) {
307 $vals['pagecount'] = $pageCount;
311 $pcomment = isset( $prop['parsedcomment'] );
312 $comment = isset( $prop['comment'] );
314 if ( $pcomment ||
$comment ) {
315 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
316 $vals['commenthidden'] = '';
319 $vals['parsedcomment'] = Linker
::formatComment(
320 $file->getDescription(), $file->getTitle() );
323 $vals['comment'] = $file->getDescription();
328 $url = isset( $prop['url'] );
329 $sha1 = isset( $prop['sha1'] );
330 $meta = isset( $prop['metadata'] );
331 $mime = isset( $prop['mime'] );
332 $mediatype = isset( $prop['mediatype'] );
333 $archive = isset( $prop['archivename'] );
334 $bitdepth = isset( $prop['bitdepth'] );
336 if ( ( $url ||
$sha1 ||
$meta ||
$mime ||
$mediatype ||
$archive ||
$bitdepth )
337 && $file->isDeleted( File
::DELETED_FILE
) ) {
338 $vals['filehidden'] = '';
340 //Early return, tidier than indenting all following things one level
345 if ( !is_null( $thumbParams ) ) {
346 $mto = $file->transform( $thumbParams );
347 if ( $mto && !$mto->isError() ) {
348 $vals['thumburl'] = wfExpandUrl( $mto->getUrl(), PROTO_CURRENT
);
350 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
351 // thumbnail sizes for the thumbnail actual size
352 if ( $mto->getUrl() !== $file->getUrl() ) {
353 $vals['thumbwidth'] = intval( $mto->getWidth() );
354 $vals['thumbheight'] = intval( $mto->getHeight() );
356 $vals['thumbwidth'] = intval( $file->getWidth() );
357 $vals['thumbheight'] = intval( $file->getHeight() );
360 if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
361 list( $ext, $mime ) = $file->getHandler()->getThumbType(
362 $mto->getExtension(), $file->getMimeType(), $thumbParams );
363 $vals['thumbmime'] = $mime;
365 } elseif ( $mto && $mto->isError() ) {
366 $vals['thumberror'] = $mto->toText();
369 $vals['url'] = wfExpandUrl( $file->getFullURL(), PROTO_CURRENT
);
370 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl(), PROTO_CURRENT
);
374 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
378 wfSuppressWarnings();
379 $metadata = unserialize( $file->getMetadata() );
381 if ( $metadata && $version !== 'latest' ) {
382 $metadata = $file->convertMetadataVersion( $metadata, $version );
384 $vals['metadata'] = $metadata ? self
::processMetaData( $metadata, $result ) : null;
388 $vals['mime'] = $file->getMimeType();
392 $vals['mediatype'] = $file->getMediaType();
395 if ( $archive && $file->isOld() ) {
396 $vals['archivename'] = $file->getArchiveName();
400 $vals['bitdepth'] = $file->getBitDepth();
408 * @param $metadata Array
409 * @param $result ApiResult
412 public static function processMetaData( $metadata, $result ) {
414 if ( is_array( $metadata ) ) {
415 foreach ( $metadata as $key => $value ) {
416 $r = array( 'name' => $key );
417 if ( is_array( $value ) ) {
418 $r['value'] = self
::processMetaData( $value, $result );
420 $r['value'] = $value;
425 $result->setIndexedTagName( $retval, 'metadata' );
429 public function getCacheMode( $params ) {
437 protected function getContinueStr( $img ) {
438 return $img->getOriginalTitle()->getText() .
439 '|' . $img->getTimestamp();
442 public function getAllowedParams() {
445 ApiBase
::PARAM_ISMULTI
=> true,
446 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
447 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
450 ApiBase
::PARAM_TYPE
=> 'limit',
451 ApiBase
::PARAM_DFLT
=> 1,
452 ApiBase
::PARAM_MIN
=> 1,
453 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
454 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
457 ApiBase
::PARAM_TYPE
=> 'timestamp'
460 ApiBase
::PARAM_TYPE
=> 'timestamp'
463 ApiBase
::PARAM_TYPE
=> 'integer',
464 ApiBase
::PARAM_DFLT
=> -1
466 'urlheight' => array(
467 ApiBase
::PARAM_TYPE
=> 'integer',
468 ApiBase
::PARAM_DFLT
=> -1
470 'metadataversion' => array(
471 ApiBase
::PARAM_TYPE
=> 'string',
472 ApiBase
::PARAM_DFLT
=> '1',
475 ApiBase
::PARAM_DFLT
=> '',
476 ApiBase
::PARAM_TYPE
=> 'string',
479 'localonly' => false,
484 * Returns all possible parameters to iiprop
486 * @param array $filter List of properties to filter out
490 public static function getPropertyNames( $filter = array() ) {
491 return array_diff( array_keys( self
::getProperties() ), $filter );
495 * Returns array key value pairs of properties and their descriptions
499 private static function getProperties( $modulePrefix = '' ) {
501 'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
502 'user' => ' user - Adds the user who uploaded the image version',
503 'userid' => ' userid - Add the user ID that uploaded the image version',
504 'comment' => ' comment - Comment on the version',
505 'parsedcomment' => ' parsedcomment - Parse the comment on the version',
506 'url' => ' url - Gives URL to the image and the description page',
507 'size' => ' size - Adds the size of the image in bytes and the height, width and page count (if applicable)',
508 'dimensions' => ' dimensions - Alias for size', // For backwards compatibility with Allimages
509 'sha1' => ' sha1 - Adds SHA-1 hash for the image',
510 'mime' => ' mime - Adds MIME type of the image',
511 'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail' .
512 ' (requires url and param ' . $modulePrefix . 'urlwidth)',
513 'mediatype' => ' mediatype - Adds the media type of the image',
514 'metadata' => ' metadata - Lists EXIF metadata for the version of the image',
515 'archivename' => ' archivename - Adds the file name of the archive version for non-latest versions',
516 'bitdepth' => ' bitdepth - Adds the bit depth of the version',
521 * Returns the descriptions for the properties provided by getPropertyNames()
523 * @param array $filter List of properties to filter out
527 public static function getPropertyDescriptions( $filter = array(), $modulePrefix = '' ) {
529 array( 'What image information to get:' ),
530 array_values( array_diff_key( self
::getProperties( $modulePrefix ), array_flip( $filter ) ) )
535 * Return the API documentation for the parameters.
536 * @return Array parameter documentation.
538 public function getParamDescription() {
539 $p = $this->getModulePrefix();
541 'prop' => self
::getPropertyDescriptions( array(), $p ),
542 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
543 'Only the current version of the image can be scaled' ),
544 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
545 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
546 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
547 'limit' => 'How many image revisions to return',
548 'start' => 'Timestamp to start listing from',
549 'end' => 'Timestamp to stop listing at',
550 'metadataversion' => array( "Version of metadata to use. if 'latest' is specified, use latest version.",
551 "Defaults to '1' for backwards compatibility" ),
552 'continue' => 'If the query response includes a continue value, use it here to get another page of results',
553 'localonly' => 'Look only for files in the local repository',
557 public static function getResultPropertiesFiltered( $filter = array() ) {
559 'timestamp' => array(
560 'timestamp' => 'timestamp'
563 'userhidden' => 'boolean',
568 'userhidden' => 'boolean',
569 'userid' => 'integer',
574 'width' => 'integer',
575 'height' => 'integer',
576 'pagecount' => array(
577 ApiBase
::PROP_TYPE
=> 'integer',
578 ApiBase
::PROP_NULLABLE
=> true
581 'dimensions' => array(
583 'width' => 'integer',
584 'height' => 'integer',
585 'pagecount' => array(
586 ApiBase
::PROP_TYPE
=> 'integer',
587 ApiBase
::PROP_NULLABLE
=> true
591 'commenthidden' => 'boolean',
593 ApiBase
::PROP_TYPE
=> 'string',
594 ApiBase
::PROP_NULLABLE
=> true
597 'parsedcomment' => array(
598 'commenthidden' => 'boolean',
599 'parsedcomment' => array(
600 ApiBase
::PROP_TYPE
=> 'string',
601 ApiBase
::PROP_NULLABLE
=> true
605 'filehidden' => 'boolean',
607 ApiBase
::PROP_TYPE
=> 'string',
608 ApiBase
::PROP_NULLABLE
=> true
610 'thumbwidth' => array(
611 ApiBase
::PROP_TYPE
=> 'integer',
612 ApiBase
::PROP_NULLABLE
=> true
614 'thumbheight' => array(
615 ApiBase
::PROP_TYPE
=> 'integer',
616 ApiBase
::PROP_NULLABLE
=> true
618 'thumberror' => array(
619 ApiBase
::PROP_TYPE
=> 'string',
620 ApiBase
::PROP_NULLABLE
=> true
623 ApiBase
::PROP_TYPE
=> 'string',
624 ApiBase
::PROP_NULLABLE
=> true
626 'descriptionurl' => array(
627 ApiBase
::PROP_TYPE
=> 'string',
628 ApiBase
::PROP_NULLABLE
=> true
632 'filehidden' => 'boolean',
634 ApiBase
::PROP_TYPE
=> 'string',
635 ApiBase
::PROP_NULLABLE
=> true
639 'filehidden' => 'boolean',
641 ApiBase
::PROP_TYPE
=> 'string',
642 ApiBase
::PROP_NULLABLE
=> true
645 'thumbmime' => array(
646 'filehidden' => 'boolean',
647 'thumbmime' => array(
648 ApiBase
::PROP_TYPE
=> 'string',
649 ApiBase
::PROP_NULLABLE
=> true
652 'mediatype' => array(
653 'filehidden' => 'boolean',
654 'mediatype' => array(
655 ApiBase
::PROP_TYPE
=> 'string',
656 ApiBase
::PROP_NULLABLE
=> true
659 'archivename' => array(
660 'filehidden' => 'boolean',
661 'archivename' => array(
662 ApiBase
::PROP_TYPE
=> 'string',
663 ApiBase
::PROP_NULLABLE
=> true
667 'filehidden' => 'boolean',
669 ApiBase
::PROP_TYPE
=> 'integer',
670 ApiBase
::PROP_NULLABLE
=> true
674 return array_diff_key( $props, array_flip( $filter ) );
677 public function getResultProperties() {
678 return self
::getResultPropertiesFiltered();
681 public function getDescription() {
682 return 'Returns image information and upload history';
685 public function getPossibleErrors() {
686 $p = $this->getModulePrefix();
687 return array_merge( parent
::getPossibleErrors(), array(
688 array( 'code' => "{$p}urlwidth", 'info' => "{$p}urlheight cannot be used without {$p}urlwidth" ),
689 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
690 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
691 array( 'code' => 'urlparam_urlwidth_mismatch', 'info' => "The width set in {$p}urlparm doesnt't " .
692 "match the one in {$p}urlwidth" ),
696 public function getExamples() {
698 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
699 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
703 public function getHelpUrls() {
704 return 'https://www.mediawiki.org/wiki/API:Properties#imageinfo_.2F_ii';