(bug 26548) Make multi-paged documents (PDFs) work with ForeignAPIRepo (aka InstantCo...
[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 // Get information about the current version first
112 // Check that the current version is within the start-end boundaries
113 $gotOne = false;
114 if (
115 ( is_null( $start ) || $img->getTimestamp() <= $start ) &&
116 ( is_null( $params['end'] ) || $img->getTimestamp() >= $params['end'] )
117 )
118 {
119 $gotOne = true;
120 $this->validateThumbParams( $img, $thumbParams );
121 $fit = $this->addPageSubItem( $pageId,
122 self::getInfo( $img, $prop, $result, $thumbParams ) );
123 if ( !$fit ) {
124 if ( count( $pageIds[NS_IMAGE] ) == 1 ) {
125 // See the 'the user is screwed' comment above
126 $this->setContinueEnumParameter( 'start',
127 wfTimestamp( TS_ISO_8601, $img->getTimestamp() ) );
128 } else {
129 $this->setContinueEnumParameter( 'continue',
130 $this->getContinueStr( $img ) );
131 }
132 break;
133 }
134 }
135
136 // Now get the old revisions
137 // Get one more to facilitate query-continue functionality
138 $count = ( $gotOne ? 1 : 0 );
139 $oldies = $img->getHistory( $params['limit'] - $count + 1, $start, $params['end'] );
140 foreach ( $oldies as $oldie ) {
141 if ( ++$count > $params['limit'] ) {
142 // We've reached the extra one which shows that there are additional pages to be had. Stop here...
143 // Only set a query-continue if there was only one title
144 if ( count( $pageIds[NS_FILE] ) == 1 ) {
145 $this->setContinueEnumParameter( 'start',
146 wfTimestamp( TS_ISO_8601, $oldie->getTimestamp() ) );
147 }
148 break;
149 }
150 $fit = $this->addPageSubItem( $pageId,
151 self::getInfo( $oldie, $prop, $result ) );
152 if ( !$fit ) {
153 if ( count( $pageIds[NS_IMAGE] ) == 1 ) {
154 $this->setContinueEnumParameter( 'start',
155 wfTimestamp( TS_ISO_8601, $oldie->getTimestamp() ) );
156 } else {
157 $this->setContinueEnumParameter( 'continue',
158 $this->getContinueStr( $oldie ) );
159 }
160 break;
161 }
162 }
163 if ( !$fit ) {
164 break;
165 }
166 $skip = false;
167 }
168
169 $data = $this->getResultData();
170 foreach ( $data['query']['pages'] as $pageid => $arr ) {
171 if ( !isset( $arr['imagerepository'] ) ) {
172 $result->addValue(
173 array( 'query', 'pages', $pageid ),
174 'imagerepository', ''
175 );
176 }
177 // The above can't fail because it doesn't increase the result size
178 }
179 }
180 }
181
182 /**
183 * From parameters, construct a 'scale' array
184 * @param $params Array:
185 * @return Array or Null: key-val array of 'width' and 'height', or null
186 */
187 public function getScale( $params ) {
188 wfDeprecated( __METHOD__ );
189 if ( !isset( $params['urlparam'] ) ) {
190 // In case there are subclasses that
191 // don't have this param set to anything.
192 $params['urlparam'] = null;
193 }
194 return $this->makeThumbParams( $params );
195 }
196
197 /* Take parameters for transforming thumbnail, validate and turn into array.
198 * @param $params Array: Parameters from the request.
199 * @return Array or null: If array, suitable to passing to $file->transform.
200 */
201 public function makeThumbParams( $params ) {
202 $p = $this->getModulePrefix();
203
204 // Height and width.
205 if ( $params['urlheight'] != -1 && $params['urlwidth'] == -1 ) {
206 $this->dieUsage( "{$p}urlheight cannot be used without {$p}urlwidth", "{$p}urlwidth" );
207 }
208
209 if ( $params['urlwidth'] != -1 ) {
210 $scale = array();
211 $scale['width'] = $params['urlwidth'];
212 $scale['height'] = $params['urlheight'];
213 } else {
214 $scale = null;
215 if ( $params['urlparam'] ) {
216 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
217 }
218 return $scale;
219 }
220
221 // Other parameters.
222 if ( is_array( $params['urlparam'] ) ) {
223 foreach( $params['urlparam'] as $item ) {
224 $parameter = explode( '=', $item, 2 );
225
226 if ( count( $parameter ) !== 2
227 || $parameter[0] === 'width'
228 || $parameter[0] === 'height'
229 ) {
230 $this->dieUsage( "Invalid value for {$p}urlparam ($item)", "urlparam" );
231 }
232 $scale[$parameter[0]] = $parameter[1];
233 }
234 }
235 return $scale;
236 }
237
238 /** Validate the thumb parameters, give error if invalid.
239 *
240 * We do this later than makeThumbParams, since we need the image
241 * to know which handler, since handlers can make their own parameters.
242 * @param File $image Image that params are for.
243 * @param Array $thumbParams thumbnail parameters
244 */
245 protected function validateThumbParams ( $image, $thumbParams ) {
246 if ( !$thumbParams ) return;
247 $p = $this->getModulePrefix();
248
249 $h = $image->getHandler();
250 if ( !h ) {
251 // No handler, so no value for iiurlparam is valid.
252 $this->dieUsage( "Invalid value for {$p}urlparam", "urlparam" );
253 }
254 foreach ( $thumbParams as $name => $value ) {
255 if ( !$h->validateParam( $name, $value ) ) {
256 /* This doesn't work well with height=-1 placeholder */
257 if ( $name === 'height' ) continue;
258 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
259 }
260 }
261 // This could also potentially check normaliseParams as well, However that seems
262 // to fall more into a thumbnail rendering error than a user input error, and
263 // will be checked by the transform functions.
264 }
265
266 /**
267 * Get result information for an image revision
268 *
269 * @param $file File object
270 * @param $prop Array of properties to get (in the keys)
271 * @param $result ApiResult object
272 * @param $thumbParams Array containing 'width' and 'height' items, or null
273 * @return Array: result array
274 */
275 static function getInfo( $file, $prop, $result, $thumbParams = null ) {
276 $vals = array();
277 if ( isset( $prop['timestamp'] ) ) {
278 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $file->getTimestamp() );
279 }
280 if ( isset( $prop['user'] ) || isset( $prop['userid'] ) ) {
281
282 if ( isset( $prop['user'] ) ) {
283 $vals['user'] = $file->getUser();
284 }
285 if ( isset( $prop['userid'] ) ) {
286 $vals['userid'] = $file->getUser( 'id' );
287 }
288 if ( !$file->getUser( 'id' ) ) {
289 $vals['anon'] = '';
290 }
291 }
292 if ( isset( $prop['size'] ) || isset( $prop['dimensions'] ) ) {
293 $vals['size'] = intval( $file->getSize() );
294 $vals['width'] = intval( $file->getWidth() );
295 $vals['height'] = intval( $file->getHeight() );
296
297 $pageCount = $file->pageCount();
298 if ( $pageCount !== false ) {
299 $vals['pagecount'] = $pageCount;
300 }
301 }
302 if ( isset( $prop['url'] ) ) {
303 if ( !is_null( $thumbParams ) && !$file->isOld() ) {
304 $mto = $file->transform( $thumbParams );
305 if ( $mto && !$mto->isError() ) {
306 $vals['thumburl'] = wfExpandUrl( $mto->getUrl() );
307
308 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
309 // thumbnail sizes for the thumbnail actual size
310 if ( $mto->getUrl() !== $file->getUrl() ) {
311 $vals['thumbwidth'] = intval( $mto->getWidth() );
312 $vals['thumbheight'] = intval( $mto->getHeight() );
313 } else {
314 $vals['thumbwidth'] = intval( $file->getWidth() );
315 $vals['thumbheight'] = intval( $file->getHeight() );
316 }
317
318 if ( isset( $prop['thumbmime'] ) ) {
319 $thumbFile = UnregisteredLocalFile::newFromPath( $mto->getPath(), false );
320 $vals['thumbmime'] = $thumbFile->getMimeType();
321 }
322 }
323 }
324 $vals['url'] = $file->getFullURL();
325 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl() );
326 }
327 if ( isset( $prop['comment'] ) ) {
328 $vals['comment'] = $file->getDescription();
329 }
330 if ( isset( $prop['parsedcomment'] ) ) {
331 global $wgUser;
332 $vals['parsedcomment'] = $wgUser->getSkin()->formatComment(
333 $file->getDescription(), $file->getTitle() );
334 }
335
336 if ( isset( $prop['sha1'] ) ) {
337 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
338 }
339 if ( isset( $prop['metadata'] ) ) {
340 $metadata = $file->getMetadata();
341 $vals['metadata'] = $metadata ? self::processMetaData( unserialize( $metadata ), $result ) : null;
342 }
343 if ( isset( $prop['mime'] ) ) {
344 $vals['mime'] = $file->getMimeType();
345 }
346
347 if ( isset( $prop['archivename'] ) && $file->isOld() ) {
348 $vals['archivename'] = $file->getArchiveName();
349 }
350
351 if ( isset( $prop['bitdepth'] ) ) {
352 $vals['bitdepth'] = $file->getBitDepth();
353 }
354
355 return $vals;
356 }
357
358 /*
359 *
360 * @param $metadata Array
361 * @param $result ApiResult
362 * @return Array
363 */
364 public static function processMetaData( $metadata, $result ) {
365 $retval = array();
366 if ( is_array( $metadata ) ) {
367 foreach ( $metadata as $key => $value ) {
368 $r = array( 'name' => $key );
369 if ( is_array( $value ) ) {
370 $r['value'] = self::processMetaData( $value, $result );
371 } else {
372 $r['value'] = $value;
373 }
374 $retval[] = $r;
375 }
376 }
377 $result->setIndexedTagName( $retval, 'metadata' );
378 return $retval;
379 }
380
381 public function getCacheMode( $params ) {
382 return 'public';
383 }
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_ISMULTI => true,
420 ),
421 'continue' => null,
422 );
423 }
424
425 /**
426 * Returns all possible parameters to iiprop
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 /**
449 * Return the API documentation for the parameters.
450 * @return {Array} parameter documentation.
451 */
452 public function getParamDescription() {
453 $p = $this->getModulePrefix();
454 return array(
455 'prop' => array(
456 'What image information to get:',
457 ' timestamp - Adds timestamp for the uploaded version',
458 ' user - Adds the user who uploaded the image version',
459 ' userid - Add the user ID that uploaded the image version',
460 ' comment - Comment on the version',
461 ' parsedcomment - Parse the comment on the version',
462 ' url - Gives URL to the image and the description page',
463 ' size - Adds the size of the image in bytes and the height and width',
464 ' dimensions - Alias for size',
465 ' sha1 - Adds SHA-1 hash for the image',
466 ' mime - Adds MIME type of the image',
467 ' thumbmime - Adds MIME type of the image thumbnail (requires url)',
468 ' metadata - Lists EXIF metadata for the version of the image',
469 ' archivename - Adds the file name of the archive version for non-latest versions',
470 ' bitdepth - Adds the bit depth of the version',
471 ),
472 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
473 'Only the current version of the image can be scaled' ),
474 'urlheight' => "Similar to {$p}urlwidth. Cannot be used without {$p}urlwidth",
475 'urlparam' => array( "Other rending parameters, such as page=2 for multipaged documents.",
476 "Multiple parameters should be seperated with a |. {$p}urlwidth must also be used"),
477 'limit' => 'How many image revisions to return',
478 'start' => 'Timestamp to start listing from',
479 'end' => 'Timestamp to stop listing at',
480 'continue' => 'If the query response includes a continue value, use it here to get another page of results'
481 );
482 }
483
484 public function getDescription() {
485 return 'Returns image information and upload history';
486 }
487
488 public function getPossibleErrors() {
489 $p = $this->getModulePrefix();
490 return array_merge( parent::getPossibleErrors(), array(
491 array( 'code' => 'iiurlwidth', 'info' => 'iiurlheight cannot be used without iiurlwidth' ),
492 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
493 array( 'code' => 'urlparam_no_width', 'info' => "iiurlparam requires {$p}urlwidth" ),
494 ) );
495 }
496
497 protected function getExamples() {
498 return array(
499 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
500 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
501 );
502 }
503
504 public function getVersion() {
505 return __CLASS__ . ': $Id$';
506 }
507 }