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, $finalThumbParams ) );
126 if ( count( $pageIds[NS_IMAGE
] ) == 1 ) {
127 // See the 'the user is screwed' comment above
128 $this->setContinueEnumParameter( 'start',
129 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
131 $this->setContinueEnumParameter( 'continue',
132 $this->getContinueStr( $img ) );
138 // Now get the old revisions
139 // Get one more to facilitate query-continue functionality
140 $count = ( $gotOne ?
1 : 0 );
141 $oldies = $img->getHistory( $params['limit'] - $count +
1, $start, $params['end'] );
142 foreach ( $oldies as $oldie ) {
143 if ( ++
$count > $params['limit'] ) {
144 // We've reached the extra one which shows that there are additional pages to be had. Stop here...
145 // Only set a query-continue if there was only one title
146 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
147 $this->setContinueEnumParameter( 'start',
148 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
152 $fit = $this->addPageSubItem( $pageId,
153 self
::getInfo( $oldie, $prop, $result, $finalThumbParams ) );
155 if ( count( $pageIds[NS_IMAGE
] ) == 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 ( !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 String 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 * @return Array: result array
270 static function getInfo( $file, $prop, $result, $thumbParams = null ) {
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'] = '';
319 $vals['parsedcomment'] = $wgUser->getSkin()->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() );
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 substr( $mto->getPath(), strrpos( $mto->getPath(), '.' ) +
1 ),
363 $file->getMimeType(), $thumbParams );
364 $vals['thumbmime'] = $mime;
366 } else if ( $mto && $mto->isError() ) {
367 $vals['thumberror'] = $mto->toText();
370 $vals['url'] = $file->getFullURL();
371 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
375 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
379 $metadata = $file->getMetadata();
380 $vals['metadata'] = $metadata ? self
::processMetaData( unserialize( $metadata ), $result ) : null;
384 $vals['mime'] = $file->getMimeType();
388 $vals['mediatype'] = $file->getMediaType();
391 if ( $archive && $file->isOld() ) {
392 $vals['archivename'] = $file->getArchiveName();
396 $vals['bitdepth'] = $file->getBitDepth();
404 * @param $metadata Array
405 * @param $result ApiResult
408 public static function processMetaData( $metadata, $result ) {
410 if ( is_array( $metadata ) ) {
411 foreach ( $metadata as $key => $value ) {
412 $r = array( 'name' => $key );
413 if ( is_array( $value ) ) {
414 $r['value'] = self
::processMetaData( $value, $result );
416 $r['value'] = $value;
421 $result->setIndexedTagName( $retval, 'metadata' );
425 public function getCacheMode( $params ) {
433 private function getContinueStr( $img ) {
434 return $img->getOriginalTitle()->getText() .
435 '|' . $img->getTimestamp();
438 public function getAllowedParams() {
441 ApiBase
::PARAM_ISMULTI
=> true,
442 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
443 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
446 ApiBase
::PARAM_TYPE
=> 'limit',
447 ApiBase
::PARAM_DFLT
=> 1,
448 ApiBase
::PARAM_MIN
=> 1,
449 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
450 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
453 ApiBase
::PARAM_TYPE
=> 'timestamp'
456 ApiBase
::PARAM_TYPE
=> 'timestamp'
459 ApiBase
::PARAM_TYPE
=> 'integer',
460 ApiBase
::PARAM_DFLT
=> -1
462 'urlheight' => array(
463 ApiBase
::PARAM_TYPE
=> 'integer',
464 ApiBase
::PARAM_DFLT
=> -1
467 ApiBase
::PARAM_DFLT
=> '',
468 ApiBase
::PARAM_TYPE
=> 'string',
475 * Returns all possible parameters to iiprop
477 * @param array $filter List of properties to filter out
482 public static function getPropertyNames( $filter = array() ) {
483 return array_diff( array_keys( self
::getProperties() ), $filter );
487 * Returns array key value pairs of properties and their descriptions
492 private static function getProperties() {
494 'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
495 'user' => ' user - Adds the user who uploaded the image version',
496 'userid' => ' userid - Add the user ID that uploaded the image version',
497 'comment' => ' comment - Comment on the version',
498 'parsedcomment' => ' parsedcomment - Parse the comment on the version',
499 'url' => ' url - Gives URL to the image and the description page',
500 'size' => ' size - Adds the size of the image in bytes and the height, width and page count (if applicable)',
501 'dimensions' => ' dimensions - Alias for size', // For backwards compatibility with Allimages
502 'sha1' => ' sha1 - Adds SHA-1 hash for the image',
503 'mime' => ' mime - Adds MIME type of the image',
504 'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail (requires url)',
505 'mediatype' => ' mediatype - Adds the media type of the image',
506 'metadata' => ' metadata - Lists EXIF metadata for the version of the image',
507 'archivename' => ' archivename - Adds the file name of the archive version for non-latest versions',
508 'bitdepth' => ' bitdepth - Adds the bit depth of the version',
513 * Returns the descriptions for the properties provided by getPropertyNames()
515 * @param array $filter List of properties to filter out
520 public static function getPropertyDescriptions( $filter = array() ) {
522 array( 'What image information to get:' ),
523 array_values( array_diff_key( self
::getProperties(), array_flip( $filter ) ) )
528 * Return the API documentation for the parameters.
529 * @return {Array} parameter documentation.
531 public function getParamDescription() {
532 $p = $this->getModulePrefix();
534 'prop' => self
::getPropertyDescriptions(),
535 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
536 'Only the current version of the image can be scaled' ),
537 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
538 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
539 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
540 'limit' => 'How many image revisions to return',
541 'start' => 'Timestamp to start listing from',
542 'end' => 'Timestamp to stop listing at',
543 'continue' => 'If the query response includes a continue value, use it here to get another page of results'
547 public function getDescription() {
548 return 'Returns image information and upload history';
551 public function getPossibleErrors() {
552 $p = $this->getModulePrefix();
553 return array_merge( parent
::getPossibleErrors(), array(
554 array( 'code' => "{$p}urlwidth", 'info' => "{$p}urlheight cannot be used without {$p}urlwidth" ),
555 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
556 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
557 array( 'code' => 'urlparam_urlwidth_mismatch', 'info' => "The width set in {$p}urlparm doesnt't " .
558 "match the one in {$p}urlwidth" ),
562 protected function getExamples() {
564 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
565 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
569 public function getVersion() {
570 return __CLASS__
. ': $Id$';