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