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 $archive = isset( $prop['archivename'] );
333 $bitdepth = isset( $prop['bitdepth'] );
335 if ( ( $url ||
$sha1 ||
$meta ||
$mime ||
$archive ||
$bitdepth )
336 && $file->isDeleted( File
::DELETED_FILE
) ) {
337 $vals['filehidden'] = '';
339 //Early return, tidier than indenting all following things one level
344 if ( !is_null( $thumbParams ) ) {
345 $mto = $file->transform( $thumbParams );
346 if ( $mto && !$mto->isError() ) {
347 $vals['thumburl'] = wfExpandUrl( $mto->getUrl() );
349 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
350 // thumbnail sizes for the thumbnail actual size
351 if ( $mto->getUrl() !== $file->getUrl() ) {
352 $vals['thumbwidth'] = intval( $mto->getWidth() );
353 $vals['thumbheight'] = intval( $mto->getHeight() );
355 $vals['thumbwidth'] = intval( $file->getWidth() );
356 $vals['thumbheight'] = intval( $file->getHeight() );
359 if ( isset( $prop['thumbmime'] ) ) {
360 $thumbFile = UnregisteredLocalFile
::newFromPath( $mto->getPath(), false );
361 $vals['thumbmime'] = $thumbFile->getMimeType();
363 } else if ( $mto && $mto->isError() ) {
364 $vals['thumberror'] = $mto->toText();
367 $vals['url'] = $file->getFullURL();
368 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
372 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
376 $metadata = $file->getMetadata();
377 $vals['metadata'] = $metadata ? self
::processMetaData( unserialize( $metadata ), $result ) : null;
381 $vals['mime'] = $file->getMimeType();
384 if ( $archive && $file->isOld() ) {
385 $vals['archivename'] = $file->getArchiveName();
389 $vals['bitdepth'] = $file->getBitDepth();
397 * @param $metadata Array
398 * @param $result ApiResult
401 public static function processMetaData( $metadata, $result ) {
403 if ( is_array( $metadata ) ) {
404 foreach ( $metadata as $key => $value ) {
405 $r = array( 'name' => $key );
406 if ( is_array( $value ) ) {
407 $r['value'] = self
::processMetaData( $value, $result );
409 $r['value'] = $value;
414 $result->setIndexedTagName( $retval, 'metadata' );
418 public function getCacheMode( $params ) {
426 private function getContinueStr( $img ) {
427 return $img->getOriginalTitle()->getText() .
428 '|' . $img->getTimestamp();
431 public function getAllowedParams() {
434 ApiBase
::PARAM_ISMULTI
=> true,
435 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
436 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
439 ApiBase
::PARAM_TYPE
=> 'limit',
440 ApiBase
::PARAM_DFLT
=> 1,
441 ApiBase
::PARAM_MIN
=> 1,
442 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
443 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
446 ApiBase
::PARAM_TYPE
=> 'timestamp'
449 ApiBase
::PARAM_TYPE
=> 'timestamp'
452 ApiBase
::PARAM_TYPE
=> 'integer',
453 ApiBase
::PARAM_DFLT
=> -1
455 'urlheight' => array(
456 ApiBase
::PARAM_TYPE
=> 'integer',
457 ApiBase
::PARAM_DFLT
=> -1
460 ApiBase
::PARAM_DFLT
=> '',
461 ApiBase
::PARAM_TYPE
=> 'string',
468 * Returns all possible parameters to iiprop
472 public static function getPropertyNames() {
481 'dimensions', // For backwards compatibility with Allimages
492 * Returns the descriptions for the properties provided by getPropertyNames()
497 public static function getPropertyDescriptions() {
499 'What image information to get:',
500 ' timestamp - Adds timestamp for the uploaded version',
501 ' user - Adds the user who uploaded the image version',
502 ' userid - Add the user ID that uploaded the image version',
503 ' comment - Comment on the version',
504 ' parsedcomment - Parse the comment on the version',
505 ' url - Gives URL to the image and the description page',
506 ' size - Adds the size of the image in bytes and the height, width and page count (if applicable)',
507 ' dimensions - Alias for size',
508 ' sha1 - Adds SHA-1 hash for the image',
509 ' mime - Adds MIME type of the image',
510 ' thumbmime - Adds MIME type of the image thumbnail (requires url)',
511 ' metadata - Lists EXIF metadata for the version of the image',
512 ' archivename - Adds the file name of the archive version for non-latest versions',
513 ' bitdepth - Adds the bit depth of the version',
518 * Return the API documentation for the parameters.
519 * @return {Array} parameter documentation.
521 public function getParamDescription() {
522 $p = $this->getModulePrefix();
524 'prop' => self
::getPropertyDescriptions(),
525 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
526 'Only the current version of the image can be scaled' ),
527 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
528 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
529 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
530 'limit' => 'How many image revisions to return',
531 'start' => 'Timestamp to start listing from',
532 'end' => 'Timestamp to stop listing at',
533 'continue' => 'If the query response includes a continue value, use it here to get another page of results'
537 public function getDescription() {
538 return 'Returns image information and upload history';
541 public function getPossibleErrors() {
542 $p = $this->getModulePrefix();
543 return array_merge( parent
::getPossibleErrors(), array(
544 array( 'code' => "{$p}urlwidth", 'info' => "{$p}urlheight cannot be used without {$p}urlwidth" ),
545 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
546 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
547 array( 'code' => 'urlparam_urlwidth_mismatch', 'info' => "The width set in {$p}urlparm doesnt't " .
548 "match the one in {$p}urlwidth" ),
552 protected function getExamples() {
554 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
555 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
559 public function getVersion() {
560 return __CLASS__
. ': $Id$';