37e216a658e1cdd6bc58330cbaa65bc75ecadcd3
[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 $gotOne = true;
122
123 $fit = $this->addPageSubItem( $pageId,
124 self::getInfo( $img, $prop, $result, $finalThumbParams ) );
125 if ( !$fit ) {
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() ) );
130 } else {
131 $this->setContinueEnumParameter( 'continue',
132 $this->getContinueStr( $img ) );
133 }
134 break;
135 }
136 }
137
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() ) );
149 }
150 break;
151 }
152 $fit = $this->addPageSubItem( $pageId,
153 self::getInfo( $oldie, $prop, $result, $finalThumbParams ) );
154 if ( !$fit ) {
155 if ( count( $pageIds[NS_IMAGE] ) == 1 ) {
156 $this->setContinueEnumParameter( 'start',
157 wfTimestamp( TS_ISO_8601, $oldie->getTimestamp() ) );
158 } else {
159 $this->setContinueEnumParameter( 'continue',
160 $this->getContinueStr( $oldie ) );
161 }
162 break;
163 }
164 }
165 if ( !$fit ) {
166 break;
167 }
168 $skip = false;
169 }
170
171 $data = $this->getResultData();
172 foreach ( $data['query']['pages'] as $pageid => $arr ) {
173 if ( !isset( $arr['imagerepository'] ) ) {
174 $result->addValue(
175 array( 'query', 'pages', $pageid ),
176 'imagerepository', ''
177 );
178 }
179 // The above can't fail because it doesn't increase the result size
180 }
181 }
182 }
183
184 /**
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
188 */
189 public function getScale( $params ) {
190 $p = $this->getModulePrefix();
191
192 // Height and width.
193 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
194 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
195 }
196
197 if ( $params['urlwidth'] != -1 ) {
198 $scale = array();
199 $scale['width'] = $params['urlwidth'];
200 $scale['height'] = $params['urlheight'];
201 } else {
202 $scale = null;
203 if ( $params['urlparam'] ) {
204 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
205 }
206 return $scale;
207 }
208
209 return $scale;
210 }
211
212 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
213 *
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.
220 */
221 protected function mergeThumbParams ( $image, $thumbParams, $otherParams ) {
222 if ( !$otherParams ) return $thumbParams;
223 $p = $this->getModulePrefix();
224
225 $h = $image->getHandler();
226 if ( !$h ) {
227 $this->setWarning( 'Could not create thumbnail because ' .
228 $image->getName() . ' does not have an associated image handler' );
229 return $thumbParams;
230 }
231
232 $paramList = $h->parseParamString( $otherParams );
233 if ( !$paramList ) {
234 // Just set a warning (instead of dieUsage), as in many cases
235 // we could still render the image using width and height parameters,
236 // and this type of thing could happen between different versions of
237 // handlers.
238 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
239 . '. Using only width and height' );
240 return $thumbParams;
241 }
242
243 if ( isset( $paramList['width'] ) ) {
244 if ( intval( $paramList['width'] ) != intval( $thumbParams['width'] ) ) {
245 $this->dieUsage( "{$p}urlparam had width of {$paramList['width']} but "
246 . "{$p}urlwidth was {$thumbParams['width']}", "urlparam_urlwidth_mismatch" );
247 }
248 }
249
250 foreach ( $paramList as $name => $value ) {
251 if ( !$h->validateParam( $name, $value ) ) {
252 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
253 }
254 }
255
256 return $thumbParams + $paramList;
257 }
258
259 /**
260 * Get result information for an image revision
261 *
262 * @param $file File object
263 * @param $prop Array of properties to get (in the keys)
264 * @param $result ApiResult object
265 * @param $thumbParams Array containing 'width' and 'height' items, or null
266 * @return Array: result array
267 */
268 static function getInfo( $file, $prop, $result, $thumbParams = null ) {
269 $vals = array();
270 if ( isset( $prop['timestamp'] ) ) {
271 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $file->getTimestamp() );
272 }
273 if ( isset( $prop['user'] ) || isset( $prop['userid'] ) ) {
274
275 if ( isset( $prop['user'] ) ) {
276 $vals['user'] = $file->getUser();
277 }
278 if ( isset( $prop['userid'] ) ) {
279 $vals['userid'] = $file->getUser( 'id' );
280 }
281 if ( !$file->getUser( 'id' ) ) {
282 $vals['anon'] = '';
283 }
284 }
285 if ( isset( $prop['size'] ) || isset( $prop['dimensions'] ) ) {
286 $vals['size'] = intval( $file->getSize() );
287 $vals['width'] = intval( $file->getWidth() );
288 $vals['height'] = intval( $file->getHeight() );
289
290 $pageCount = $file->pageCount();
291 if ( $pageCount !== false ) {
292 $vals['pagecount'] = $pageCount;
293 }
294 }
295 if ( isset( $prop['url'] ) ) {
296 if ( !is_null( $thumbParams ) ) {
297 $mto = $file->transform( $thumbParams );
298 if ( $mto && !$mto->isError() ) {
299 $vals['thumburl'] = wfExpandUrl( $mto->getUrl() );
300
301 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
302 // thumbnail sizes for the thumbnail actual size
303 if ( $mto->getUrl() !== $file->getUrl() ) {
304 $vals['thumbwidth'] = intval( $mto->getWidth() );
305 $vals['thumbheight'] = intval( $mto->getHeight() );
306 } else {
307 $vals['thumbwidth'] = intval( $file->getWidth() );
308 $vals['thumbheight'] = intval( $file->getHeight() );
309 }
310
311 if ( isset( $prop['thumbmime'] ) ) {
312 $thumbFile = UnregisteredLocalFile::newFromPath( $mto->getPath(), false );
313 $vals['thumbmime'] = $thumbFile->getMimeType();
314 }
315 }
316 if ( $mto && $mto->isError() ) {
317 $vals['thumberror'] = $mto->toText();
318 }
319 }
320 $vals['url'] = $file->getFullURL();
321 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
322 }
323 if ( isset( $prop['comment'] ) ) {
324 $vals['comment'] = $file->getDescription();
325 }
326 if ( isset( $prop['parsedcomment'] ) ) {
327 global $wgUser;
328 $vals['parsedcomment'] = $wgUser->getSkin()->formatComment(
329 $file->getDescription(), $file->getTitle() );
330 }
331
332 if ( isset( $prop['sha1'] ) ) {
333 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
334 }
335 if ( isset( $prop['metadata'] ) ) {
336 $metadata = $file->getMetadata();
337 $vals['metadata'] = $metadata ? self::processMetaData( unserialize( $metadata ), $result ) : null;
338 }
339 if ( isset( $prop['mime'] ) ) {
340 $vals['mime'] = $file->getMimeType();
341 }
342
343 if ( isset( $prop['archivename'] ) && $file->isOld() ) {
344 $vals['archivename'] = $file->getArchiveName();
345 }
346
347 if ( isset( $prop['bitdepth'] ) ) {
348 $vals['bitdepth'] = $file->getBitDepth();
349 }
350
351 return $vals;
352 }
353
354 /**
355 *
356 * @param $metadata Array
357 * @param $result ApiResult
358 * @return Array
359 */
360 public static function processMetaData( $metadata, $result ) {
361 $retval = array();
362 if ( is_array( $metadata ) ) {
363 foreach ( $metadata as $key => $value ) {
364 $r = array( 'name' => $key );
365 if ( is_array( $value ) ) {
366 $r['value'] = self::processMetaData( $value, $result );
367 } else {
368 $r['value'] = $value;
369 }
370 $retval[] = $r;
371 }
372 }
373 $result->setIndexedTagName( $retval, 'metadata' );
374 return $retval;
375 }
376
377 public function getCacheMode( $params ) {
378 return 'public';
379 }
380
381 /**
382 * @param $img File
383 * @return string
384 */
385 private function getContinueStr( $img ) {
386 return $img->getOriginalTitle()->getText() .
387 '|' . $img->getTimestamp();
388 }
389
390 public function getAllowedParams() {
391 return array(
392 'prop' => array(
393 ApiBase::PARAM_ISMULTI => true,
394 ApiBase::PARAM_DFLT => 'timestamp|user',
395 ApiBase::PARAM_TYPE => self::getPropertyNames()
396 ),
397 'limit' => array(
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
403 ),
404 'start' => array(
405 ApiBase::PARAM_TYPE => 'timestamp'
406 ),
407 'end' => array(
408 ApiBase::PARAM_TYPE => 'timestamp'
409 ),
410 'urlwidth' => array(
411 ApiBase::PARAM_TYPE => 'integer',
412 ApiBase::PARAM_DFLT => -1
413 ),
414 'urlheight' => array(
415 ApiBase::PARAM_TYPE => 'integer',
416 ApiBase::PARAM_DFLT => -1
417 ),
418 'urlparam' => array(
419 ApiBase::PARAM_DFLT => '',
420 ApiBase::PARAM_TYPE => 'string',
421 ),
422 'continue' => null,
423 );
424 }
425
426 /**
427 * Returns all possible parameters to iiprop
428 * @static
429 * @return Array
430 */
431 public static function getPropertyNames() {
432 return array(
433 'timestamp',
434 'user',
435 'userid',
436 'comment',
437 'parsedcomment',
438 'url',
439 'size',
440 'dimensions', // For backwards compatibility with Allimages
441 'sha1',
442 'mime',
443 'thumbmime',
444 'metadata',
445 'archivename',
446 'bitdepth',
447 );
448 }
449
450 /**
451 * Returns the descriptions for the properties provided by getPropertyNames()
452 *
453 * @static
454 * @return array
455 */
456 public static function getPropertyDescriptions() {
457 return array(
458 'What image information to get:',
459 ' timestamp - Adds timestamp for the uploaded version',
460 ' user - Adds the user who uploaded the image version',
461 ' userid - Add the user ID that uploaded the image version',
462 ' comment - Comment on the version',
463 ' parsedcomment - Parse the comment on the version',
464 ' url - Gives URL to the image and the description page',
465 ' size - Adds the size of the image in bytes and the height and width',
466 ' dimensions - Alias for size',
467 ' sha1 - Adds SHA-1 hash for the image',
468 ' mime - Adds MIME type of the image',
469 ' thumbmime - Adds MIME type of the image thumbnail (requires url)',
470 ' metadata - Lists EXIF metadata for the version of the image',
471 ' archivename - Adds the file name of the archive version for non-latest versions',
472 ' bitdepth - Adds the bit depth of the version',
473 );
474 }
475
476 /**
477 * Return the API documentation for the parameters.
478 * @return {Array} parameter documentation.
479 */
480 public function getParamDescription() {
481 $p = $this->getModulePrefix();
482 return array(
483 'prop' => self::getPropertyDescriptions(),
484 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
485 'Only the current version of the image can be scaled' ),
486 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
487 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
488 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
489 'limit' => 'How many image revisions to return',
490 'start' => 'Timestamp to start listing from',
491 'end' => 'Timestamp to stop listing at',
492 'continue' => 'If the query response includes a continue value, use it here to get another page of results'
493 );
494 }
495
496 public function getDescription() {
497 return 'Returns image information and upload history';
498 }
499
500 public function getPossibleErrors() {
501 $p = $this->getModulePrefix();
502 return array_merge( parent::getPossibleErrors(), array(
503 array( 'code' => 'iiurlwidth', 'info' => 'iiurlheight cannot be used without iiurlwidth' ),
504 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
505 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
506 array( 'code' => 'urlparam_urlwidth_mismatch', 'info' => "The width set in {$p}urlparm doesnt't " .
507 "match the one in {$p}urlwidth" ),
508 ) );
509 }
510
511 protected function getExamples() {
512 return array(
513 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
514 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
515 );
516 }
517
518 public function getVersion() {
519 return __CLASS__ . ': $Id$';
520 }
521 }