MediaWiki  master
ApiQueryAllImages.php
Go to the documentation of this file.
1 <?php
2 
31 
38 
42  protected $mRepo;
43 
46 
53  public function __construct(
54  ApiQuery $query,
55  $moduleName,
56  RepoGroup $repoGroup,
58  ) {
59  parent::__construct( $query, $moduleName, 'ai' );
60  $this->mRepo = $repoGroup->getLocalRepo();
61  $this->groupPermissionsLookup = $groupPermissionsLookup;
62  }
63 
71  protected function getDB() {
72  return $this->mRepo->getReplicaDB();
73  }
74 
75  public function execute() {
76  $this->run();
77  }
78 
79  public function getCacheMode( $params ) {
80  return 'public';
81  }
82 
87  public function executeGenerator( $resultPageSet ) {
88  if ( $resultPageSet->isResolvingRedirects() ) {
89  $this->dieWithError( 'apierror-allimages-redirect', 'invalidparammix' );
90  }
91 
92  $this->run( $resultPageSet );
93  }
94 
99  private function run( $resultPageSet = null ) {
100  $repo = $this->mRepo;
101  if ( !$repo instanceof LocalRepo ) {
102  $this->dieWithError( 'apierror-unsupportedrepo' );
103  }
104 
105  $prefix = $this->getModulePrefix();
106 
107  $db = $this->getDB();
108 
109  $params = $this->extractRequestParams();
110 
111  // Table and return fields
112  $prop = array_fill_keys( $params['prop'], true );
113 
114  $fileQuery = LocalFile::getQueryInfo();
115  $this->addTables( $fileQuery['tables'] );
116  $this->addFields( $fileQuery['fields'] );
117  $this->addJoinConds( $fileQuery['joins'] );
118 
119  $ascendingOrder = true;
120  if ( $params['dir'] == 'descending' || $params['dir'] == 'older' ) {
121  $ascendingOrder = false;
122  }
123 
124  if ( $params['sort'] == 'name' ) {
125  // Check mutually exclusive params
126  $disallowed = [ 'start', 'end', 'user' ];
127  foreach ( $disallowed as $pname ) {
128  if ( isset( $params[$pname] ) ) {
129  $this->dieWithError(
130  [
131  'apierror-invalidparammix-mustusewith',
132  "{$prefix}{$pname}",
133  "{$prefix}sort=timestamp"
134  ],
135  'invalidparammix'
136  );
137  }
138  }
139  if ( $params['filterbots'] != 'all' ) {
140  $this->dieWithError(
141  [
142  'apierror-invalidparammix-mustusewith',
143  "{$prefix}filterbots",
144  "{$prefix}sort=timestamp"
145  ],
146  'invalidparammix'
147  );
148  }
149 
150  // Pagination
151  if ( $params['continue'] !== null ) {
152  $cont = explode( '|', $params['continue'] );
153  $this->dieContinueUsageIf( count( $cont ) != 1 );
154  $op = $ascendingOrder ? '>' : '<';
155  $continueFrom = $db->addQuotes( $cont[0] );
156  $this->addWhere( "img_name $op= $continueFrom" );
157  }
158 
159  // Image filters
160  $from = $params['from'] === null ? null : $this->titlePartToKey( $params['from'], NS_FILE );
161  $to = $params['to'] === null ? null : $this->titlePartToKey( $params['to'], NS_FILE );
162  $this->addWhereRange( 'img_name', $ascendingOrder ? 'newer' : 'older', $from, $to );
163 
164  if ( isset( $params['prefix'] ) ) {
165  $this->addWhere( 'img_name' . $db->buildLike(
166  $this->titlePartToKey( $params['prefix'], NS_FILE ),
167  $db->anyString() ) );
168  }
169  } else {
170  // Check mutually exclusive params
171  $disallowed = [ 'from', 'to', 'prefix' ];
172  foreach ( $disallowed as $pname ) {
173  if ( isset( $params[$pname] ) ) {
174  $this->dieWithError(
175  [
176  'apierror-invalidparammix-mustusewith',
177  "{$prefix}{$pname}",
178  "{$prefix}sort=name"
179  ],
180  'invalidparammix'
181  );
182  }
183  }
184  if ( $params['user'] !== null && $params['filterbots'] != 'all' ) {
185  // Since filterbots checks if each user has the bot right, it
186  // doesn't make sense to use it with user
187  $this->dieWithError(
188  [ 'apierror-invalidparammix-cannotusewith', "{$prefix}user", "{$prefix}filterbots" ]
189  );
190  }
191 
192  // Pagination
193  $this->addTimestampWhereRange(
194  'img_timestamp',
195  $ascendingOrder ? 'newer' : 'older',
196  $params['start'],
197  $params['end']
198  );
199  // Include in ORDER BY for uniqueness
200  $this->addWhereRange( 'img_name', $ascendingOrder ? 'newer' : 'older', null, null );
201 
202  if ( $params['continue'] !== null ) {
203  $cont = explode( '|', $params['continue'] );
204  $this->dieContinueUsageIf( count( $cont ) != 2 );
205  $op = ( $ascendingOrder ? '>' : '<' );
206  $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
207  $continueName = $db->addQuotes( $cont[1] );
208  $this->addWhere( "img_timestamp $op $continueTimestamp OR " .
209  "(img_timestamp = $continueTimestamp AND " .
210  "img_name $op= $continueName)"
211  );
212  }
213 
214  // Image filters
215  if ( $params['user'] !== null ) {
216  $this->addWhereFld( $fileQuery['fields']['img_user_text'], $params['user'] );
217  }
218  if ( $params['filterbots'] != 'all' ) {
219  $this->addTables( 'user_groups' );
220  $this->addJoinConds( [ 'user_groups' => [
221  'LEFT JOIN',
222  [
223  'ug_group' => $this->groupPermissionsLookup->getGroupsWithPermission( 'bot' ),
224  'ug_user = actor_user',
225  'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
226  ]
227  ] ] );
228  $groupCond = $params['filterbots'] == 'nobots' ? 'NULL' : 'NOT NULL';
229  $this->addWhere( "ug_group IS $groupCond" );
230  }
231  }
232 
233  // Filters not depending on sort
234  if ( isset( $params['minsize'] ) ) {
235  $this->addWhere( 'img_size>=' . (int)$params['minsize'] );
236  }
237 
238  if ( isset( $params['maxsize'] ) ) {
239  $this->addWhere( 'img_size<=' . (int)$params['maxsize'] );
240  }
241 
242  $sha1 = false;
243  if ( isset( $params['sha1'] ) ) {
244  $sha1 = strtolower( $params['sha1'] );
245  if ( !$this->validateSha1Hash( $sha1 ) ) {
246  $this->dieWithError( 'apierror-invalidsha1hash' );
247  }
248  $sha1 = Wikimedia\base_convert( $sha1, 16, 36, 31 );
249  } elseif ( isset( $params['sha1base36'] ) ) {
250  $sha1 = strtolower( $params['sha1base36'] );
251  if ( !$this->validateSha1Base36Hash( $sha1 ) ) {
252  $this->dieWithError( 'apierror-invalidsha1base36hash' );
253  }
254  }
255  if ( $sha1 ) {
256  $this->addWhereFld( 'img_sha1', $sha1 );
257  }
258 
259  if ( $params['mime'] !== null ) {
260  if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
261  $this->dieWithError( 'apierror-mimesearchdisabled' );
262  }
263 
264  $mimeConds = [];
265  foreach ( $params['mime'] as $mime ) {
266  list( $major, $minor ) = File::splitMime( $mime );
267  $mimeConds[] = $db->makeList(
268  [
269  'img_major_mime' => $major,
270  'img_minor_mime' => $minor,
271  ],
272  LIST_AND
273  );
274  }
275  // safeguard against internal_api_error_DBQueryError
276  if ( count( $mimeConds ) > 0 ) {
277  $this->addWhere( $db->makeList( $mimeConds, LIST_OR ) );
278  } else {
279  // no MIME types, no files
280  $this->getResult()->addValue( 'query', $this->getModuleName(), [] );
281  return;
282  }
283  }
284 
285  $limit = $params['limit'];
286  $this->addOption( 'LIMIT', $limit + 1 );
287  $sortFlag = '';
288  if ( !$ascendingOrder ) {
289  $sortFlag = ' DESC';
290  }
291  if ( $params['sort'] == 'timestamp' ) {
292  $this->addOption( 'ORDER BY', 'img_timestamp' . $sortFlag );
293  } else {
294  $this->addOption( 'ORDER BY', 'img_name' . $sortFlag );
295  }
296 
297  $res = $this->select( __METHOD__ );
298 
299  $titles = [];
300  $count = 0;
301  $result = $this->getResult();
302  foreach ( $res as $row ) {
303  if ( ++$count > $limit ) {
304  // We've reached the one extra which shows that there are
305  // additional pages to be had. Stop here...
306  if ( $params['sort'] == 'name' ) {
307  $this->setContinueEnumParameter( 'continue', $row->img_name );
308  } else {
309  $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
310  }
311  break;
312  }
313 
314  if ( $resultPageSet === null ) {
315  $file = $repo->newFileFromRow( $row );
316  $info = array_merge( [ 'name' => $row->img_name ],
317  ApiQueryImageInfo::getInfo( $file, $prop, $result ) );
318  self::addTitleInfo( $info, $file->getTitle() );
319 
320  $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $info );
321  if ( !$fit ) {
322  if ( $params['sort'] == 'name' ) {
323  $this->setContinueEnumParameter( 'continue', $row->img_name );
324  } else {
325  $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
326  }
327  break;
328  }
329  } else {
330  $titles[] = Title::makeTitle( NS_FILE, $row->img_name );
331  }
332  }
333 
334  if ( $resultPageSet === null ) {
335  $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'img' );
336  } else {
337  $resultPageSet->populateFromTitles( $titles );
338  }
339  }
340 
341  public function getAllowedParams() {
342  $ret = [
343  'sort' => [
344  ApiBase::PARAM_DFLT => 'name',
346  'name',
347  'timestamp'
348  ]
349  ],
350  'dir' => [
351  ApiBase::PARAM_DFLT => 'ascending',
353  // sort=name
354  'ascending',
355  'descending',
356  // sort=timestamp
357  'newer',
358  'older'
359  ]
360  ],
361  'from' => null,
362  'to' => null,
363  'continue' => [
364  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
365  ],
366  'start' => [
367  ApiBase::PARAM_TYPE => 'timestamp'
368  ],
369  'end' => [
370  ApiBase::PARAM_TYPE => 'timestamp'
371  ],
372  'prop' => [
373  ApiBase::PARAM_TYPE => ApiQueryImageInfo::getPropertyNames( $this->propertyFilter ),
374  ApiBase::PARAM_DFLT => 'timestamp|url',
375  ApiBase::PARAM_ISMULTI => true,
376  ApiBase::PARAM_HELP_MSG => 'apihelp-query+imageinfo-param-prop',
378  ApiQueryImageInfo::getPropertyMessages( $this->propertyFilter ),
379  ],
380  'prefix' => null,
381  'minsize' => [
382  ApiBase::PARAM_TYPE => 'integer',
383  ],
384  'maxsize' => [
385  ApiBase::PARAM_TYPE => 'integer',
386  ],
387  'sha1' => null,
388  'sha1base36' => null,
389  'user' => [
390  ApiBase::PARAM_TYPE => 'user',
391  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
392  ],
393  'filterbots' => [
394  ApiBase::PARAM_DFLT => 'all',
396  'all',
397  'bots',
398  'nobots'
399  ]
400  ],
401  'mime' => [
402  ApiBase::PARAM_ISMULTI => true,
403  ],
404  'limit' => [
405  ApiBase::PARAM_DFLT => 10,
406  ApiBase::PARAM_TYPE => 'limit',
407  ApiBase::PARAM_MIN => 1,
410  ],
411  ];
412 
413  if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
414  $ret['mime'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
415  }
416 
417  return $ret;
418  }
419 
420  private $propertyFilter = [ 'archivename', 'thumbmime', 'uploadwarning' ];
421 
422  protected function getExamplesMessages() {
423  return [
424  'action=query&list=allimages&aifrom=B'
425  => 'apihelp-query+allimages-example-b',
426  'action=query&list=allimages&aiprop=user|timestamp|url&' .
427  'aisort=timestamp&aidir=older'
428  => 'apihelp-query+allimages-example-recent',
429  'action=query&list=allimages&aimime=image/png|image/gif'
430  => 'apihelp-query+allimages-example-mimetypes',
431  'action=query&generator=allimages&gailimit=4&' .
432  'gaifrom=T&prop=imageinfo'
433  => 'apihelp-query+allimages-example-generator',
434  ];
435  }
436 
437  public function getHelpUrls() {
438  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allimages';
439  }
440 }
const NS_FILE
Definition: Defines.php:70
const LIST_OR
Definition: Defines.php:46
const LIST_AND
Definition: Defines.php:43
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:506
const PARAM_MAX2
Definition: ApiBase.php:90
const PARAM_MAX
Definition: ApiBase.php:86
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1446
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition: ApiBase.php:1638
const PARAM_TYPE
Definition: ApiBase.php:82
const PARAM_DFLT
Definition: ApiBase.php:74
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:196
const PARAM_MIN
Definition: ApiBase.php:94
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:221
getResult()
Get the result object.
Definition: ApiBase.php:629
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:765
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:163
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:223
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:498
const PARAM_ISMULTI
Definition: ApiBase.php:78
Query module to enumerate all images.
getExamplesMessages()
Returns usage examples for this module.
getCacheMode( $params)
Get the cache mode for the data generated by this module.
getDB()
Override parent method to make sure the repo's DB is used which may not necessarily be the same as th...
executeGenerator( $resultPageSet)
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
__construct(ApiQuery $query, $moduleName, RepoGroup $repoGroup, GroupPermissionsLookup $groupPermissionsLookup)
GroupPermissionsLookup $groupPermissionsLookup
getHelpUrls()
Return links to more detailed help pages about the module.
run( $resultPageSet=null)
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
validateSha1Base36Hash( $hash)
addWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, and an ORDER BY clause to sort in the right direction.
validateSha1Hash( $hash)
addFields( $value)
Add a set of fields to select to the internal array.
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addTimestampWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, similar to addWhereRange, but converts $start and $end t...
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
titlePartToKey( $titlePart, $namespace=NS_MAIN)
Convert an input title or title prefix into a dbkey.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
static getPropertyNames( $filter=[])
Returns all possible parameters to iiprop.
static getInfo( $file, $prop, $result, $thumbParams=null, $opts=false)
Get result information for an image revision.
static getPropertyMessages( $filter=[])
Returns messages for all possible parameters to iiprop.
This is the main query class.
Definition: ApiQuery.php:40
static splitMime( $mime)
Split an internet media type into its two components; if not a two-part name, set the minor type to '...
Definition: File.php:307
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object.
Definition: LocalFile.php:267
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition: LocalRepo.php:39
A class containing constants representing the names of configuration variables.
Prioritized list of file repositories.
Definition: RepoGroup.php:29
getLocalRepo()
Get the local repository, i.e.
Definition: RepoGroup.php:339
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:637
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:39
$mime
Definition: router.php:60
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42