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