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 $thumbParams = $this->makeThumbParams( $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 // 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 $this->validateThumbParams( $img, $thumbParams );
121 $fit = $this->addPageSubItem( $pageId,
122 self
::getInfo( $img, $prop, $result, $thumbParams ) );
124 if ( count( $pageIds[NS_IMAGE
] ) == 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 ) );
153 if ( count( $pageIds[NS_IMAGE
] ) == 1 ) {
154 $this->setContinueEnumParameter( 'start',
155 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
157 $this->setContinueEnumParameter( 'continue',
158 $this->getContinueStr( $oldie ) );
169 $data = $this->getResultData();
170 foreach ( $data['query']['pages'] as $pageid => $arr ) {
171 if ( !isset( $arr['imagerepository'] ) ) {
173 array( 'query', 'pages', $pageid ),
174 'imagerepository', ''
177 // The above can't fail because it doesn't increase the result size
183 * From parameters, construct a 'scale' array
184 * @param $params Array:
185 * @return Array or Null: key-val array of 'width' and 'height', or null
187 public function getScale( $params ) {
188 wfDeprecated( __METHOD__
);
189 if ( !isset( $params['urlparam'] ) ) {
190 // In case there are subclasses that
191 // don't have this param set to anything.
192 $params['urlparam'] = null;
194 return $this->makeThumbParams( $params );
197 /* Take parameters for transforming thumbnail, validate and turn into array.
198 * @param $params Array: Parameters from the request.
199 * @return Array or null: If array, suitable to passing to $file->transform.
201 public function makeThumbParams( $params ) {
202 $p = $this->getModulePrefix();
205 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
206 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
209 if ( $params['urlwidth'] != -1 ) {
211 $scale['width'] = $params['urlwidth'];
212 $scale['height'] = $params['urlheight'];
215 if ( $params['urlparam'] ) {
216 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
222 if ( is_array( $params['urlparam'] ) ) {
223 foreach( $params['urlparam'] as $item ) {
224 $parameter = explode( '=', $item, 2 );
226 if ( count( $parameter ) !== 2
227 ||
$parameter[0] === 'width'
228 ||
$parameter[0] === 'height'
230 $this->dieUsage( "Invalid value for {$p}urlparam ($item)", "urlparam" );
232 $scale[$parameter[0]] = $parameter[1];
238 /** Validate the thumb parameters, give error if invalid.
240 * We do this later than makeThumbParams, since we need the image
241 * to know which handler, since handlers can make their own parameters.
242 * @param File $image Image that params are for.
243 * @param Array $thumbParams thumbnail parameters
245 protected function validateThumbParams ( $image, $thumbParams ) {
246 if ( !$thumbParams ) return;
247 $p = $this->getModulePrefix();
249 $h = $image->getHandler();
251 // No handler, so no value for iiurlparam is valid.
252 $this->dieUsage( "Invalid value for {$p}urlparam", "urlparam" );
254 foreach ( $thumbParams as $name => $value ) {
255 if ( !$h->validateParam( $name, $value ) ) {
256 /* This doesn't work well with height=-1 placeholder */
257 if ( $name === 'height' ) continue;
258 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
261 // This could also potentially check normaliseParams as well, However that seems
262 // to fall more into a thumbnail rendering error than a user input error, and
263 // will be checked by the transform functions.
267 * Get result information for an image revision
269 * @param $file File object
270 * @param $prop Array of properties to get (in the keys)
271 * @param $result ApiResult object
272 * @param $thumbParams Array containing 'width' and 'height' items, or null
273 * @return Array: result array
275 static function getInfo( $file, $prop, $result, $thumbParams = null ) {
277 if ( isset( $prop['timestamp'] ) ) {
278 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
280 if ( isset( $prop['user'] ) ||
isset( $prop['userid'] ) ) {
282 if ( isset( $prop['user'] ) ) {
283 $vals['user'] = $file->getUser();
285 if ( isset( $prop['userid'] ) ) {
286 $vals['userid'] = $file->getUser( 'id' );
288 if ( !$file->getUser( 'id' ) ) {
292 if ( isset( $prop['size'] ) ||
isset( $prop['dimensions'] ) ) {
293 $vals['size'] = intval( $file->getSize() );
294 $vals['width'] = intval( $file->getWidth() );
295 $vals['height'] = intval( $file->getHeight() );
297 $pageCount = $file->pageCount();
298 if ( $pageCount !== false ) {
299 $vals['pagecount'] = $pageCount;
302 if ( isset( $prop['url'] ) ) {
303 if ( !is_null( $thumbParams ) && !$file->isOld() ) {
304 $mto = $file->transform( $thumbParams );
305 if ( $mto && !$mto->isError() ) {
306 $vals['thumburl'] = wfExpandUrl( $mto->getUrl() );
308 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
309 // thumbnail sizes for the thumbnail actual size
310 if ( $mto->getUrl() !== $file->getUrl() ) {
311 $vals['thumbwidth'] = intval( $mto->getWidth() );
312 $vals['thumbheight'] = intval( $mto->getHeight() );
314 $vals['thumbwidth'] = intval( $file->getWidth() );
315 $vals['thumbheight'] = intval( $file->getHeight() );
318 if ( isset( $prop['thumbmime'] ) ) {
319 $thumbFile = UnregisteredLocalFile
::newFromPath( $mto->getPath(), false );
320 $vals['thumbmime'] = $thumbFile->getMimeType();
324 $vals['url'] = $file->getFullURL();
325 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
327 if ( isset( $prop['comment'] ) ) {
328 $vals['comment'] = $file->getDescription();
330 if ( isset( $prop['parsedcomment'] ) ) {
332 $vals['parsedcomment'] = $wgUser->getSkin()->formatComment(
333 $file->getDescription(), $file->getTitle() );
336 if ( isset( $prop['sha1'] ) ) {
337 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
339 if ( isset( $prop['metadata'] ) ) {
340 $metadata = $file->getMetadata();
341 $vals['metadata'] = $metadata ? self
::processMetaData( unserialize( $metadata ), $result ) : null;
343 if ( isset( $prop['mime'] ) ) {
344 $vals['mime'] = $file->getMimeType();
347 if ( isset( $prop['archivename'] ) && $file->isOld() ) {
348 $vals['archivename'] = $file->getArchiveName();
351 if ( isset( $prop['bitdepth'] ) ) {
352 $vals['bitdepth'] = $file->getBitDepth();
360 * @param $metadata Array
361 * @param $result ApiResult
364 public static function processMetaData( $metadata, $result ) {
366 if ( is_array( $metadata ) ) {
367 foreach ( $metadata as $key => $value ) {
368 $r = array( 'name' => $key );
369 if ( is_array( $value ) ) {
370 $r['value'] = self
::processMetaData( $value, $result );
372 $r['value'] = $value;
377 $result->setIndexedTagName( $retval, 'metadata' );
381 public function getCacheMode( $params ) {
385 private function getContinueStr( $img ) {
386 return $img->getOriginalTitle()->getText() .
387 '|' . $img->getTimestamp();
390 public function getAllowedParams() {
393 ApiBase
::PARAM_ISMULTI
=> true,
394 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
395 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
398 ApiBase
::PARAM_TYPE
=> 'limit',
399 ApiBase
::PARAM_DFLT
=> 1,
400 ApiBase
::PARAM_MIN
=> 1,
401 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
402 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
405 ApiBase
::PARAM_TYPE
=> 'timestamp'
408 ApiBase
::PARAM_TYPE
=> 'timestamp'
411 ApiBase
::PARAM_TYPE
=> 'integer',
412 ApiBase
::PARAM_DFLT
=> -1
414 'urlheight' => array(
415 ApiBase
::PARAM_TYPE
=> 'integer',
416 ApiBase
::PARAM_DFLT
=> -1
419 ApiBase
::PARAM_ISMULTI
=> true,
426 * Returns all possible parameters to iiprop
428 public static function getPropertyNames() {
437 'dimensions', // For backwards compatibility with Allimages
449 * Return the API documentation for the parameters.
450 * @return {Array} parameter documentation.
452 public function getParamDescription() {
453 $p = $this->getModulePrefix();
456 'What image information to get:',
457 ' timestamp - Adds timestamp for the uploaded version',
458 ' user - Adds the user who uploaded the image version',
459 ' userid - Add the user ID that uploaded the image version',
460 ' comment - Comment on the version',
461 ' parsedcomment - Parse the comment on the version',
462 ' url - Gives URL to the image and the description page',
463 ' size - Adds the size of the image in bytes and the height and width',
464 ' dimensions - Alias for size',
465 ' sha1 - Adds SHA-1 hash for the image',
466 ' mime - Adds MIME type of the image',
467 ' thumbmime - Adds MIME type of the image thumbnail (requires url)',
468 ' metadata - Lists EXIF metadata for the version of the image',
469 ' archivename - Adds the file name of the archive version for non-latest versions',
470 ' bitdepth - Adds the bit depth of the version',
472 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
473 'Only the current version of the image can be scaled' ),
474 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
475 'urlparam' => array( "Other rending parameters, such as page=2 for multipaged documents.",
476 "Multiple parameters should be seperated with a |. {$p}urlwidth must also be used"),
477 'limit' => 'How many image revisions to return',
478 'start' => 'Timestamp to start listing from',
479 'end' => 'Timestamp to stop listing at',
480 'continue' => 'If the query response includes a continue value, use it here to get another page of results'
484 public function getDescription() {
485 return 'Returns image information and upload history';
488 public function getPossibleErrors() {
489 $p = $this->getModulePrefix();
490 return array_merge( parent
::getPossibleErrors(), array(
491 array( 'code' => 'iiurlwidth', 'info' => 'iiurlheight cannot be used without iiurlwidth' ),
492 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
493 array( 'code' => 'urlparam_no_width', 'info' => "iiurlparam requires {$p}urlwidth" ),
497 protected function getExamples() {
499 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
500 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
504 public function getVersion() {
505 return __CLASS__
. ': $Id$';