Follow-up r81971: Can't use $this->setWarning() in static context, so append the...
[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 $thumbParams = $this->makeThumbParams( $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
112 $this->validateThumbParams( $img, $thumbParams );
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, $thumbParams ) );
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, $thumbParams ) );
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:
188 * @return Array or Null: key-val array of 'width' and 'height', or null
189 */
190 public function getScale( $params ) {
191 wfDeprecated( __METHOD__ );
192 if ( !isset( $params['urlparam'] ) ) {
193 // In case there are subclasses that
194 // don't have this param set to anything.
195 $params['urlparam'] = null;
196 }
197 return $this->makeThumbParams( $params );
198 }
199
200 /* Take parameters for transforming thumbnail, validate and turn into array.
201 * @param $params Array: Parameters from the request.
202 * @return Array or null: If array, suitable to passing to $file->transform.
203 */
204 public function makeThumbParams( $params ) {
205 $p = $this->getModulePrefix();
206
207 // Height and width.
208 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
209 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
210 }
211
212 if ( $params['urlwidth'] != -1 ) {
213 $scale = array();
214 $scale['width'] = $params['urlwidth'];
215 $scale['height'] = $params['urlheight'];
216 } else {
217 $scale = null;
218 if ( $params['urlparam'] ) {
219 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
220 }
221 return $scale;
222 }
223
224 // Other parameters.
225 if ( is_array( $params['urlparam'] ) ) {
226 foreach( $params['urlparam'] as $item ) {
227 $parameter = explode( '=', $item, 2 );
228
229 if ( count( $parameter ) !== 2
230 || $parameter[0] === 'width'
231 || $parameter[0] === 'height'
232 ) {
233 $this->dieUsage( "Invalid value for {$p}urlparam ($item)", "urlparam" );
234 }
235 $scale[$parameter[0]] = $parameter[1];
236 }
237 }
238 return $scale;
239 }
240
241 /** Validate the thumb parameters, give error if invalid.
242 *
243 * We do this later than makeThumbParams, since we need the image
244 * to know which handler, since handlers can make their own parameters.
245 * @param File $image Image that params are for.
246 * @param Array $thumbParams thumbnail parameters
247 */
248 protected function validateThumbParams ( $image, $thumbParams ) {
249 if ( !$thumbParams ) return;
250 $p = $this->getModulePrefix();
251
252 $h = $image->getHandler();
253 if ( !$h ) {
254 $this->setWarning( 'Could not create thumbnail because ' .
255 $image->getName() . ' does not have an associated image handler' );
256 return;
257 }
258 foreach ( $thumbParams as $name => $value ) {
259 if ( !$h->validateParam( $name, $value ) ) {
260 /* This doesn't work well with height=-1 placeholder */
261 if ( $name === 'height' ) continue;
262 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
263 }
264 }
265 // This could also potentially check normaliseParams as well, However that seems
266 // to fall more into a thumbnail rendering error than a user input error, and
267 // will be checked by the transform functions.
268 }
269
270 /**
271 * Get result information for an image revision
272 *
273 * @param $file File object
274 * @param $prop Array of properties to get (in the keys)
275 * @param $result ApiResult object
276 * @param $thumbParams Array containing 'width' and 'height' items, or null
277 * @return Array: result array
278 */
279 static function getInfo( $file, $prop, $result, $thumbParams = null ) {
280 $vals = array();
281 if ( isset( $prop['timestamp'] ) ) {
282 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $file->getTimestamp() );
283 }
284 if ( isset( $prop['user'] ) || isset( $prop['userid'] ) ) {
285
286 if ( isset( $prop['user'] ) ) {
287 $vals['user'] = $file->getUser();
288 }
289 if ( isset( $prop['userid'] ) ) {
290 $vals['userid'] = $file->getUser( 'id' );
291 }
292 if ( !$file->getUser( 'id' ) ) {
293 $vals['anon'] = '';
294 }
295 }
296 if ( isset( $prop['size'] ) || isset( $prop['dimensions'] ) ) {
297 $vals['size'] = intval( $file->getSize() );
298 $vals['width'] = intval( $file->getWidth() );
299 $vals['height'] = intval( $file->getHeight() );
300
301 $pageCount = $file->pageCount();
302 if ( $pageCount !== false ) {
303 $vals['pagecount'] = $pageCount;
304 }
305 }
306 if ( isset( $prop['url'] ) ) {
307 if ( !is_null( $thumbParams ) ) {
308 $mto = $file->transform( $thumbParams );
309 if ( $mto && !$mto->isError() ) {
310 $vals['thumburl'] = wfExpandUrl( $mto->getUrl() );
311
312 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
313 // thumbnail sizes for the thumbnail actual size
314 if ( $mto->getUrl() !== $file->getUrl() ) {
315 $vals['thumbwidth'] = intval( $mto->getWidth() );
316 $vals['thumbheight'] = intval( $mto->getHeight() );
317 } else {
318 $vals['thumbwidth'] = intval( $file->getWidth() );
319 $vals['thumbheight'] = intval( $file->getHeight() );
320 }
321
322 if ( isset( $prop['thumbmime'] ) ) {
323 $thumbFile = UnregisteredLocalFile::newFromPath( $mto->getPath(), false );
324 $vals['thumbmime'] = $thumbFile->getMimeType();
325 }
326 }
327 if ( $mto && $mto->isError() ) {
328 $vals['thumberror'] = $mto->toText();
329 }
330 }
331 $vals['url'] = $file->getFullURL();
332 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
333 }
334 if ( isset( $prop['comment'] ) ) {
335 $vals['comment'] = $file->getDescription();
336 }
337 if ( isset( $prop['parsedcomment'] ) ) {
338 global $wgUser;
339 $vals['parsedcomment'] = $wgUser->getSkin()->formatComment(
340 $file->getDescription(), $file->getTitle() );
341 }
342
343 if ( isset( $prop['sha1'] ) ) {
344 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
345 }
346 if ( isset( $prop['metadata'] ) ) {
347 $metadata = $file->getMetadata();
348 $vals['metadata'] = $metadata ? self::processMetaData( unserialize( $metadata ), $result ) : null;
349 }
350 if ( isset( $prop['mime'] ) ) {
351 $vals['mime'] = $file->getMimeType();
352 }
353
354 if ( isset( $prop['archivename'] ) && $file->isOld() ) {
355 $vals['archivename'] = $file->getArchiveName();
356 }
357
358 if ( isset( $prop['bitdepth'] ) ) {
359 $vals['bitdepth'] = $file->getBitDepth();
360 }
361
362 return $vals;
363 }
364
365 /*
366 *
367 * @param $metadata Array
368 * @param $result ApiResult
369 * @return Array
370 */
371 public static function processMetaData( $metadata, $result ) {
372 $retval = array();
373 if ( is_array( $metadata ) ) {
374 foreach ( $metadata as $key => $value ) {
375 $r = array( 'name' => $key );
376 if ( is_array( $value ) ) {
377 $r['value'] = self::processMetaData( $value, $result );
378 } else {
379 $r['value'] = $value;
380 }
381 $retval[] = $r;
382 }
383 }
384 $result->setIndexedTagName( $retval, 'metadata' );
385 return $retval;
386 }
387
388 public function getCacheMode( $params ) {
389 return 'public';
390 }
391
392 private function getContinueStr( $img ) {
393 return $img->getOriginalTitle()->getText() .
394 '|' . $img->getTimestamp();
395 }
396
397 public function getAllowedParams() {
398 return array(
399 'prop' => array(
400 ApiBase::PARAM_ISMULTI => true,
401 ApiBase::PARAM_DFLT => 'timestamp|user',
402 ApiBase::PARAM_TYPE => self::getPropertyNames()
403 ),
404 'limit' => array(
405 ApiBase::PARAM_TYPE => 'limit',
406 ApiBase::PARAM_DFLT => 1,
407 ApiBase::PARAM_MIN => 1,
408 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
409 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
410 ),
411 'start' => array(
412 ApiBase::PARAM_TYPE => 'timestamp'
413 ),
414 'end' => array(
415 ApiBase::PARAM_TYPE => 'timestamp'
416 ),
417 'urlwidth' => array(
418 ApiBase::PARAM_TYPE => 'integer',
419 ApiBase::PARAM_DFLT => -1
420 ),
421 'urlheight' => array(
422 ApiBase::PARAM_TYPE => 'integer',
423 ApiBase::PARAM_DFLT => -1
424 ),
425 'urlparam' => array(
426 ApiBase::PARAM_ISMULTI => true,
427 ),
428 'continue' => null,
429 );
430 }
431
432 /**
433 * Returns all possible parameters to iiprop
434 * @static
435 * @return Array
436 */
437 public static function getPropertyNames() {
438 return array(
439 'timestamp',
440 'user',
441 'userid',
442 'comment',
443 'parsedcomment',
444 'url',
445 'size',
446 'dimensions', // For backwards compatibility with Allimages
447 'sha1',
448 'mime',
449 'thumbmime',
450 'metadata',
451 'archivename',
452 'bitdepth',
453 );
454 }
455
456 /**
457 * Returns the descriptions for the properties provided by getPropertyNames()
458 *
459 * @static
460 * @return array
461 */
462 public static function getPropertyDescriptions() {
463 return array(
464 'What image information to get:',
465 ' timestamp - Adds timestamp for the uploaded version',
466 ' user - Adds the user who uploaded the image version',
467 ' userid - Add the user ID that uploaded the image version',
468 ' comment - Comment on the version',
469 ' parsedcomment - Parse the comment on the version',
470 ' url - Gives URL to the image and the description page',
471 ' size - Adds the size of the image in bytes and the height and width',
472 ' dimensions - Alias for size',
473 ' sha1 - Adds SHA-1 hash for the image',
474 ' mime - Adds MIME type of the image',
475 ' thumbmime - Adds MIME type of the image thumbnail (requires url)',
476 ' metadata - Lists EXIF metadata for the version of the image',
477 ' archivename - Adds the file name of the archive version for non-latest versions',
478 ' bitdepth - Adds the bit depth of the version',
479 );
480 }
481
482 /**
483 * Return the API documentation for the parameters.
484 * @return {Array} parameter documentation.
485 */
486 public function getParamDescription() {
487 $p = $this->getModulePrefix();
488 return array(
489 'prop' => self::getPropertyDescriptions(),
490 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
491 'Only the current version of the image can be scaled' ),
492 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
493 'urlparam' => array( "Other rending parameters, such as page=2 for multipaged documents.",
494 "Multiple parameters should be seperated with a |. {$p}urlwidth must also be used"),
495 'limit' => 'How many image revisions to return',
496 'start' => 'Timestamp to start listing from',
497 'end' => 'Timestamp to stop listing at',
498 'continue' => 'If the query response includes a continue value, use it here to get another page of results'
499 );
500 }
501
502 public function getDescription() {
503 return 'Returns image information and upload history';
504 }
505
506 public function getPossibleErrors() {
507 $p = $this->getModulePrefix();
508 return array_merge( parent::getPossibleErrors(), array(
509 array( 'code' => 'iiurlwidth', 'info' => 'iiurlheight cannot be used without iiurlwidth' ),
510 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
511 array( 'code' => 'urlparam_no_width', 'info' => "iiurlparam requires {$p}urlwidth" ),
512 ) );
513 }
514
515 protected function getExamples() {
516 return array(
517 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
518 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
519 );
520 }
521
522 public function getVersion() {
523 return __CLASS__ . ': $Id$';
524 }
525 }