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
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiQueryBase.php' );
33 * A query action to get image information and upload history.
37 class ApiQueryImageInfo
extends ApiQueryBase
{
39 public function __construct( $query, $moduleName, $prefix = 'ii' ) {
40 // We allow a subclass to override the prefix, to create a related API module.
41 // Some other parts of MediaWiki construct this with a null $prefix, which used to be ignored when this only took two arguments
42 if ( is_null( $prefix ) ) {
45 parent
::__construct( $query, $moduleName, $prefix );
48 public function execute() {
49 $params = $this->extractRequestParams();
51 $prop = array_flip( $params['prop'] );
53 $scale = $this->getScale( $params );
55 $pageIds = $this->getPageSet()->getAllTitlesByNamespace();
56 if ( !empty( $pageIds[NS_FILE
] ) ) {
57 $titles = array_keys( $pageIds[NS_FILE
] );
58 asort( $titles ); // Ensure the order is always the same
61 if ( !is_null( $params['continue'] ) ) {
63 $cont = explode( '|', $params['continue'] );
64 if ( count( $cont ) != 2 ) {
65 $this->dieUsage( 'Invalid continue param. You should pass the original ' .
66 'value returned by the previous query', '_badcontinue' );
68 $fromTitle = strval( $cont[0] );
69 $fromTimestamp = $cont[1];
70 // Filter out any titles before $fromTitle
71 foreach ( $titles as $key => $title ) {
72 if ( $title < $fromTitle ) {
73 unset( $titles[$key] );
80 $result = $this->getResult();
81 $images = RepoGroup
::singleton()->findFiles( $titles );
82 foreach ( $images as $img ) {
84 if ( $img->getOriginalTitle()->isRedirect() ) {
88 $start = $skip ?
$fromTimestamp : $params['start'];
89 $pageId = $pageIds[NS_IMAGE
][ $img->getOriginalTitle()->getDBkey() ];
91 $fit = $result->addValue(
92 array( 'query', 'pages', intval( $pageId ) ),
93 'imagerepository', $img->getRepoName()
96 if ( count( $pageIds[NS_IMAGE
] ) == 1 ) {
97 // The user is screwed. imageinfo can't be solely
98 // responsible for exceeding the limit in this case,
99 // so set a query-continue that just returns the same
100 // thing again. When the violating queries have been
101 // out-continued, the result will get through
102 $this->setContinueEnumParameter( 'start',
103 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
105 $this->setContinueEnumParameter( 'continue',
106 $this->getContinueStr( $img ) );
111 // Check if we can make the requested thumbnail, and get transform parameters.
112 $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
114 // Get information about the current version first
115 // Check that the current version is within the start-end boundaries
118 ( is_null( $start ) ||
$img->getTimestamp() <= $start ) &&
119 ( is_null( $params['end'] ) ||
$img->getTimestamp() >= $params['end'] )
123 $fit = $this->addPageSubItem( $pageId,
124 self
::getInfo( $img, $prop, $result,
125 $finalThumbParams, $params['metadataversion'] ) );
127 if ( count( $pageIds[NS_IMAGE
] ) == 1 ) {
128 // See the 'the user is screwed' comment above
129 $this->setContinueEnumParameter( 'start',
130 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
132 $this->setContinueEnumParameter( 'continue',
133 $this->getContinueStr( $img ) );
139 // Now get the old revisions
140 // Get one more to facilitate query-continue functionality
141 $count = ( $gotOne ?
1 : 0 );
142 $oldies = $img->getHistory( $params['limit'] - $count +
1, $start, $params['end'] );
143 foreach ( $oldies as $oldie ) {
144 if ( ++
$count > $params['limit'] ) {
145 // We've reached the extra one which shows that there are additional pages to be had. Stop here...
146 // Only set a query-continue if there was only one title
147 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
148 $this->setContinueEnumParameter( 'start',
149 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
153 $fit = $this->addPageSubItem( $pageId,
154 self
::getInfo( $oldie, $prop, $result,
155 $finalThumbParams, $params['metadataversion'] ) );
157 if ( count( $pageIds[NS_IMAGE
] ) == 1 ) {
158 $this->setContinueEnumParameter( 'start',
159 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
161 $this->setContinueEnumParameter( 'continue',
162 $this->getContinueStr( $oldie ) );
173 $data = $this->getResultData();
174 foreach ( $data['query']['pages'] as $pageid => $arr ) {
175 if ( !isset( $arr['imagerepository'] ) ) {
177 array( 'query', 'pages', $pageid ),
178 'imagerepository', ''
181 // The above can't fail because it doesn't increase the result size
187 * From parameters, construct a 'scale' array
188 * @param $params Array: Parameters passed to api.
189 * @return Array or Null: key-val array of 'width' and 'height', or null
191 public function getScale( $params ) {
192 $p = $this->getModulePrefix();
195 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
196 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
199 if ( $params['urlwidth'] != -1 ) {
201 $scale['width'] = $params['urlwidth'];
202 $scale['height'] = $params['urlheight'];
205 if ( $params['urlparam'] ) {
206 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
214 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
216 * We do this later than getScale, since we need the image
217 * to know which handler, since handlers can make their own parameters.
218 * @param File $image Image that params are for.
219 * @param Array $thumbParams thumbnail parameters from getScale
220 * @param String $otherParams of otherParams (iiurlparam).
221 * @return Array of parameters for transform.
223 protected function mergeThumbParams ( $image, $thumbParams, $otherParams ) {
224 if ( !$otherParams ) {
227 $p = $this->getModulePrefix();
229 $h = $image->getHandler();
231 $this->setWarning( 'Could not create thumbnail because ' .
232 $image->getName() . ' does not have an associated image handler' );
236 $paramList = $h->parseParamString( $otherParams );
238 // Just set a warning (instead of dieUsage), as in many cases
239 // we could still render the image using width and height parameters,
240 // and this type of thing could happen between different versions of
242 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
243 . '. Using only width and height' );
247 if ( isset( $paramList['width'] ) ) {
248 if ( intval( $paramList['width'] ) != intval( $thumbParams['width'] ) ) {
249 $this->dieUsage( "{$p}urlparam had width of {$paramList['width']} but "
250 . "{$p}urlwidth was {$thumbParams['width']}", "urlparam_urlwidth_mismatch" );
254 foreach ( $paramList as $name => $value ) {
255 if ( !$h->validateParam( $name, $value ) ) {
256 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
260 return $thumbParams +
$paramList;
264 * Get result information for an image revision
266 * @param $file File object
267 * @param $prop Array of properties to get (in the keys)
268 * @param $result ApiResult object
269 * @param $thumbParams Array containing 'width' and 'height' items, or null
270 * @param $version string Version of image metadata (for things like jpeg which have different versions).
271 * @return Array: result array
273 static function getInfo( $file, $prop, $result, $thumbParams = null, $version = 'latest' ) {
275 // Timestamp is shown even if the file is revdelete'd in interface
277 if ( isset( $prop['timestamp'] ) ) {
278 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
281 $user = isset( $prop['user'] );
282 $userid = isset( $prop['userid'] );
284 if ( $user ||
$userid ) {
285 if ( $file->isDeleted( File
::DELETED_USER
) ) {
286 $vals['userhidden'] = '';
289 $vals['user'] = $file->getUser();
292 $vals['userid'] = $file->getUser( 'id' );
294 if ( !$file->getUser( 'id' ) ) {
300 // This is shown even if the file is revdelete'd in interface
302 if ( isset( $prop['size'] ) ||
isset( $prop['dimensions'] ) ) {
303 $vals['size'] = intval( $file->getSize() );
304 $vals['width'] = intval( $file->getWidth() );
305 $vals['height'] = intval( $file->getHeight() );
307 $pageCount = $file->pageCount();
308 if ( $pageCount !== false ) {
309 $vals['pagecount'] = $pageCount;
313 $pcomment = isset( $prop['parsedcomment'] );
314 $comment = isset( $prop['comment'] );
316 if ( $pcomment ||
$comment ) {
317 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
318 $vals['commenthidden'] = '';
322 $vals['parsedcomment'] = $wgUser->getSkin()->formatComment(
323 $file->getDescription(), $file->getTitle() );
326 $vals['comment'] = $file->getDescription();
331 $url = isset( $prop['url'] );
332 $sha1 = isset( $prop['sha1'] );
333 $meta = isset( $prop['metadata'] );
334 $mime = isset( $prop['mime'] );
335 $mediatype = isset( $prop['mediatype'] );
336 $archive = isset( $prop['archivename'] );
337 $bitdepth = isset( $prop['bitdepth'] );
339 if ( ( $url ||
$sha1 ||
$meta ||
$mime ||
$mediatype ||
$archive ||
$bitdepth )
340 && $file->isDeleted( File
::DELETED_FILE
) ) {
341 $vals['filehidden'] = '';
343 //Early return, tidier than indenting all following things one level
348 if ( !is_null( $thumbParams ) ) {
349 $mto = $file->transform( $thumbParams );
350 if ( $mto && !$mto->isError() ) {
351 $vals['thumburl'] = wfExpandUrl( $mto->getUrl() );
353 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
354 // thumbnail sizes for the thumbnail actual size
355 if ( $mto->getUrl() !== $file->getUrl() ) {
356 $vals['thumbwidth'] = intval( $mto->getWidth() );
357 $vals['thumbheight'] = intval( $mto->getHeight() );
359 $vals['thumbwidth'] = intval( $file->getWidth() );
360 $vals['thumbheight'] = intval( $file->getHeight() );
363 if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
364 list( $ext, $mime ) = $file->getHandler()->getThumbType(
365 substr( $mto->getPath(), strrpos( $mto->getPath(), '.' ) +
1 ),
366 $file->getMimeType(), $thumbParams );
367 $vals['thumbmime'] = $mime;
369 } else if ( $mto && $mto->isError() ) {
370 $vals['thumberror'] = $mto->toText();
373 $vals['url'] = $file->getFullURL();
374 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
378 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
382 $metadata = unserialize( $file->getMetadata() );
383 if ( $version !== 'latest' ) {
384 $metadata = $file->convertMetadataVersion( $metadata, $version );
386 $vals['metadata'] = $metadata ? self
::processMetaData( $metadata, $result ) : null;
390 $vals['mime'] = $file->getMimeType();
394 $vals['mediatype'] = $file->getMediaType();
397 if ( $archive && $file->isOld() ) {
398 $vals['archivename'] = $file->getArchiveName();
402 $vals['bitdepth'] = $file->getBitDepth();
410 * @param $metadata Array
411 * @param $result ApiResult
414 public static function processMetaData( $metadata, $result ) {
416 if ( is_array( $metadata ) ) {
417 foreach ( $metadata as $key => $value ) {
418 $r = array( 'name' => $key );
419 if ( is_array( $value ) ) {
420 $r['value'] = self
::processMetaData( $value, $result );
422 $r['value'] = $value;
427 $result->setIndexedTagName( $retval, 'metadata' );
431 public function getCacheMode( $params ) {
439 private function getContinueStr( $img ) {
440 return $img->getOriginalTitle()->getText() .
441 '|' . $img->getTimestamp();
444 public function getAllowedParams() {
447 ApiBase
::PARAM_ISMULTI
=> true,
448 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
449 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
452 ApiBase
::PARAM_TYPE
=> 'limit',
453 ApiBase
::PARAM_DFLT
=> 1,
454 ApiBase
::PARAM_MIN
=> 1,
455 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
456 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
459 ApiBase
::PARAM_TYPE
=> 'timestamp'
462 ApiBase
::PARAM_TYPE
=> 'timestamp'
465 ApiBase
::PARAM_TYPE
=> 'integer',
466 ApiBase
::PARAM_DFLT
=> -1
468 'urlheight' => array(
469 ApiBase
::PARAM_TYPE
=> 'integer',
470 ApiBase
::PARAM_DFLT
=> -1
472 'metadataversion' => array(
473 ApiBase
::PARAM_TYPE
=> 'string',
474 ApiBase
::PARAM_DFLT
=> '1',
477 ApiBase
::PARAM_DFLT
=> '',
478 ApiBase
::PARAM_TYPE
=> 'string',
485 * Returns all possible parameters to iiprop
487 * @param array $filter List of properties to filter out
491 public static function getPropertyNames( $filter = array() ) {
492 return array_diff( array_keys( self
::getProperties() ), $filter );
496 * Returns array key value pairs of properties and their descriptions
500 private static function getProperties() {
502 'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
503 'user' => ' user - Adds the user who uploaded the image version',
504 'userid' => ' userid - Add the user ID that uploaded the image version',
505 'comment' => ' comment - Comment on the version',
506 'parsedcomment' => ' parsedcomment - Parse the comment on the version',
507 'url' => ' url - Gives URL to the image and the description page',
508 'size' => ' size - Adds the size of the image in bytes and the height, width and page count (if applicable)',
509 'dimensions' => ' dimensions - Alias for size', // For backwards compatibility with Allimages
510 'sha1' => ' sha1 - Adds SHA-1 hash for the image',
511 'mime' => ' mime - Adds MIME type of the image',
512 'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail (requires url)',
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() ) {
529 array( 'What image information to get:' ),
530 array_values( array_diff_key( self
::getProperties(), 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(),
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'
556 public function getDescription() {
557 return 'Returns image information and upload history';
560 public function getPossibleErrors() {
561 $p = $this->getModulePrefix();
562 return array_merge( parent
::getPossibleErrors(), array(
563 array( 'code' => "{$p}urlwidth", 'info' => "{$p}urlheight cannot be used without {$p}urlwidth" ),
564 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
565 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
566 array( 'code' => 'urlparam_urlwidth_mismatch', 'info' => "The width set in {$p}urlparm doesnt't " .
567 "match the one in {$p}urlwidth" ),
571 protected function getExamples() {
573 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
574 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
578 public function getVersion() {
579 return __CLASS__
. ': $Id$';