MediaWiki REL1_39
ApiQueryAllImages.php
Go to the documentation of this file.
1<?php
2
33
40
44 protected $mRepo;
45
47 private $groupPermissionsLookup;
48
55 public function __construct(
56 ApiQuery $query,
57 $moduleName,
58 RepoGroup $repoGroup,
59 GroupPermissionsLookup $groupPermissionsLookup
60 ) {
61 parent::__construct( $query, $moduleName, 'ai' );
62 $this->mRepo = $repoGroup->getLocalRepo();
63 $this->groupPermissionsLookup = $groupPermissionsLookup;
64 }
65
73 protected function getDB() {
74 return $this->mRepo->getReplicaDB();
75 }
76
77 public function execute() {
78 $this->run();
79 }
80
81 public function getCacheMode( $params ) {
82 return 'public';
83 }
84
89 public function executeGenerator( $resultPageSet ) {
90 if ( $resultPageSet->isResolvingRedirects() ) {
91 $this->dieWithError( 'apierror-allimages-redirect', 'invalidparammix' );
92 }
93
94 $this->run( $resultPageSet );
95 }
96
101 private function run( $resultPageSet = null ) {
102 $repo = $this->mRepo;
103 if ( !$repo instanceof LocalRepo ) {
104 $this->dieWithError( 'apierror-unsupportedrepo' );
105 }
106
107 $prefix = $this->getModulePrefix();
108
109 $db = $this->getDB();
110
111 $params = $this->extractRequestParams();
112
113 // Table and return fields
114 $prop = array_fill_keys( $params['prop'], true );
115
116 $fileQuery = LocalFile::getQueryInfo();
117 $this->addTables( $fileQuery['tables'] );
118 $this->addFields( $fileQuery['fields'] );
119 $this->addJoinConds( $fileQuery['joins'] );
120
121 $ascendingOrder = true;
122 if ( $params['dir'] == 'descending' || $params['dir'] == 'older' ) {
123 $ascendingOrder = false;
124 }
125
126 if ( $params['sort'] == 'name' ) {
127 // Check mutually exclusive params
128 $disallowed = [ 'start', 'end', 'user' ];
129 foreach ( $disallowed as $pname ) {
130 if ( isset( $params[$pname] ) ) {
131 $this->dieWithError(
132 [
133 'apierror-invalidparammix-mustusewith',
134 "{$prefix}{$pname}",
135 "{$prefix}sort=timestamp"
136 ],
137 'invalidparammix'
138 );
139 }
140 }
141 if ( $params['filterbots'] != 'all' ) {
142 $this->dieWithError(
143 [
144 'apierror-invalidparammix-mustusewith',
145 "{$prefix}filterbots",
146 "{$prefix}sort=timestamp"
147 ],
148 'invalidparammix'
149 );
150 }
151
152 // Pagination
153 if ( $params['continue'] !== null ) {
154 $cont = explode( '|', $params['continue'] );
155 $this->dieContinueUsageIf( count( $cont ) != 1 );
156 $op = $ascendingOrder ? '>' : '<';
157 $continueFrom = $db->addQuotes( $cont[0] );
158 $this->addWhere( "img_name $op= $continueFrom" );
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( 'img_name' . $db->buildLike(
168 $this->titlePartToKey( $params['prefix'], NS_FILE ),
169 $db->anyString() ) );
170 }
171 } else {
172 // Check mutually exclusive params
173 $disallowed = [ 'from', 'to', 'prefix' ];
174 foreach ( $disallowed as $pname ) {
175 if ( isset( $params[$pname] ) ) {
176 $this->dieWithError(
177 [
178 'apierror-invalidparammix-mustusewith',
179 "{$prefix}{$pname}",
180 "{$prefix}sort=name"
181 ],
182 'invalidparammix'
183 );
184 }
185 }
186 if ( $params['user'] !== null && $params['filterbots'] != 'all' ) {
187 // Since filterbots checks if each user has the bot right, it
188 // doesn't make sense to use it with user
189 $this->dieWithError(
190 [ 'apierror-invalidparammix-cannotusewith', "{$prefix}user", "{$prefix}filterbots" ]
191 );
192 }
193
194 // Pagination
196 'img_timestamp',
197 $ascendingOrder ? 'newer' : 'older',
198 $params['start'],
199 $params['end']
200 );
201 // Include in ORDER BY for uniqueness
202 $this->addWhereRange( 'img_name', $ascendingOrder ? 'newer' : 'older', null, null );
203
204 if ( $params['continue'] !== null ) {
205 $cont = explode( '|', $params['continue'] );
206 $this->dieContinueUsageIf( count( $cont ) != 2 );
207 $op = ( $ascendingOrder ? '>' : '<' );
208 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
209 $continueName = $db->addQuotes( $cont[1] );
210 $this->addWhere( "img_timestamp $op $continueTimestamp OR " .
211 "(img_timestamp = $continueTimestamp AND " .
212 "img_name $op= $continueName)"
213 );
214 }
215
216 // Image filters
217 if ( $params['user'] !== null ) {
218 $this->addWhereFld( $fileQuery['fields']['img_user_text'], $params['user'] );
219 }
220 if ( $params['filterbots'] != 'all' ) {
221 $this->addTables( 'user_groups' );
222 $this->addJoinConds( [ 'user_groups' => [
223 'LEFT JOIN',
224 [
225 'ug_group' => $this->groupPermissionsLookup->getGroupsWithPermission( 'bot' ),
226 'ug_user = actor_user',
227 'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
228 ]
229 ] ] );
230 $groupCond = $params['filterbots'] == 'nobots' ? 'NULL' : 'NOT NULL';
231 $this->addWhere( "ug_group IS $groupCond" );
232 }
233 }
234
235 // Filters not depending on sort
236 if ( isset( $params['minsize'] ) ) {
237 $this->addWhere( 'img_size>=' . (int)$params['minsize'] );
238 }
239
240 if ( isset( $params['maxsize'] ) ) {
241 $this->addWhere( 'img_size<=' . (int)$params['maxsize'] );
242 }
243
244 $sha1 = false;
245 if ( isset( $params['sha1'] ) ) {
246 $sha1 = strtolower( $params['sha1'] );
247 if ( !$this->validateSha1Hash( $sha1 ) ) {
248 $this->dieWithError( 'apierror-invalidsha1hash' );
249 }
250 $sha1 = Wikimedia\base_convert( $sha1, 16, 36, 31 );
251 } elseif ( isset( $params['sha1base36'] ) ) {
252 $sha1 = strtolower( $params['sha1base36'] );
253 if ( !$this->validateSha1Base36Hash( $sha1 ) ) {
254 $this->dieWithError( 'apierror-invalidsha1base36hash' );
255 }
256 }
257 if ( $sha1 ) {
258 $this->addWhereFld( 'img_sha1', $sha1 );
259 }
260
261 if ( $params['mime'] !== null ) {
262 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
263 $this->dieWithError( 'apierror-mimesearchdisabled' );
264 }
265
266 $mimeConds = [];
267 foreach ( $params['mime'] as $mime ) {
268 list( $major, $minor ) = File::splitMime( $mime );
269 $mimeConds[] = $db->makeList(
270 [
271 'img_major_mime' => $major,
272 'img_minor_mime' => $minor,
273 ],
275 );
276 }
277 // safeguard against internal_api_error_DBQueryError
278 if ( count( $mimeConds ) > 0 ) {
279 $this->addWhere( $db->makeList( $mimeConds, LIST_OR ) );
280 } else {
281 // no MIME types, no files
282 $this->getResult()->addValue( 'query', $this->getModuleName(), [] );
283 return;
284 }
285 }
286
287 $limit = $params['limit'];
288 $this->addOption( 'LIMIT', $limit + 1 );
289 $sortFlag = '';
290 if ( !$ascendingOrder ) {
291 $sortFlag = ' DESC';
292 }
293 if ( $params['sort'] == 'timestamp' ) {
294 $this->addOption( 'ORDER BY', 'img_timestamp' . $sortFlag );
295 } else {
296 $this->addOption( 'ORDER BY', 'img_name' . $sortFlag );
297 }
298
299 $res = $this->select( __METHOD__ );
300
301 $titles = [];
302 $count = 0;
303 $result = $this->getResult();
304 foreach ( $res as $row ) {
305 if ( ++$count > $limit ) {
306 // We've reached the one extra which shows that there are
307 // additional pages to be had. Stop here...
308 if ( $params['sort'] == 'name' ) {
309 $this->setContinueEnumParameter( 'continue', $row->img_name );
310 } else {
311 $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
312 }
313 break;
314 }
315
316 if ( $resultPageSet === null ) {
317 $file = $repo->newFileFromRow( $row );
318 $info = array_merge( [ 'name' => $row->img_name ],
319 ApiQueryImageInfo::getInfo( $file, $prop, $result ) );
320 self::addTitleInfo( $info, $file->getTitle() );
321
322 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $info );
323 if ( !$fit ) {
324 if ( $params['sort'] == 'name' ) {
325 $this->setContinueEnumParameter( 'continue', $row->img_name );
326 } else {
327 $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
328 }
329 break;
330 }
331 } else {
332 $titles[] = Title::makeTitle( NS_FILE, $row->img_name );
333 }
334 }
335
336 if ( $resultPageSet === null ) {
337 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'img' );
338 } else {
339 $resultPageSet->populateFromTitles( $titles );
340 }
341 }
342
343 public function getAllowedParams() {
344 $ret = [
345 'sort' => [
346 ParamValidator::PARAM_DEFAULT => 'name',
347 ParamValidator::PARAM_TYPE => [
348 'name',
349 'timestamp'
350 ]
351 ],
352 'dir' => [
353 ParamValidator::PARAM_DEFAULT => 'ascending',
354 ParamValidator::PARAM_TYPE => [
355 // sort=name
356 'ascending',
357 'descending',
358 // sort=timestamp
359 'newer',
360 'older'
361 ]
362 ],
363 'from' => null,
364 'to' => null,
365 'continue' => [
366 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
367 ],
368 'start' => [
369 ParamValidator::PARAM_TYPE => 'timestamp'
370 ],
371 'end' => [
372 ParamValidator::PARAM_TYPE => 'timestamp'
373 ],
374 'prop' => [
375 ParamValidator::PARAM_TYPE => ApiQueryImageInfo::getPropertyNames( $this->propertyFilter ),
376 ParamValidator::PARAM_DEFAULT => 'timestamp|url',
377 ParamValidator::PARAM_ISMULTI => true,
378 ApiBase::PARAM_HELP_MSG => 'apihelp-query+imageinfo-param-prop',
380 ApiQueryImageInfo::getPropertyMessages( $this->propertyFilter ),
381 ],
382 'prefix' => null,
383 'minsize' => [
384 ParamValidator::PARAM_TYPE => 'integer',
385 ],
386 'maxsize' => [
387 ParamValidator::PARAM_TYPE => 'integer',
388 ],
389 'sha1' => null,
390 'sha1base36' => null,
391 'user' => [
392 ParamValidator::PARAM_TYPE => 'user',
393 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'id', 'interwiki' ],
394 ],
395 'filterbots' => [
396 ParamValidator::PARAM_DEFAULT => 'all',
397 ParamValidator::PARAM_TYPE => [
398 'all',
399 'bots',
400 'nobots'
401 ]
402 ],
403 'mime' => [
404 ParamValidator::PARAM_ISMULTI => true,
405 ],
406 'limit' => [
407 ParamValidator::PARAM_DEFAULT => 10,
408 ParamValidator::PARAM_TYPE => 'limit',
409 IntegerDef::PARAM_MIN => 1,
410 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
411 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
412 ],
413 ];
414
415 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
416 $ret['mime'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
417 }
418
419 return $ret;
420 }
421
422 private $propertyFilter = [ 'archivename', 'thumbmime', 'uploadwarning' ];
423
424 protected function getExamplesMessages() {
425 return [
426 'action=query&list=allimages&aifrom=B'
427 => 'apihelp-query+allimages-example-b',
428 'action=query&list=allimages&aiprop=user|timestamp|url&' .
429 'aisort=timestamp&aidir=older'
430 => 'apihelp-query+allimages-example-recent',
431 'action=query&list=allimages&aimime=image/png|image/gif'
432 => 'apihelp-query+allimages-example-mimetypes',
433 'action=query&generator=allimages&gailimit=4&' .
434 'gaifrom=T&prop=imageinfo'
435 => 'apihelp-query+allimages-example-generator',
436 ];
437 }
438
439 public function getHelpUrls() {
440 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allimages';
441 }
442}
const NS_FILE
Definition Defines.php:70
const LIST_OR
Definition Defines.php:46
const LIST_AND
Definition Defines.php:43
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1454
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:506
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition ApiBase.php:1643
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 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
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)
getHelpUrls()
Return links to more detailed help pages about the module.
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:41
static splitMime(?string $mime)
Split an internet media type into its two components; if not a two-part name, set the minor type to '...
Definition File.php:306
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object.
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.
Type definition for user types.
Definition UserDef.php:27
Prioritized list of file repositories.
Definition RepoGroup.php:29
getLocalRepo()
Get the local repository, i.e.
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition Title.php:638
Service for formatting and validating API parameters.
Type definition for integer types.
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