a3e4c953733344fe407458cd6e7057fc6dccc7d3
[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 ) {
223 return $thumbParams;
224 }
225 $p = $this->getModulePrefix();
226
227 $h = $image->getHandler();
228 if ( !$h ) {
229 $this->setWarning( 'Could not create thumbnail because ' .
230 $image->getName() . ' does not have an associated image handler' );
231 return $thumbParams;
232 }
233
234 $paramList = $h->parseParamString( $otherParams );
235 if ( !$paramList ) {
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
239 // handlers.
240 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
241 . '. Using only width and height' );
242 return $thumbParams;
243 }
244
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" );
249 }
250 }
251
252 foreach ( $paramList as $name => $value ) {
253 if ( !$h->validateParam( $name, $value ) ) {
254 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
255 }
256 }
257
258 return $thumbParams + $paramList;
259 }
260
261 /**
262 * Get result information for an image revision
263 *
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
269 */
270 static function getInfo( $file, $prop, $result, $thumbParams = null ) {
271 $vals = array();
272 // Timestamp is shown even if the file is revdelete'd in interface
273 // so do same here.
274 if ( isset( $prop['timestamp'] ) ) {
275 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $file->getTimestamp() );
276 }
277
278 $user = isset( $prop['user'] );
279 $userid = isset( $prop['userid'] );
280
281 if ( $user || $userid ) {
282 if ( $file->isDeleted( File::DELETED_USER ) ) {
283 $vals['userhidden'] = '';
284 } else {
285 if ( $user ) {
286 $vals['user'] = $file->getUser();
287 }
288 if ( $userid ) {
289 $vals['userid'] = $file->getUser( 'id' );
290 }
291 if ( !$file->getUser( 'id' ) ) {
292 $vals['anon'] = '';
293 }
294 }
295 }
296
297 // This is shown even if the file is revdelete'd in interface
298 // so do same here.
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() );
303
304 $pageCount = $file->pageCount();
305 if ( $pageCount !== false ) {
306 $vals['pagecount'] = $pageCount;
307 }
308 }
309
310 $pcomment = isset( $prop['parsedcomment'] );
311 $comment = isset( $prop['comment'] );
312
313 if ( $pcomment || $comment ) {
314 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
315 $vals['commenthidden'] = '';
316 } else {
317 if ( $pcomment ) {
318 global $wgUser;
319 $vals['parsedcomment'] = $wgUser->getSkin()->formatComment(
320 $file->getDescription(), $file->getTitle() );
321 }
322 if ( $comment ) {
323 $vals['comment'] = $file->getDescription();
324 }
325 }
326 }
327
328 $url = isset( $prop['url'] );
329 $sha1 = isset( $prop['sha1'] );
330 $meta = isset( $prop['metadata'] );
331 $mime = isset( $prop['mime'] );
332 $mediatype = isset( $prop['mediatype'] );
333 $archive = isset( $prop['archivename'] );
334 $bitdepth = isset( $prop['bitdepth'] );
335
336 if ( ( $url || $sha1 || $meta || $mime || $mediatype || $archive || $bitdepth )
337 && $file->isDeleted( File::DELETED_FILE ) ) {
338 $vals['filehidden'] = '';
339
340 //Early return, tidier than indenting all following things one level
341 return $vals;
342 }
343
344 if ( $url ) {
345 if ( !is_null( $thumbParams ) ) {
346 $mto = $file->transform( $thumbParams );
347 if ( $mto && !$mto->isError() ) {
348 $vals['thumburl'] = wfExpandUrl( $mto->getUrl() );
349
350 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
351 // thumbnail sizes for the thumbnail actual size
352 if ( $mto->getUrl() !== $file->getUrl() ) {
353 $vals['thumbwidth'] = intval( $mto->getWidth() );
354 $vals['thumbheight'] = intval( $mto->getHeight() );
355 } else {
356 $vals['thumbwidth'] = intval( $file->getWidth() );
357 $vals['thumbheight'] = intval( $file->getHeight() );
358 }
359
360 if ( isset( $prop['thumbmime'] ) ) {
361 $thumbFile = UnregisteredLocalFile::newFromPath( $mto->getPath(), false );
362 $vals['thumbmime'] = $thumbFile->getMimeType();
363 }
364 } else if ( $mto && $mto->isError() ) {
365 $vals['thumberror'] = $mto->toText();
366 }
367 }
368 $vals['url'] = $file->getFullURL();
369 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
370 }
371
372 if ( $sha1 ) {
373 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
374 }
375
376 if ( $meta ) {
377 $metadata = $file->getMetadata();
378 $vals['metadata'] = $metadata ? self::processMetaData( unserialize( $metadata ), $result ) : null;
379 }
380
381 if ( $mime ) {
382 $vals['mime'] = $file->getMimeType();
383 }
384
385 if ( $mediatype ) {
386 $vals['mediatype'] = $file->getMediaType();
387 }
388
389 if ( $archive && $file->isOld() ) {
390 $vals['archivename'] = $file->getArchiveName();
391 }
392
393 if ( $bitdepth ) {
394 $vals['bitdepth'] = $file->getBitDepth();
395 }
396
397 return $vals;
398 }
399
400 /**
401 *
402 * @param $metadata Array
403 * @param $result ApiResult
404 * @return Array
405 */
406 public static function processMetaData( $metadata, $result ) {
407 $retval = array();
408 if ( is_array( $metadata ) ) {
409 foreach ( $metadata as $key => $value ) {
410 $r = array( 'name' => $key );
411 if ( is_array( $value ) ) {
412 $r['value'] = self::processMetaData( $value, $result );
413 } else {
414 $r['value'] = $value;
415 }
416 $retval[] = $r;
417 }
418 }
419 $result->setIndexedTagName( $retval, 'metadata' );
420 return $retval;
421 }
422
423 public function getCacheMode( $params ) {
424 return 'public';
425 }
426
427 /**
428 * @param $img File
429 * @return string
430 */
431 private function getContinueStr( $img ) {
432 return $img->getOriginalTitle()->getText() .
433 '|' . $img->getTimestamp();
434 }
435
436 public function getAllowedParams() {
437 return array(
438 'prop' => array(
439 ApiBase::PARAM_ISMULTI => true,
440 ApiBase::PARAM_DFLT => 'timestamp|user',
441 ApiBase::PARAM_TYPE => self::getPropertyNames()
442 ),
443 'limit' => array(
444 ApiBase::PARAM_TYPE => 'limit',
445 ApiBase::PARAM_DFLT => 1,
446 ApiBase::PARAM_MIN => 1,
447 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
448 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
449 ),
450 'start' => array(
451 ApiBase::PARAM_TYPE => 'timestamp'
452 ),
453 'end' => array(
454 ApiBase::PARAM_TYPE => 'timestamp'
455 ),
456 'urlwidth' => array(
457 ApiBase::PARAM_TYPE => 'integer',
458 ApiBase::PARAM_DFLT => -1
459 ),
460 'urlheight' => array(
461 ApiBase::PARAM_TYPE => 'integer',
462 ApiBase::PARAM_DFLT => -1
463 ),
464 'urlparam' => array(
465 ApiBase::PARAM_DFLT => '',
466 ApiBase::PARAM_TYPE => 'string',
467 ),
468 'continue' => null,
469 );
470 }
471
472 /**
473 * Returns all possible parameters to iiprop
474 * @static
475 * @return Array
476 */
477 public static function getPropertyNames() {
478 return array_keys( self::getProperties() );
479 }
480
481 /**
482 * Returns array key value pairs of
483 *
484 * @static
485 * @return array
486 */
487 private static function getProperties() {
488 return array(
489 'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
490 'user' => ' user - Adds the user who uploaded the image version',
491 'userid' => ' userid - Add the user ID that uploaded the image version',
492 'comment' => ' comment - Comment on the version',
493 'parsedcomment' => ' parsedcomment - Parse the comment on the version',
494 'url' => ' url - Gives URL to the image and the description page',
495 'size' => ' size - Adds the size of the image in bytes and the height, width and page count (if applicable)',
496 'dimensions' => ' dimensions - Alias for size', // For backwards compatibility with Allimages
497 'sha1' => ' sha1 - Adds SHA-1 hash for the image',
498 'mime' => ' mime - Adds MIME type of the image',
499 'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail (requires url)',
500 'mediatype' => ' mediatype - Adds the media type of the image',
501 'metadata' => ' metadata - Lists EXIF metadata for the version of the image',
502 'archivename' => ' archivename - Adds the file name of the archive version for non-latest versions',
503 'bitdepth' => ' bitdepth - Adds the bit depth of the version',
504 );
505 }
506
507 /**
508 * Returns the descriptions for the properties provided by getPropertyNames()
509 *
510 * @static
511 * @return array
512 */
513 public static function getPropertyDescriptions() {
514 return array_merge(
515 array( 'What image information to get:' ),
516 array_values( self::getProperties() )
517 );
518 }
519
520 /**
521 * Return the API documentation for the parameters.
522 * @return {Array} parameter documentation.
523 */
524 public function getParamDescription() {
525 $p = $this->getModulePrefix();
526 return array(
527 'prop' => self::getPropertyDescriptions(),
528 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
529 'Only the current version of the image can be scaled' ),
530 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
531 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
532 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
533 'limit' => 'How many image revisions to return',
534 'start' => 'Timestamp to start listing from',
535 'end' => 'Timestamp to stop listing at',
536 'continue' => 'If the query response includes a continue value, use it here to get another page of results'
537 );
538 }
539
540 public function getDescription() {
541 return 'Returns image information and upload history';
542 }
543
544 public function getPossibleErrors() {
545 $p = $this->getModulePrefix();
546 return array_merge( parent::getPossibleErrors(), array(
547 array( 'code' => "{$p}urlwidth", 'info' => "{$p}urlheight cannot be used without {$p}urlwidth" ),
548 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
549 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
550 array( 'code' => 'urlparam_urlwidth_mismatch', 'info' => "The width set in {$p}urlparm doesnt't " .
551 "match the one in {$p}urlwidth" ),
552 ) );
553 }
554
555 protected function getExamples() {
556 return array(
557 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
558 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
559 );
560 }
561
562 public function getVersion() {
563 return __CLASS__ . ': $Id$';
564 }
565 }