d95836e8a8e5633d87c4946cbf935b46b95bef8f
[lhc/web/wiklou.git] / includes / api / ApiQueryImageInfo.php
1 <?php
2 /**
3 *
4 *
5 * Created on July 6, 2007
6 *
7 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
8 *
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.
13 *
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.
18 *
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
23 *
24 * @file
25 */
26
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiQueryBase.php' );
30 }
31
32 /**
33 * A query action to get image information and upload history.
34 *
35 * @ingroup API
36 */
37 class ApiQueryImageInfo extends ApiQueryBase {
38
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 ) ) {
43 $prefix = 'ii';
44 }
45 parent::__construct( $query, $moduleName, $prefix );
46 }
47
48 public function execute() {
49 $params = $this->extractRequestParams();
50
51 $prop = array_flip( $params['prop'] );
52
53 $scale = $this->getScale( $params );
54
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
59
60 $skip = false;
61 if ( !is_null( $params['continue'] ) ) {
62 $skip = true;
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' );
67 }
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] );
74 } else {
75 break;
76 }
77 }
78 }
79
80 $result = $this->getResult();
81 $images = RepoGroup::singleton()->findFiles( $titles );
82 foreach ( $images as $img ) {
83 // Skip redirects
84 if ( $img->getOriginalTitle()->isRedirect() ) {
85 continue;
86 }
87
88 $start = $skip ? $fromTimestamp : $params['start'];
89 $pageId = $pageIds[NS_IMAGE][ $img->getOriginalTitle()->getDBkey() ];
90
91 $fit = $result->addValue(
92 array( 'query', 'pages', intval( $pageId ) ),
93 'imagerepository', $img->getRepoName()
94 );
95 if ( !$fit ) {
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() ) );
104 } else {
105 $this->setContinueEnumParameter( 'continue',
106 $this->getContinueStr( $img ) );
107 }
108 break;
109 }
110
111 // Check if we can make the requested thumbnail, and get transform parameters.
112 $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
113
114 // Get information about the current version first
115 // Check that the current version is within the start-end boundaries
116 $gotOne = false;
117 if (
118 ( is_null( $start ) || $img->getTimestamp() <= $start ) &&
119 ( is_null( $params['end'] ) || $img->getTimestamp() >= $params['end'] )
120 )
121 {
122 $gotOne = true;
123
124 $fit = $this->addPageSubItem( $pageId,
125 self::getInfo( $img, $prop, $result, $finalThumbParams ) );
126 if ( !$fit ) {
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() ) );
131 } else {
132 $this->setContinueEnumParameter( 'continue',
133 $this->getContinueStr( $img ) );
134 }
135 break;
136 }
137 }
138
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() ) );
150 }
151 break;
152 }
153 $fit = $this->addPageSubItem( $pageId,
154 self::getInfo( $oldie, $prop, $result, $finalThumbParams ) );
155 if ( !$fit ) {
156 if ( count( $pageIds[NS_IMAGE] ) == 1 ) {
157 $this->setContinueEnumParameter( 'start',
158 wfTimestamp( TS_ISO_8601, $oldie->getTimestamp() ) );
159 } else {
160 $this->setContinueEnumParameter( 'continue',
161 $this->getContinueStr( $oldie ) );
162 }
163 break;
164 }
165 }
166 if ( !$fit ) {
167 break;
168 }
169 $skip = false;
170 }
171
172 $data = $this->getResultData();
173 foreach ( $data['query']['pages'] as $pageid => $arr ) {
174 if ( !isset( $arr['imagerepository'] ) ) {
175 $result->addValue(
176 array( 'query', 'pages', $pageid ),
177 'imagerepository', ''
178 );
179 }
180 // The above can't fail because it doesn't increase the result size
181 }
182 }
183 }
184
185 /**
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
189 */
190 public function getScale( $params ) {
191 $p = $this->getModulePrefix();
192
193 // Height and width.
194 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
195 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
196 }
197
198 if ( $params['urlwidth'] != -1 ) {
199 $scale = array();
200 $scale['width'] = $params['urlwidth'];
201 $scale['height'] = $params['urlheight'];
202 } else {
203 $scale = null;
204 if ( $params['urlparam'] ) {
205 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
206 }
207 return $scale;
208 }
209
210 return $scale;
211 }
212
213 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
214 *
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.
221 */
222 protected function mergeThumbParams ( $image, $thumbParams, $otherParams ) {
223 if ( !$otherParams ) return $thumbParams;
224 $p = $this->getModulePrefix();
225
226 $h = $image->getHandler();
227 if ( !$h ) {
228 $this->setWarning( 'Could not create thumbnail because ' .
229 $image->getName() . ' does not have an associated image handler' );
230 return $thumbParams;
231 }
232
233 $paramList = $h->parseParamString( $otherParams );
234 if ( !$paramList ) {
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
238 // handlers.
239 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
240 . '. Using only width and height' );
241 return $thumbParams;
242 }
243
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" );
248 }
249 }
250
251 foreach ( $paramList as $name => $value ) {
252 if ( !$h->validateParam( $name, $value ) ) {
253 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
254 }
255 }
256
257 return $thumbParams + $paramList;
258 }
259
260 /**
261 * Get result information for an image revision
262 *
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
268 */
269 static function getInfo( $file, $prop, $result, $thumbParams = null ) {
270 $vals = array();
271 if ( isset( $prop['timestamp'] ) ) {
272 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $file->getTimestamp() );
273 }
274 if ( isset( $prop['user'] ) || isset( $prop['userid'] ) ) {
275
276 if ( isset( $prop['user'] ) ) {
277 $vals['user'] = $file->getUser();
278 }
279 if ( isset( $prop['userid'] ) ) {
280 $vals['userid'] = $file->getUser( 'id' );
281 }
282 if ( !$file->getUser( 'id' ) ) {
283 $vals['anon'] = '';
284 }
285 }
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() );
290
291 $pageCount = $file->pageCount();
292 if ( $pageCount !== false ) {
293 $vals['pagecount'] = $pageCount;
294 }
295 }
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() );
301
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() );
307 } else {
308 $vals['thumbwidth'] = intval( $file->getWidth() );
309 $vals['thumbheight'] = intval( $file->getHeight() );
310 }
311
312 if ( isset( $prop['thumbmime'] ) ) {
313 $thumbFile = UnregisteredLocalFile::newFromPath( $mto->getPath(), false );
314 $vals['thumbmime'] = $thumbFile->getMimeType();
315 }
316 }
317 if ( $mto && $mto->isError() ) {
318 $vals['thumberror'] = $mto->toText();
319 }
320 }
321 $vals['url'] = $file->getFullURL();
322 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
323 }
324 if ( isset( $prop['comment'] ) ) {
325 $vals['comment'] = $file->getDescription();
326 }
327 if ( isset( $prop['parsedcomment'] ) ) {
328 global $wgUser;
329 $vals['parsedcomment'] = $wgUser->getSkin()->formatComment(
330 $file->getDescription(), $file->getTitle() );
331 }
332
333 if ( isset( $prop['sha1'] ) ) {
334 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
335 }
336 if ( isset( $prop['metadata'] ) ) {
337 $metadata = $file->getMetadata();
338 $vals['metadata'] = $metadata ? self::processMetaData( unserialize( $metadata ), $result ) : null;
339 }
340 if ( isset( $prop['mime'] ) ) {
341 $vals['mime'] = $file->getMimeType();
342 }
343
344 if ( isset( $prop['archivename'] ) && $file->isOld() ) {
345 $vals['archivename'] = $file->getArchiveName();
346 }
347
348 if ( isset( $prop['bitdepth'] ) ) {
349 $vals['bitdepth'] = $file->getBitDepth();
350 }
351
352 return $vals;
353 }
354
355 /*
356 *
357 * @param $metadata Array
358 * @param $result ApiResult
359 * @return Array
360 */
361 public static function processMetaData( $metadata, $result ) {
362 $retval = array();
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 );
368 } else {
369 $r['value'] = $value;
370 }
371 $retval[] = $r;
372 }
373 }
374 $result->setIndexedTagName( $retval, 'metadata' );
375 return $retval;
376 }
377
378 public function getCacheMode( $params ) {
379 return 'public';
380 }
381
382 private function getContinueStr( $img ) {
383 return $img->getOriginalTitle()->getText() .
384 '|' . $img->getTimestamp();
385 }
386
387 public function getAllowedParams() {
388 return array(
389 'prop' => array(
390 ApiBase::PARAM_ISMULTI => true,
391 ApiBase::PARAM_DFLT => 'timestamp|user',
392 ApiBase::PARAM_TYPE => self::getPropertyNames()
393 ),
394 'limit' => array(
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
400 ),
401 'start' => array(
402 ApiBase::PARAM_TYPE => 'timestamp'
403 ),
404 'end' => array(
405 ApiBase::PARAM_TYPE => 'timestamp'
406 ),
407 'urlwidth' => array(
408 ApiBase::PARAM_TYPE => 'integer',
409 ApiBase::PARAM_DFLT => -1
410 ),
411 'urlheight' => array(
412 ApiBase::PARAM_TYPE => 'integer',
413 ApiBase::PARAM_DFLT => -1
414 ),
415 'urlparam' => array(
416 ApiBase::PARAM_DFLT => '',
417 ApiBase::PARAM_TYPE => 'string',
418 ),
419 'continue' => null,
420 );
421 }
422
423 /**
424 * Returns all possible parameters to iiprop
425 * @static
426 * @return Array
427 */
428 public static function getPropertyNames() {
429 return array(
430 'timestamp',
431 'user',
432 'userid',
433 'comment',
434 'parsedcomment',
435 'url',
436 'size',
437 'dimensions', // For backwards compatibility with Allimages
438 'sha1',
439 'mime',
440 'thumbmime',
441 'metadata',
442 'archivename',
443 'bitdepth',
444 );
445 }
446
447 /**
448 * Returns the descriptions for the properties provided by getPropertyNames()
449 *
450 * @static
451 * @return array
452 */
453 public static function getPropertyDescriptions() {
454 return array(
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',
470 );
471 }
472
473 /**
474 * Return the API documentation for the parameters.
475 * @return {Array} parameter documentation.
476 */
477 public function getParamDescription() {
478 $p = $this->getModulePrefix();
479 return array(
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'
490 );
491 }
492
493 public function getDescription() {
494 return 'Returns image information and upload history';
495 }
496
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" ),
505 ) );
506 }
507
508 protected function getExamples() {
509 return array(
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',
512 );
513 }
514
515 public function getVersion() {
516 return __CLASS__ . ': $Id$';
517 }
518 }