MediaWiki master
ApiQueryAllImages.php
Go to the documentation of this file.
1<?php
2
13namespace MediaWiki\Api;
14
28
35
39 protected $mRepo;
40
41 public function __construct(
42 ApiQuery $query,
43 string $moduleName,
44 RepoGroup $repoGroup,
45 private readonly GroupPermissionsLookup $groupPermissionsLookup,
46 ) {
47 parent::__construct( $query, $moduleName, 'ai' );
48 $this->mRepo = $repoGroup->getLocalRepo();
49 }
50
58 protected function getDB() {
59 return $this->mRepo->getReplicaDB();
60 }
61
62 public function execute() {
63 $this->run();
64 }
65
67 public function getCacheMode( $params ) {
68 return 'public';
69 }
70
75 public function executeGenerator( $resultPageSet ) {
76 if ( $resultPageSet->isResolvingRedirects() ) {
77 $this->dieWithError( 'apierror-allimages-redirect', 'invalidparammix' );
78 }
79
80 $this->run( $resultPageSet );
81 }
82
87 private function run( $resultPageSet = null ) {
88 $repo = $this->mRepo;
89 if ( !$repo instanceof LocalRepo ) {
90 $this->dieWithError( 'apierror-unsupportedrepo' );
91 }
92
93 $prefix = $this->getModulePrefix();
94
95 $db = $this->getDB();
96
97 $params = $this->extractRequestParams();
98
99 // Table and return fields
100 $prop = array_fill_keys( $params['prop'], true );
101
102 $fileQuery = FileSelectQueryBuilder::newForFile( $db )->getQueryInfo();
103 $this->addTables( $fileQuery['tables'] );
104 $this->addFields( $fileQuery['fields'] );
105 $this->addJoinConds( $fileQuery['join_conds'] );
106
107 $ascendingOrder = true;
108 if ( $params['dir'] == 'descending' || $params['dir'] == 'older' ) {
109 $ascendingOrder = false;
110 }
111
112 if ( $params['sort'] == 'name' ) {
113 // Check mutually exclusive params
114 $disallowed = [ 'start', 'end', 'user' ];
115 foreach ( $disallowed as $pname ) {
116 if ( isset( $params[$pname] ) ) {
117 $this->dieWithError(
118 [
119 'apierror-invalidparammix-mustusewith',
120 "{$prefix}{$pname}",
121 "{$prefix}sort=timestamp"
122 ],
123 'invalidparammix'
124 );
125 }
126 }
127 if ( $params['filterbots'] != 'all' ) {
128 $this->dieWithError(
129 [
130 'apierror-invalidparammix-mustusewith',
131 "{$prefix}filterbots",
132 "{$prefix}sort=timestamp"
133 ],
134 'invalidparammix'
135 );
136 }
137
138 // Pagination
139 if ( $params['continue'] !== null ) {
140 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string' ] );
141 $op = $ascendingOrder ? '>=' : '<=';
142 $this->addWhere( $db->expr( 'img_name', $op, $cont[0] ) );
143 }
144
145 // Image filters
146 $from = $params['from'] === null ? null : $this->titlePartToKey( $params['from'], NS_FILE );
147 $to = $params['to'] === null ? null : $this->titlePartToKey( $params['to'], NS_FILE );
148 $this->addWhereRange( 'img_name', $ascendingOrder ? 'newer' : 'older', $from, $to );
149
150 if ( isset( $params['prefix'] ) ) {
151 $this->addWhere(
152 $db->expr(
153 'img_name',
154 IExpression::LIKE,
155 new LikeValue( $this->titlePartToKey( $params['prefix'], NS_FILE ), $db->anyString() )
156 )
157 );
158 }
159 } else {
160 // Check mutually exclusive params
161 $disallowed = [ 'from', 'to', 'prefix' ];
162 foreach ( $disallowed as $pname ) {
163 if ( isset( $params[$pname] ) ) {
164 $this->dieWithError(
165 [
166 'apierror-invalidparammix-mustusewith',
167 "{$prefix}{$pname}",
168 "{$prefix}sort=name"
169 ],
170 'invalidparammix'
171 );
172 }
173 }
174 if ( $params['user'] !== null && $params['filterbots'] != 'all' ) {
175 // Since filterbots checks if each user has the bot right, it
176 // doesn't make sense to use it with user
177 $this->dieWithError(
178 [ 'apierror-invalidparammix-cannotusewith', "{$prefix}user", "{$prefix}filterbots" ]
179 );
180 }
181
182 // Pagination
184 'img_timestamp',
185 $ascendingOrder ? 'newer' : 'older',
186 $params['start'],
187 $params['end']
188 );
189 // Include in ORDER BY for uniqueness
190 $this->addWhereRange( 'img_name', $ascendingOrder ? 'newer' : 'older', null, null );
191
192 if ( $params['continue'] !== null ) {
193 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'timestamp', 'string' ] );
194 $op = ( $ascendingOrder ? '>=' : '<=' );
195 $this->addWhere( $db->buildComparison( $op, [
196 'img_timestamp' => $db->timestamp( $cont[0] ),
197 'img_name' => $cont[1],
198 ] ) );
199 }
200
201 // Image filters
202 if ( $params['user'] !== null ) {
203 if ( isset( $fileQuery['fields']['img_user_text'] ) ) {
204 $this->addWhereFld( $fileQuery['fields']['img_user_text'], $params['user'] );
205 } else {
206 // file read new
207 $this->addWhereFld( 'img_user_text', $params['user'] );
208 }
209
210 }
211 if ( $params['filterbots'] != 'all' ) {
212 $this->addTables( 'user_groups' );
213 $this->addJoinConds( [ 'user_groups' => [
214 'LEFT JOIN',
215 [
216 'ug_group' => $this->groupPermissionsLookup->getGroupsWithPermission( 'bot' ),
217 'ug_user = actor_user',
218 $db->expr( 'ug_expiry', '=', null )->or( 'ug_expiry', '>=', $db->timestamp() )
219 ]
220 ] ] );
221 $groupCond = $params['filterbots'] == 'nobots' ? 'NULL' : 'NOT NULL';
222 $this->addWhere( "ug_group IS $groupCond" );
223 }
224 }
225
226 // Filters not depending on sort
227 if ( isset( $params['minsize'] ) ) {
228 $this->addWhere( 'img_size>=' . (int)$params['minsize'] );
229 }
230
231 if ( isset( $params['maxsize'] ) ) {
232 $this->addWhere( 'img_size<=' . (int)$params['maxsize'] );
233 }
234
235 $sha1 = false;
236 if ( isset( $params['sha1'] ) ) {
237 $sha1 = strtolower( $params['sha1'] );
238 if ( !$this->validateSha1Hash( $sha1 ) ) {
239 $this->dieWithError( 'apierror-invalidsha1hash' );
240 }
241 $sha1 = \Wikimedia\base_convert( $sha1, 16, 36, 31 );
242 } elseif ( isset( $params['sha1base36'] ) ) {
243 $sha1 = strtolower( $params['sha1base36'] );
244 if ( !$this->validateSha1Base36Hash( $sha1 ) ) {
245 $this->dieWithError( 'apierror-invalidsha1base36hash' );
246 }
247 }
248 if ( $sha1 ) {
249 $this->addWhereFld( 'img_sha1', $sha1 );
250 }
251
252 if ( $params['mime'] !== null ) {
253 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
254 $this->dieWithError( 'apierror-mimesearchdisabled' );
255 }
256
257 $mimeConds = [];
258 foreach ( $params['mime'] as $mime ) {
259 [ $major, $minor ] = File::splitMime( $mime );
260 $mimeConds[] =
261 $db->expr( 'img_major_mime', '=', $major )
262 ->and( 'img_minor_mime', '=', $minor );
263 }
264 if ( count( $mimeConds ) > 0 ) {
265 $this->addWhere( $db->orExpr( $mimeConds ) );
266 } else {
267 // no MIME types, no files
268 $this->getResult()->addValue( 'query', $this->getModuleName(), [] );
269 return;
270 }
271 }
272
273 $limit = $params['limit'];
274 $this->addOption( 'LIMIT', $limit + 1 );
275
276 $res = $this->select( __METHOD__ );
277
278 $titles = [];
279 $count = 0;
280 $result = $this->getResult();
281 foreach ( $res as $row ) {
282 if ( ++$count > $limit ) {
283 // We've reached the one extra which shows that there are
284 // additional pages to be had. Stop here...
285 if ( $params['sort'] == 'name' ) {
286 $this->setContinueEnumParameter( 'continue', $row->img_name );
287 } else {
288 $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
289 }
290 break;
291 }
292
293 if ( $resultPageSet === null ) {
294 $file = $repo->newFileFromRow( $row );
295 $info = ApiQueryImageInfo::getInfo( $file, $prop, $result ) +
296 [ 'name' => $row->img_name ];
297 self::addTitleInfo( $info, $file->getTitle() );
298
299 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $info );
300 if ( !$fit ) {
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 } else {
309 $titles[] = Title::makeTitle( NS_FILE, $row->img_name );
310 }
311 }
312
313 if ( $resultPageSet === null ) {
314 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'img' );
315 } else {
316 $resultPageSet->populateFromTitles( $titles );
317 }
318 }
319
321 public function getAllowedParams() {
322 $ret = [
323 'sort' => [
324 ParamValidator::PARAM_DEFAULT => 'name',
325 ParamValidator::PARAM_TYPE => [
326 'name',
327 'timestamp'
328 ]
329 ],
330 'dir' => [
331 ParamValidator::PARAM_DEFAULT => 'ascending',
332 ParamValidator::PARAM_TYPE => [
333 // sort=name
334 'ascending',
335 'descending',
336 // sort=timestamp
337 'newer',
338 'older'
339 ]
340 ],
341 'from' => null,
342 'to' => null,
343 'continue' => [
344 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
345 ],
346 'start' => [
347 ParamValidator::PARAM_TYPE => 'timestamp'
348 ],
349 'end' => [
350 ParamValidator::PARAM_TYPE => 'timestamp'
351 ],
352 'prop' => [
353 ParamValidator::PARAM_TYPE => ApiQueryImageInfo::getPropertyNames( self::PROPERTY_FILTER ),
354 ParamValidator::PARAM_DEFAULT => 'timestamp|url',
355 ParamValidator::PARAM_ISMULTI => true,
356 ApiBase::PARAM_HELP_MSG => 'apihelp-query+imageinfo-param-prop',
358 ApiQueryImageInfo::getPropertyMessages( self::PROPERTY_FILTER ),
359 ],
360 'prefix' => null,
361 'minsize' => [
362 ParamValidator::PARAM_TYPE => 'integer',
363 ],
364 'maxsize' => [
365 ParamValidator::PARAM_TYPE => 'integer',
366 ],
367 'sha1' => null,
368 'sha1base36' => null,
369 'user' => [
370 ParamValidator::PARAM_TYPE => 'user',
371 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'temp', 'id', 'interwiki' ],
372 ],
373 'filterbots' => [
374 ParamValidator::PARAM_DEFAULT => 'all',
375 ParamValidator::PARAM_TYPE => [
376 'all',
377 'bots',
378 'nobots'
379 ]
380 ],
381 'mime' => [
382 ParamValidator::PARAM_ISMULTI => true,
383 ],
384 'limit' => [
385 ParamValidator::PARAM_DEFAULT => 10,
386 ParamValidator::PARAM_TYPE => 'limit',
387 IntegerDef::PARAM_MIN => 1,
388 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
389 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
390 ],
391 ];
392
393 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
394 $ret['mime'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
395 }
396
397 return $ret;
398 }
399
400 private const PROPERTY_FILTER = [ 'archivename', 'thumbmime', 'uploadwarning' ];
401
403 protected function getExamplesMessages() {
404 return [
405 'action=query&list=allimages&aifrom=B'
406 => 'apihelp-query+allimages-example-b',
407 'action=query&list=allimages&aiprop=user|timestamp|url&' .
408 'aisort=timestamp&aidir=older'
409 => 'apihelp-query+allimages-example-recent',
410 'action=query&list=allimages&aimime=image/png|image/gif'
411 => 'apihelp-query+allimages-example-mimetypes',
412 'action=query&generator=allimages&gailimit=4&' .
413 'gaifrom=T&prop=imageinfo'
414 => 'apihelp-query+allimages-example-generator',
415 ];
416 }
417
419 public function getHelpUrls() {
420 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allimages';
421 }
422}
423
425class_alias( ApiQueryAllImages::class, 'ApiQueryAllImages' );
const NS_FILE
Definition Defines.php:57
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:206
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:166
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:233
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:231
Query module to enumerate all images.
__construct(ApiQuery $query, string $moduleName, RepoGroup $repoGroup, private readonly GroupPermissionsLookup $groupPermissionsLookup,)
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
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.1.25, returning boolean false is deprecated...
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.Override this in the module subclass....
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:36
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
static newForFile(IReadableDatabase $db, array $options=[])
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:80
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:45
Prioritized list of file repositories.
Definition RepoGroup.php:30
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:69
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.