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