d95836e8a8e5633d87c4946cbf935b46b95bef8f
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'] )
124 $fit = $this->addPageSubItem( $pageId,
125 self
::getInfo( $img, $prop, $result, $finalThumbParams ) );
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, $finalThumbParams ) );
156 if ( count( $pageIds[NS_IMAGE
] ) == 1 ) {
157 $this->setContinueEnumParameter( 'start',
158 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
160 $this->setContinueEnumParameter( 'continue',
161 $this->getContinueStr( $oldie ) );
172 $data = $this->getResultData();
173 foreach ( $data['query']['pages'] as $pageid => $arr ) {
174 if ( !isset( $arr['imagerepository'] ) ) {
176 array( 'query', 'pages', $pageid ),
177 'imagerepository', ''
180 // The above can't fail because it doesn't increase the result size
186 * From parameters, construct a 'scale' array
187 * @param $params Array: Parameters passed to api.
188 * @return Array or Null: key-val array of 'width' and 'height', or null
190 public function getScale( $params ) {
191 $p = $this->getModulePrefix();
194 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
195 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
198 if ( $params['urlwidth'] != -1 ) {
200 $scale['width'] = $params['urlwidth'];
201 $scale['height'] = $params['urlheight'];
204 if ( $params['urlparam'] ) {
205 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
213 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
215 * We do this later than getScale, since we need the image
216 * to know which handler, since handlers can make their own parameters.
217 * @param File $image Image that params are for.
218 * @param Array $thumbParams thumbnail parameters from getScale
219 * @param String String of otherParams (iiurlparam).
220 * @return Array of parameters for transform.
222 protected function mergeThumbParams ( $image, $thumbParams, $otherParams ) {
223 if ( !$otherParams ) return $thumbParams;
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 * @return Array: result array
269 static function getInfo( $file, $prop, $result, $thumbParams = null ) {
271 if ( isset( $prop['timestamp'] ) ) {
272 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
274 if ( isset( $prop['user'] ) ||
isset( $prop['userid'] ) ) {
276 if ( isset( $prop['user'] ) ) {
277 $vals['user'] = $file->getUser();
279 if ( isset( $prop['userid'] ) ) {
280 $vals['userid'] = $file->getUser( 'id' );
282 if ( !$file->getUser( 'id' ) ) {
286 if ( isset( $prop['size'] ) ||
isset( $prop['dimensions'] ) ) {
287 $vals['size'] = intval( $file->getSize() );
288 $vals['width'] = intval( $file->getWidth() );
289 $vals['height'] = intval( $file->getHeight() );
291 $pageCount = $file->pageCount();
292 if ( $pageCount !== false ) {
293 $vals['pagecount'] = $pageCount;
296 if ( isset( $prop['url'] ) ) {
297 if ( !is_null( $thumbParams ) ) {
298 $mto = $file->transform( $thumbParams );
299 if ( $mto && !$mto->isError() ) {
300 $vals['thumburl'] = wfExpandUrl( $mto->getUrl() );
302 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
303 // thumbnail sizes for the thumbnail actual size
304 if ( $mto->getUrl() !== $file->getUrl() ) {
305 $vals['thumbwidth'] = intval( $mto->getWidth() );
306 $vals['thumbheight'] = intval( $mto->getHeight() );
308 $vals['thumbwidth'] = intval( $file->getWidth() );
309 $vals['thumbheight'] = intval( $file->getHeight() );
312 if ( isset( $prop['thumbmime'] ) ) {
313 $thumbFile = UnregisteredLocalFile
::newFromPath( $mto->getPath(), false );
314 $vals['thumbmime'] = $thumbFile->getMimeType();
317 if ( $mto && $mto->isError() ) {
318 $vals['thumberror'] = $mto->toText();
321 $vals['url'] = $file->getFullURL();
322 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
324 if ( isset( $prop['comment'] ) ) {
325 $vals['comment'] = $file->getDescription();
327 if ( isset( $prop['parsedcomment'] ) ) {
329 $vals['parsedcomment'] = $wgUser->getSkin()->formatComment(
330 $file->getDescription(), $file->getTitle() );
333 if ( isset( $prop['sha1'] ) ) {
334 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
336 if ( isset( $prop['metadata'] ) ) {
337 $metadata = $file->getMetadata();
338 $vals['metadata'] = $metadata ? self
::processMetaData( unserialize( $metadata ), $result ) : null;
340 if ( isset( $prop['mime'] ) ) {
341 $vals['mime'] = $file->getMimeType();
344 if ( isset( $prop['archivename'] ) && $file->isOld() ) {
345 $vals['archivename'] = $file->getArchiveName();
348 if ( isset( $prop['bitdepth'] ) ) {
349 $vals['bitdepth'] = $file->getBitDepth();
357 * @param $metadata Array
358 * @param $result ApiResult
361 public static function processMetaData( $metadata, $result ) {
363 if ( is_array( $metadata ) ) {
364 foreach ( $metadata as $key => $value ) {
365 $r = array( 'name' => $key );
366 if ( is_array( $value ) ) {
367 $r['value'] = self
::processMetaData( $value, $result );
369 $r['value'] = $value;
374 $result->setIndexedTagName( $retval, 'metadata' );
378 public function getCacheMode( $params ) {
382 private function getContinueStr( $img ) {
383 return $img->getOriginalTitle()->getText() .
384 '|' . $img->getTimestamp();
387 public function getAllowedParams() {
390 ApiBase
::PARAM_ISMULTI
=> true,
391 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
392 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
395 ApiBase
::PARAM_TYPE
=> 'limit',
396 ApiBase
::PARAM_DFLT
=> 1,
397 ApiBase
::PARAM_MIN
=> 1,
398 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
399 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
402 ApiBase
::PARAM_TYPE
=> 'timestamp'
405 ApiBase
::PARAM_TYPE
=> 'timestamp'
408 ApiBase
::PARAM_TYPE
=> 'integer',
409 ApiBase
::PARAM_DFLT
=> -1
411 'urlheight' => array(
412 ApiBase
::PARAM_TYPE
=> 'integer',
413 ApiBase
::PARAM_DFLT
=> -1
416 ApiBase
::PARAM_DFLT
=> '',
417 ApiBase
::PARAM_TYPE
=> 'string',
424 * Returns all possible parameters to iiprop
428 public static function getPropertyNames() {
437 'dimensions', // For backwards compatibility with Allimages
448 * Returns the descriptions for the properties provided by getPropertyNames()
453 public static function getPropertyDescriptions() {
455 'What image information to get:',
456 ' timestamp - Adds timestamp for the uploaded version',
457 ' user - Adds the user who uploaded the image version',
458 ' userid - Add the user ID that uploaded the image version',
459 ' comment - Comment on the version',
460 ' parsedcomment - Parse the comment on the version',
461 ' url - Gives URL to the image and the description page',
462 ' size - Adds the size of the image in bytes and the height and width',
463 ' dimensions - Alias for size',
464 ' sha1 - Adds SHA-1 hash for the image',
465 ' mime - Adds MIME type of the image',
466 ' thumbmime - Adds MIME type of the image thumbnail (requires url)',
467 ' metadata - Lists EXIF metadata for the version of the image',
468 ' archivename - Adds the file name of the archive version for non-latest versions',
469 ' bitdepth - Adds the bit depth of the version',
474 * Return the API documentation for the parameters.
475 * @return {Array} parameter documentation.
477 public function getParamDescription() {
478 $p = $this->getModulePrefix();
480 'prop' => self
::getPropertyDescriptions(),
481 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
482 'Only the current version of the image can be scaled' ),
483 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
484 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
485 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
486 'limit' => 'How many image revisions to return',
487 'start' => 'Timestamp to start listing from',
488 'end' => 'Timestamp to stop listing at',
489 'continue' => 'If the query response includes a continue value, use it here to get another page of results'
493 public function getDescription() {
494 return 'Returns image information and upload history';
497 public function getPossibleErrors() {
498 $p = $this->getModulePrefix();
499 return array_merge( parent
::getPossibleErrors(), array(
500 array( 'code' => 'iiurlwidth', 'info' => 'iiurlheight cannot be used without iiurlwidth' ),
501 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
502 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
503 array( 'code' => 'urlparam_urlwidth_mismatch', 'info' => "The width set in {$p}urlparm doesnt't " .
504 "match the one in {$p}urlwidth" ),
508 protected function getExamples() {
510 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
511 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
515 public function getVersion() {
516 return __CLASS__
. ': $Id$';