MediaWiki  master
ApiQueryImageInfo.php
Go to the documentation of this file.
1 <?php
24 
31  const TRANSFORM_LIMIT = 50;
32  private static $transformCount = 0;
33 
34  public function __construct( ApiQuery $query, $moduleName, $prefix = 'ii' ) {
35  // We allow a subclass to override the prefix, to create a related API
36  // module. Some other parts of MediaWiki construct this with a null
37  // $prefix, which used to be ignored when this only took two arguments
38  if ( is_null( $prefix ) ) {
39  $prefix = 'ii';
40  }
41  parent::__construct( $query, $moduleName, $prefix );
42  }
43 
44  public function execute() {
45  $params = $this->extractRequestParams();
46 
47  $prop = array_flip( $params['prop'] );
48 
49  $scale = $this->getScale( $params );
50 
51  $opts = [
52  'version' => $params['metadataversion'],
53  'language' => $params['extmetadatalanguage'],
54  'multilang' => $params['extmetadatamultilang'],
55  'extmetadatafilter' => $params['extmetadatafilter'],
56  'revdelUser' => $this->getUser(),
57  ];
58 
59  if ( isset( $params['badfilecontexttitle'] ) ) {
60  $badFileContextTitle = Title::newFromText( $params['badfilecontexttitle'] );
61  if ( !$badFileContextTitle ) {
62  $p = $this->getModulePrefix();
63  $this->dieWithError( [ 'apierror-bad-badfilecontexttitle', $p ], 'invalid-title' );
64  }
65  } else {
66  $badFileContextTitle = false;
67  }
68 
69  $pageIds = $this->getPageSet()->getGoodAndMissingTitlesByNamespace();
70  if ( !empty( $pageIds[NS_FILE] ) ) {
71  $titles = array_keys( $pageIds[NS_FILE] );
72  asort( $titles ); // Ensure the order is always the same
73 
74  $fromTitle = null;
75  if ( !is_null( $params['continue'] ) ) {
76  $cont = explode( '|', $params['continue'] );
77  $this->dieContinueUsageIf( count( $cont ) != 2 );
78  $fromTitle = strval( $cont[0] );
79  $fromTimestamp = $cont[1];
80  // Filter out any titles before $fromTitle
81  foreach ( $titles as $key => $title ) {
82  if ( $title < $fromTitle ) {
83  unset( $titles[$key] );
84  } else {
85  break;
86  }
87  }
88  }
89 
90  $user = $this->getUser();
91  $findTitles = array_map( function ( $title ) use ( $user ) {
92  return [
93  'title' => $title,
94  'private' => $user,
95  ];
96  }, $titles );
97 
98  if ( $params['localonly'] ) {
99  $images = RepoGroup::singleton()->getLocalRepo()->findFiles( $findTitles );
100  } else {
101  $images = RepoGroup::singleton()->findFiles( $findTitles );
102  }
103 
104  $result = $this->getResult();
105  foreach ( $titles as $title ) {
106  $info = [];
107  $pageId = $pageIds[NS_FILE][$title];
108  $start = $title === $fromTitle ? $fromTimestamp : $params['start'];
109 
110  if ( !isset( $images[$title] ) ) {
111  if ( isset( $prop['uploadwarning'] ) || isset( $prop['badfile'] ) ) {
112  // uploadwarning and badfile need info about non-existing files
113  $images[$title] = MediaWikiServices::getInstance()->getRepoGroup()
114  ->getLocalRepo()->newFile( $title );
115  // Doesn't exist, so set an empty image repository
116  $info['imagerepository'] = '';
117  } else {
118  $result->addValue(
119  [ 'query', 'pages', (int)$pageId ],
120  'imagerepository', ''
121  );
122  // The above can't fail because it doesn't increase the result size
123  continue;
124  }
125  }
126 
128  $img = $images[$title];
129 
130  if ( self::getTransformCount() >= self::TRANSFORM_LIMIT ) {
131  if ( count( $pageIds[NS_FILE] ) == 1 ) {
132  // See the 'the user is screwed' comment below
133  $this->setContinueEnumParameter( 'start',
134  $start ?? wfTimestamp( TS_ISO_8601, $img->getTimestamp() )
135  );
136  } else {
137  $this->setContinueEnumParameter( 'continue',
138  $this->getContinueStr( $img, $start ) );
139  }
140  break;
141  }
142 
143  if ( !isset( $info['imagerepository'] ) ) {
144  $info['imagerepository'] = $img->getRepoName();
145  }
146  if ( isset( $prop['badfile'] ) ) {
147  $info['badfile'] = (bool)wfIsBadImage( $title, $badFileContextTitle );
148  }
149 
150  $fit = $result->addValue( [ 'query', 'pages' ], (int)$pageId, $info );
151  if ( !$fit ) {
152  if ( count( $pageIds[NS_FILE] ) == 1 ) {
153  // The user is screwed. imageinfo can't be solely
154  // responsible for exceeding the limit in this case,
155  // so set a query-continue that just returns the same
156  // thing again. When the violating queries have been
157  // out-continued, the result will get through
158  $this->setContinueEnumParameter( 'start',
159  $start ?? wfTimestamp( TS_ISO_8601, $img->getTimestamp() )
160  );
161  } else {
162  $this->setContinueEnumParameter( 'continue',
163  $this->getContinueStr( $img, $start ) );
164  }
165  break;
166  }
167 
168  // Check if we can make the requested thumbnail, and get transform parameters.
169  $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
170 
171  // Get information about the current version first
172  // Check that the current version is within the start-end boundaries
173  $gotOne = false;
174  if (
175  ( is_null( $start ) || $img->getTimestamp() <= $start ) &&
176  ( is_null( $params['end'] ) || $img->getTimestamp() >= $params['end'] )
177  ) {
178  $gotOne = true;
179 
180  $fit = $this->addPageSubItem( $pageId,
181  static::getInfo( $img, $prop, $result,
182  $finalThumbParams, $opts
183  )
184  );
185  if ( !$fit ) {
186  if ( count( $pageIds[NS_FILE] ) == 1 ) {
187  // See the 'the user is screwed' comment above
188  $this->setContinueEnumParameter( 'start',
189  wfTimestamp( TS_ISO_8601, $img->getTimestamp() ) );
190  } else {
191  $this->setContinueEnumParameter( 'continue',
192  $this->getContinueStr( $img ) );
193  }
194  break;
195  }
196  }
197 
198  // Now get the old revisions
199  // Get one more to facilitate query-continue functionality
200  $count = ( $gotOne ? 1 : 0 );
201  $oldies = $img->getHistory( $params['limit'] - $count + 1, $start, $params['end'] );
203  foreach ( $oldies as $oldie ) {
204  if ( ++$count > $params['limit'] ) {
205  // We've reached the extra one which shows that there are
206  // additional pages to be had. Stop here...
207  // Only set a query-continue if there was only one title
208  if ( count( $pageIds[NS_FILE] ) == 1 ) {
209  $this->setContinueEnumParameter( 'start',
210  wfTimestamp( TS_ISO_8601, $oldie->getTimestamp() ) );
211  }
212  break;
213  }
214  $fit = self::getTransformCount() < self::TRANSFORM_LIMIT &&
215  $this->addPageSubItem( $pageId,
216  static::getInfo( $oldie, $prop, $result,
217  $finalThumbParams, $opts
218  )
219  );
220  if ( !$fit ) {
221  if ( count( $pageIds[NS_FILE] ) == 1 ) {
222  $this->setContinueEnumParameter( 'start',
223  wfTimestamp( TS_ISO_8601, $oldie->getTimestamp() ) );
224  } else {
225  $this->setContinueEnumParameter( 'continue',
226  $this->getContinueStr( $oldie ) );
227  }
228  break;
229  }
230  }
231  if ( !$fit ) {
232  break;
233  }
234  }
235  }
236  }
237 
243  public function getScale( $params ) {
244  if ( $params['urlwidth'] != -1 ) {
245  $scale = [];
246  $scale['width'] = $params['urlwidth'];
247  $scale['height'] = $params['urlheight'];
248  } elseif ( $params['urlheight'] != -1 ) {
249  // Height is specified but width isn't
250  // Don't set $scale['width']; this signals mergeThumbParams() to fill it with the image's width
251  $scale = [];
252  $scale['height'] = $params['urlheight'];
253  } elseif ( $params['urlparam'] ) {
254  // Audio files might not have a width/height.
255  $scale = [];
256  } else {
257  $scale = null;
258  }
259 
260  return $scale;
261  }
262 
272  protected function mergeThumbParams( $image, $thumbParams, $otherParams ) {
273  if ( $thumbParams === null ) {
274  // No scaling requested
275  return null;
276  }
277  if ( !isset( $thumbParams['width'] ) && isset( $thumbParams['height'] ) ) {
278  // We want to limit only by height in this situation, so pass the
279  // image's full width as the limiting width. But some file types
280  // don't have a width of their own, so pick something arbitrary so
281  // thumbnailing the default icon works.
282  if ( $image->getWidth() <= 0 ) {
283  $thumbParams['width'] = max( $this->getConfig()->get( 'ThumbLimits' ) );
284  } else {
285  $thumbParams['width'] = $image->getWidth();
286  }
287  }
288 
289  if ( !$otherParams ) {
290  $this->checkParameterNormalise( $image, $thumbParams );
291  return $thumbParams;
292  }
293  $p = $this->getModulePrefix();
294 
295  $h = $image->getHandler();
296  if ( !$h ) {
297  $this->addWarning( [ 'apiwarn-nothumb-noimagehandler', wfEscapeWikiText( $image->getName() ) ] );
298 
299  return $thumbParams;
300  }
301 
302  $paramList = $h->parseParamString( $otherParams );
303  if ( !$paramList ) {
304  // Just set a warning (instead of dieWithError), as in many cases
305  // we could still render the image using width and height parameters,
306  // and this type of thing could happen between different versions of
307  // handlers.
308  $this->addWarning( [ 'apiwarn-badurlparam', $p, wfEscapeWikiText( $image->getName() ) ] );
309  $this->checkParameterNormalise( $image, $thumbParams );
310  return $thumbParams;
311  }
312 
313  if ( isset( $paramList['width'] ) && isset( $thumbParams['width'] ) ) {
314  if ( (int)$paramList['width'] != (int)$thumbParams['width'] ) {
315  $this->addWarning(
316  [ 'apiwarn-urlparamwidth', $p, $paramList['width'], $thumbParams['width'] ]
317  );
318  }
319  }
320 
321  foreach ( $paramList as $name => $value ) {
322  if ( !$h->validateParam( $name, $value ) ) {
323  $this->dieWithError(
324  [ 'apierror-invalidurlparam', $p, wfEscapeWikiText( $name ), wfEscapeWikiText( $value ) ]
325  );
326  }
327  }
328 
329  $finalParams = $thumbParams + $paramList;
330  $this->checkParameterNormalise( $image, $finalParams );
331  return $finalParams;
332  }
333 
345  protected function checkParameterNormalise( $image, $finalParams ) {
346  $h = $image->getHandler();
347  if ( !$h ) {
348  return;
349  }
350  // Note: normaliseParams modifies the array in place, but we aren't interested
351  // in the actual normalised version, only if we can actually normalise them,
352  // so we use the functions scope to throw away the normalisations.
353  if ( !$h->normaliseParams( $image, $finalParams ) ) {
354  $this->dieWithError( [ 'apierror-urlparamnormal', wfEscapeWikiText( $image->getName() ) ] );
355  }
356  }
357 
373  public static function getInfo( $file, $prop, $result, $thumbParams = null, $opts = false ) {
374  $anyHidden = false;
375 
376  if ( !$opts || is_string( $opts ) ) {
377  $opts = [
378  'version' => $opts ?: 'latest',
379  'language' => MediaWikiServices::getInstance()->getContentLanguage(),
380  'multilang' => false,
381  'extmetadatafilter' => [],
382  'revdelUser' => null,
383  ];
384  }
385  $version = $opts['version'];
386  $vals = [
387  ApiResult::META_TYPE => 'assoc',
388  ];
389  // Timestamp is shown even if the file is revdelete'd in interface
390  // so do same here.
391  if ( isset( $prop['timestamp'] ) ) {
392  $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $file->getTimestamp() );
393  }
394 
395  // Handle external callers who don't pass revdelUser
396  if ( isset( $opts['revdelUser'] ) && $opts['revdelUser'] ) {
397  $revdelUser = $opts['revdelUser'];
398  $canShowField = function ( $field ) use ( $file, $revdelUser ) {
399  return $file->userCan( $field, $revdelUser );
400  };
401  } else {
402  $canShowField = function ( $field ) use ( $file ) {
403  return !$file->isDeleted( $field );
404  };
405  }
406 
407  $user = isset( $prop['user'] );
408  $userid = isset( $prop['userid'] );
409 
410  if ( $user || $userid ) {
411  if ( $file->isDeleted( File::DELETED_USER ) ) {
412  $vals['userhidden'] = true;
413  $anyHidden = true;
414  }
415  if ( $canShowField( File::DELETED_USER ) ) {
416  if ( $user ) {
417  $vals['user'] = $file->getUser();
418  }
419  if ( $userid ) {
420  $vals['userid'] = $file->getUser( 'id' );
421  }
422  if ( !$file->getUser( 'id' ) ) {
423  $vals['anon'] = true;
424  }
425  }
426  }
427 
428  // This is shown even if the file is revdelete'd in interface
429  // so do same here.
430  if ( isset( $prop['size'] ) || isset( $prop['dimensions'] ) ) {
431  $vals['size'] = (int)$file->getSize();
432  $vals['width'] = (int)$file->getWidth();
433  $vals['height'] = (int)$file->getHeight();
434 
435  $pageCount = $file->pageCount();
436  if ( $pageCount !== false ) {
437  $vals['pagecount'] = $pageCount;
438  }
439 
440  // length as in how many seconds long a video is.
441  $length = $file->getLength();
442  if ( $length ) {
443  // Call it duration, because "length" can be ambiguous.
444  $vals['duration'] = (float)$length;
445  }
446  }
447 
448  $pcomment = isset( $prop['parsedcomment'] );
449  $comment = isset( $prop['comment'] );
450 
451  if ( $pcomment || $comment ) {
452  if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
453  $vals['commenthidden'] = true;
454  $anyHidden = true;
455  }
456  if ( $canShowField( File::DELETED_COMMENT ) ) {
457  if ( $pcomment ) {
458  $vals['parsedcomment'] = Linker::formatComment(
459  $file->getDescription( File::RAW ), $file->getTitle() );
460  }
461  if ( $comment ) {
462  $vals['comment'] = $file->getDescription( File::RAW );
463  }
464  }
465  }
466 
467  $canonicaltitle = isset( $prop['canonicaltitle'] );
468  $url = isset( $prop['url'] );
469  $sha1 = isset( $prop['sha1'] );
470  $meta = isset( $prop['metadata'] );
471  $extmetadata = isset( $prop['extmetadata'] );
472  $commonmeta = isset( $prop['commonmetadata'] );
473  $mime = isset( $prop['mime'] );
474  $mediatype = isset( $prop['mediatype'] );
475  $archive = isset( $prop['archivename'] );
476  $bitdepth = isset( $prop['bitdepth'] );
477  $uploadwarning = isset( $prop['uploadwarning'] );
478 
479  if ( $uploadwarning ) {
481  }
482 
483  if ( $file->isDeleted( File::DELETED_FILE ) ) {
484  $vals['filehidden'] = true;
485  $anyHidden = true;
486  }
487 
488  if ( $anyHidden && $file->isDeleted( File::DELETED_RESTRICTED ) ) {
489  $vals['suppressed'] = true;
490  }
491 
492  if ( !$canShowField( File::DELETED_FILE ) ) {
493  // Early return, tidier than indenting all following things one level
494  return $vals;
495  }
496 
497  if ( $canonicaltitle ) {
498  $vals['canonicaltitle'] = $file->getTitle()->getPrefixedText();
499  }
500 
501  if ( $url ) {
502  if ( $file->exists() ) {
503  if ( !is_null( $thumbParams ) ) {
504  $mto = $file->transform( $thumbParams );
505  self::$transformCount++;
506  if ( $mto && !$mto->isError() ) {
507  $vals['thumburl'] = wfExpandUrl( $mto->getUrl(), PROTO_CURRENT );
508 
509  // T25834 - If the URLs are the same, we haven't resized it, so shouldn't give the wanted
510  // thumbnail sizes for the thumbnail actual size
511  if ( $mto->getUrl() !== $file->getUrl() ) {
512  $vals['thumbwidth'] = (int)$mto->getWidth();
513  $vals['thumbheight'] = (int)$mto->getHeight();
514  } else {
515  $vals['thumbwidth'] = (int)$file->getWidth();
516  $vals['thumbheight'] = (int)$file->getHeight();
517  }
518 
519  if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
520  list( , $mime ) = $file->getHandler()->getThumbType(
521  $mto->getExtension(), $file->getMimeType(), $thumbParams );
522  $vals['thumbmime'] = $mime;
523  }
524  } elseif ( $mto && $mto->isError() ) {
525  $vals['thumberror'] = $mto->toText();
526  }
527  }
528  $vals['url'] = wfExpandUrl( $file->getFullUrl(), PROTO_CURRENT );
529  } else {
530  $vals['filemissing'] = true;
531  }
532  $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl(), PROTO_CURRENT );
533 
534  $shortDescriptionUrl = $file->getDescriptionShortUrl();
535  if ( $shortDescriptionUrl !== null ) {
536  $vals['descriptionshorturl'] = wfExpandUrl( $shortDescriptionUrl, PROTO_CURRENT );
537  }
538  }
539 
540  if ( $sha1 ) {
541  $vals['sha1'] = Wikimedia\base_convert( $file->getSha1(), 36, 16, 40 );
542  }
543 
544  if ( $meta ) {
545  Wikimedia\suppressWarnings();
546  $metadata = unserialize( $file->getMetadata() );
547  Wikimedia\restoreWarnings();
548  if ( $metadata && $version !== 'latest' ) {
549  $metadata = $file->convertMetadataVersion( $metadata, $version );
550  }
551  $vals['metadata'] = $metadata ? static::processMetaData( $metadata, $result ) : null;
552  }
553  if ( $commonmeta ) {
554  $metaArray = $file->getCommonMetaArray();
555  $vals['commonmetadata'] = $metaArray ? static::processMetaData( $metaArray, $result ) : [];
556  }
557 
558  if ( $extmetadata ) {
559  // Note, this should return an array where all the keys
560  // start with a letter, and all the values are strings.
561  // Thus there should be no issue with format=xml.
562  $format = new FormatMetadata;
563  $format->setSingleLanguage( !$opts['multilang'] );
564  $format->getContext()->setLanguage( $opts['language'] );
565  $extmetaArray = $format->fetchExtendedMetadata( $file );
566  if ( $opts['extmetadatafilter'] ) {
567  $extmetaArray = array_intersect_key(
568  $extmetaArray, array_flip( $opts['extmetadatafilter'] )
569  );
570  }
571  $vals['extmetadata'] = $extmetaArray;
572  }
573 
574  if ( $mime ) {
575  $vals['mime'] = $file->getMimeType();
576  }
577 
578  if ( $mediatype ) {
579  $vals['mediatype'] = $file->getMediaType();
580  }
581 
582  if ( $archive && $file->isOld() ) {
583  $vals['archivename'] = $file->getArchiveName();
584  }
585 
586  if ( $bitdepth ) {
587  $vals['bitdepth'] = $file->getBitDepth();
588  }
589 
590  return $vals;
591  }
592 
600  static function getTransformCount() {
601  return self::$transformCount;
602  }
603 
610  public static function processMetaData( $metadata, $result ) {
611  $retval = [];
612  if ( is_array( $metadata ) ) {
613  foreach ( $metadata as $key => $value ) {
614  $r = [
615  'name' => $key,
616  ApiResult::META_BC_BOOLS => [ 'value' ],
617  ];
618  if ( is_array( $value ) ) {
619  $r['value'] = static::processMetaData( $value, $result );
620  } else {
621  $r['value'] = $value;
622  }
623  $retval[] = $r;
624  }
625  }
626  ApiResult::setIndexedTagName( $retval, 'metadata' );
627 
628  return $retval;
629  }
630 
631  public function getCacheMode( $params ) {
632  if ( $this->userCanSeeRevDel() ) {
633  return 'private';
634  }
635 
636  return 'public';
637  }
638 
644  protected function getContinueStr( $img, $start = null ) {
645  if ( $start === null ) {
646  $start = $img->getTimestamp();
647  }
648 
649  return $img->getOriginalTitle()->getDBkey() . '|' . $start;
650  }
651 
652  public function getAllowedParams() {
653  return [
654  'prop' => [
655  ApiBase::PARAM_ISMULTI => true,
656  ApiBase::PARAM_DFLT => 'timestamp|user',
657  ApiBase::PARAM_TYPE => static::getPropertyNames(),
658  ApiBase::PARAM_HELP_MSG_PER_VALUE => static::getPropertyMessages(),
659  ],
660  'limit' => [
661  ApiBase::PARAM_TYPE => 'limit',
662  ApiBase::PARAM_DFLT => 1,
663  ApiBase::PARAM_MIN => 1,
666  ],
667  'start' => [
668  ApiBase::PARAM_TYPE => 'timestamp'
669  ],
670  'end' => [
671  ApiBase::PARAM_TYPE => 'timestamp'
672  ],
673  'urlwidth' => [
674  ApiBase::PARAM_TYPE => 'integer',
675  ApiBase::PARAM_DFLT => -1,
677  'apihelp-query+imageinfo-param-urlwidth',
678  self::TRANSFORM_LIMIT,
679  ],
680  ],
681  'urlheight' => [
682  ApiBase::PARAM_TYPE => 'integer',
683  ApiBase::PARAM_DFLT => -1
684  ],
685  'metadataversion' => [
686  ApiBase::PARAM_TYPE => 'string',
687  ApiBase::PARAM_DFLT => '1',
688  ],
689  'extmetadatalanguage' => [
690  ApiBase::PARAM_TYPE => 'string',
692  MediaWikiServices::getInstance()->getContentLanguage()->getCode(),
693  ],
694  'extmetadatamultilang' => [
695  ApiBase::PARAM_TYPE => 'boolean',
696  ApiBase::PARAM_DFLT => false,
697  ],
698  'extmetadatafilter' => [
699  ApiBase::PARAM_TYPE => 'string',
700  ApiBase::PARAM_ISMULTI => true,
701  ],
702  'urlparam' => [
703  ApiBase::PARAM_DFLT => '',
704  ApiBase::PARAM_TYPE => 'string',
705  ],
706  'badfilecontexttitle' => [
707  ApiBase::PARAM_TYPE => 'string',
708  ],
709  'continue' => [
710  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
711  ],
712  'localonly' => false,
713  ];
714  }
715 
722  public static function getPropertyNames( $filter = [] ) {
723  return array_keys( static::getPropertyMessages( $filter ) );
724  }
725 
732  public static function getPropertyMessages( $filter = [] ) {
733  return array_diff_key(
734  [
735  'timestamp' => 'apihelp-query+imageinfo-paramvalue-prop-timestamp',
736  'user' => 'apihelp-query+imageinfo-paramvalue-prop-user',
737  'userid' => 'apihelp-query+imageinfo-paramvalue-prop-userid',
738  'comment' => 'apihelp-query+imageinfo-paramvalue-prop-comment',
739  'parsedcomment' => 'apihelp-query+imageinfo-paramvalue-prop-parsedcomment',
740  'canonicaltitle' => 'apihelp-query+imageinfo-paramvalue-prop-canonicaltitle',
741  'url' => 'apihelp-query+imageinfo-paramvalue-prop-url',
742  'size' => 'apihelp-query+imageinfo-paramvalue-prop-size',
743  'dimensions' => 'apihelp-query+imageinfo-paramvalue-prop-dimensions',
744  'sha1' => 'apihelp-query+imageinfo-paramvalue-prop-sha1',
745  'mime' => 'apihelp-query+imageinfo-paramvalue-prop-mime',
746  'thumbmime' => 'apihelp-query+imageinfo-paramvalue-prop-thumbmime',
747  'mediatype' => 'apihelp-query+imageinfo-paramvalue-prop-mediatype',
748  'metadata' => 'apihelp-query+imageinfo-paramvalue-prop-metadata',
749  'commonmetadata' => 'apihelp-query+imageinfo-paramvalue-prop-commonmetadata',
750  'extmetadata' => 'apihelp-query+imageinfo-paramvalue-prop-extmetadata',
751  'archivename' => 'apihelp-query+imageinfo-paramvalue-prop-archivename',
752  'bitdepth' => 'apihelp-query+imageinfo-paramvalue-prop-bitdepth',
753  'uploadwarning' => 'apihelp-query+imageinfo-paramvalue-prop-uploadwarning',
754  'badfile' => 'apihelp-query+imageinfo-paramvalue-prop-badfile',
755  ],
756  array_flip( $filter )
757  );
758  }
759 
767  private static function getProperties( $modulePrefix = '' ) {
768  return [
769  'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
770  'user' => ' user - Adds the user who uploaded the image version',
771  'userid' => ' userid - Add the user ID that uploaded the image version',
772  'comment' => ' comment - Comment on the version',
773  'parsedcomment' => ' parsedcomment - Parse the comment on the version',
774  'canonicaltitle' => ' canonicaltitle - Adds the canonical title of the image file',
775  'url' => ' url - Gives URL to the image and the description page',
776  'size' => ' size - Adds the size of the image in bytes, ' .
777  'its height and its width. Page count and duration are added if applicable',
778  'dimensions' => ' dimensions - Alias for size', // B/C with Allimages
779  'sha1' => ' sha1 - Adds SHA-1 hash for the image',
780  'mime' => ' mime - Adds MIME type of the image',
781  'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail' .
782  ' (requires url and param ' . $modulePrefix . 'urlwidth)',
783  'mediatype' => ' mediatype - Adds the media type of the image',
784  'metadata' => ' metadata - Lists Exif metadata for the version of the image',
785  'commonmetadata' => ' commonmetadata - Lists file format generic metadata ' .
786  'for the version of the image',
787  'extmetadata' => ' extmetadata - Lists formatted metadata combined ' .
788  'from multiple sources. Results are HTML formatted.',
789  'archivename' => ' archivename - Adds the file name of the archive ' .
790  'version for non-latest versions',
791  'bitdepth' => ' bitdepth - Adds the bit depth of the version',
792  'uploadwarning' => ' uploadwarning - Used by the Special:Upload page to ' .
793  'get information about an existing file. Not intended for use outside MediaWiki core',
794  ];
795  }
796 
805  public static function getPropertyDescriptions( $filter = [], $modulePrefix = '' ) {
806  return array_merge(
807  [ 'What image information to get:' ],
808  array_values( array_diff_key( static::getProperties( $modulePrefix ), array_flip( $filter ) ) )
809  );
810  }
811 
812  protected function getExamplesMessages() {
813  return [
814  'action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo'
815  => 'apihelp-query+imageinfo-example-simple',
816  'action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&' .
817  'iiend=2007-12-31T23:59:59Z&iiprop=timestamp|user|url'
818  => 'apihelp-query+imageinfo-example-dated',
819  ];
820  }
821 
822  public function getHelpUrls() {
823  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Imageinfo';
824  }
825 }
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:261
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
const DELETED_COMMENT
Definition: File.php:64
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1585
getResult()
Get the result object.
Definition: ApiBase.php:639
static getPropertyNames( $filter=[])
Returns all possible parameters to iiprop.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
Format Image metadata values into a human readable form.
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
wfIsBadImage( $name, $contextTitle=false, $blacklist=null)
Determine if an image exists on the &#39;bad image list&#39;.
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:259
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
mergeThumbParams( $image, $thumbParams, $otherParams)
Validate and merge scale parameters with handler thumb parameters, give error if invalid.
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:97
This is a base class for all Query modules.
$value
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:2008
const PROTO_CURRENT
Definition: Defines.php:218
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:760
const META_TYPE
Key for the &#39;type&#39; metadata item.
Definition: ApiResult.php:110
getPageSet()
Get the PageSet object to work on.
static getExistsWarning( $file)
Helper function that does various existence checks for a file.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
__construct(ApiQuery $query, $moduleName, $prefix='ii')
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition: ApiBase.php:164
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:616
const DELETED_FILE
Definition: File.php:63
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
checkParameterNormalise( $image, $finalParams)
Verify that the final image parameters can be normalised.
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition: Linker.php:1160
static getProperties( $modulePrefix='')
Returns array key value pairs of properties and their descriptions.
static getInfo( $file, $prop, $result, $thumbParams=null, $opts=false)
Get result information for an image revision.
userCanSeeRevDel()
Check whether the current user has permission to view revision-deleted fields.
static processMetaData( $metadata, $result)
static singleton()
Definition: RepoGroup.php:60
dieContinueUsageIf( $condition)
Die with the &#39;badcontinue&#39; error.
Definition: ApiBase.php:2199
static getTransformCount()
Get the count of image transformations performed.
static getPropertyDescriptions( $filter=[], $modulePrefix='')
Returns the descriptions for the properties provided by getPropertyNames()
$params
unserialize( $serialized)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
$filter
A query action to get image information and upload history.
const NS_FILE
Definition: Defines.php:66
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right, for PARAM_TYPE &#39;limit&#39;.
Definition: ApiBase.php:103
This is the main query class.
Definition: ApiQuery.php:36
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
setSingleLanguage( $val)
Trigger only outputting single language for multilanguage fields.
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:131
const DELETED_USER
Definition: File.php:65
const DELETED_RESTRICTED
Definition: File.php:66
static getExistsWarning( $exists)
Formats a result of UploadBase::getExistsWarning as HTML This check is static and can be done pre-upl...
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
getScale( $params)
From parameters, construct a &#39;scale&#39; array.
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
Definition: linkcache.txt:17
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:527
const RAW
Definition: File.php:81
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition: hooks.txt:780
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1927
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
const META_BC_BOOLS
Key for the &#39;BC bools&#39; metadata item.
Definition: ApiResult.php:136
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
static getPropertyMessages( $filter=[])
Returns messages for all possible parameters to iiprop.
getContinueStr( $img, $start=null)
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:106
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:319
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.