Merge "Add some entries removed in I41f1995d back."
[lhc/web/wiklou.git] / includes / api / ApiQueryAllImages.php
1 <?php
2
3 /**
4 * API for MediaWiki 1.12+
5 *
6 * Created on Mar 16, 2008
7 *
8 * Copyright © 2008 Vasiliev Victor vasilvv@gmail.com,
9 * based on ApiQueryAllPages.php
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 * http://www.gnu.org/copyleft/gpl.html
25 *
26 * @file
27 */
28
29 /**
30 * Query module to enumerate all available pages.
31 *
32 * @ingroup API
33 */
34 class ApiQueryAllImages extends ApiQueryGeneratorBase {
35
36 protected $mRepo;
37
38 public function __construct( $query, $moduleName ) {
39 parent::__construct( $query, $moduleName, 'ai' );
40 $this->mRepo = RepoGroup::singleton()->getLocalRepo();
41 }
42
43 /**
44 * Override parent method to make sure to make sure the repo's DB is used
45 * which may not necesarilly be the same as the local DB.
46 *
47 * TODO: allow querying non-local repos.
48 * @return DatabaseBase
49 */
50 protected function getDB() {
51 return $this->mRepo->getSlaveDB();
52 }
53
54 public function execute() {
55 $this->run();
56 }
57
58 public function getCacheMode( $params ) {
59 return 'public';
60 }
61
62 /**
63 * @param $resultPageSet ApiPageSet
64 * @return void
65 */
66 public function executeGenerator( $resultPageSet ) {
67 if ( $resultPageSet->isResolvingRedirects() ) {
68 $this->dieUsage( 'Use "gaifilterredir=nonredirects" option instead of "redirects" when using allimages as a generator', 'params' );
69 }
70
71 $this->run( $resultPageSet );
72 }
73
74 /**
75 * @param $resultPageSet ApiPageSet
76 * @return void
77 */
78 private function run( $resultPageSet = null ) {
79 $repo = $this->mRepo;
80 if ( !$repo instanceof LocalRepo ) {
81 $this->dieUsage( 'Local file repository does not support querying all images', 'unsupportedrepo' );
82 }
83
84 $prefix = $this->getModulePrefix();
85
86 $db = $this->getDB();
87
88 $params = $this->extractRequestParams();
89
90 // Table and return fields
91 $this->addTables( 'image' );
92
93 $prop = array_flip( $params['prop'] );
94 $this->addFields( LocalFile::selectFields() );
95
96 $ascendingOrder = true;
97 if ( $params['dir'] == 'descending' || $params['dir'] == 'older') {
98 $ascendingOrder = false;
99 }
100
101 if ( $params['sort'] == 'name' ) {
102 // Check mutually exclusive params
103 $disallowed = array( 'start', 'end', 'user' );
104 foreach ( $disallowed as $pname ) {
105 if ( isset( $params[$pname] ) ) {
106 $this->dieUsage( "Parameter '{$prefix}{$pname}' can only be used with {$prefix}sort=timestamp", 'badparams' );
107 }
108 }
109 if ( $params['filterbots'] != 'all' ) {
110 $this->dieUsage( "Parameter '{$prefix}filterbots' can only be used with {$prefix}sort=timestamp", 'badparams' );
111 }
112
113 // Pagination
114 if ( !is_null( $params['continue'] ) ) {
115 $cont = explode( '|', $params['continue'] );
116 if ( count( $cont ) != 1 ) {
117 $this->dieUsage( 'Invalid continue param. You should pass the ' .
118 'original value returned by the previous query', '_badcontinue' );
119 }
120 $op = ( $ascendingOrder ? '>' : '<' );
121 $continueFrom = $db->addQuotes( $cont[0] );
122 $this->addWhere( "img_name $op= $continueFrom" );
123 }
124
125 // Image filters
126 $from = ( is_null( $params['from'] ) ? null : $this->titlePartToKey( $params['from'] ) );
127 $to = ( is_null( $params['to'] ) ? null : $this->titlePartToKey( $params['to'] ) );
128 $this->addWhereRange( 'img_name', ( $ascendingOrder ? 'newer' : 'older' ), $from, $to );
129
130 if ( isset( $params['prefix'] ) ) {
131 $this->addWhere( 'img_name' . $db->buildLike( $this->titlePartToKey( $params['prefix'] ), $db->anyString() ) );
132 }
133 } else {
134 // Check mutually exclusive params
135 $disallowed = array( 'from', 'to', 'prefix' );
136 foreach ( $disallowed as $pname ) {
137 if ( isset( $params[$pname] ) ) {
138 $this->dieUsage( "Parameter '{$prefix}{$pname}' can only be used with {$prefix}sort=name", 'badparams' );
139 }
140 }
141 if ( !is_null( $params['user'] ) && $params['filterbots'] != 'all' ) {
142 // Since filterbots checks if each user has the bot right, it doesn't make sense to use it with user
143 $this->dieUsage( "Parameters '{$prefix}user' and '{$prefix}filterbots' cannot be used together", 'badparams' );
144 }
145
146 // Pagination
147 $this->addTimestampWhereRange( 'img_timestamp', ( $ascendingOrder ? 'newer' : 'older' ), $params['start'], $params['end'] );
148
149 // Image filters
150 if ( !is_null( $params['user'] ) ) {
151 $this->addWhereFld( 'img_user_text', $params['user'] );
152 }
153 if ( $params['filterbots'] != 'all' ) {
154 $this->addTables( 'user_groups' );
155 $this->addJoinConds( array( 'user_groups' => array(
156 'LEFT JOIN',
157 array(
158 'ug_group' => User::getGroupsWithPermission( 'bot' ),
159 'ug_user = img_user'
160 )
161 ) ) );
162 $groupCond = ( $params['filterbots'] == 'nobots' ? 'NULL': 'NOT NULL' );
163 $this->addWhere( "ug_group IS $groupCond" );
164 }
165 }
166
167 // Filters not depending on sort
168 if ( isset( $params['minsize'] ) ) {
169 $this->addWhere( 'img_size>=' . intval( $params['minsize'] ) );
170 }
171
172 if ( isset( $params['maxsize'] ) ) {
173 $this->addWhere( 'img_size<=' . intval( $params['maxsize'] ) );
174 }
175
176 $sha1 = false;
177 if ( isset( $params['sha1'] ) ) {
178 if ( !$this->validateSha1Hash( $params['sha1'] ) ) {
179 $this->dieUsage( 'The SHA1 hash provided is not valid', 'invalidsha1hash' );
180 }
181 $sha1 = wfBaseConvert( $params['sha1'], 16, 36, 31 );
182 } elseif ( isset( $params['sha1base36'] ) ) {
183 $sha1 = $params['sha1base36'];
184 if ( !$this->validateSha1Base36Hash( $sha1 ) ) {
185 $this->dieUsage( 'The SHA1Base36 hash provided is not valid', 'invalidsha1base36hash' );
186 }
187 }
188 if ( $sha1 ) {
189 $this->addWhereFld( 'img_sha1', $sha1 );
190 }
191
192 if ( !is_null( $params['mime'] ) ) {
193 global $wgMiserMode;
194 if ( $wgMiserMode ) {
195 $this->dieUsage( 'MIME search disabled in Miser Mode', 'mimesearchdisabled' );
196 }
197
198 list( $major, $minor ) = File::splitMime( $params['mime'] );
199
200 $this->addWhereFld( 'img_major_mime', $major );
201 $this->addWhereFld( 'img_minor_mime', $minor );
202 }
203
204 $limit = $params['limit'];
205 $this->addOption( 'LIMIT', $limit + 1 );
206 $sortFlag = '';
207 if ( !$ascendingOrder ) {
208 $sortFlag = ' DESC';
209 }
210 if ( $params['sort'] == 'timestamp' ) {
211 $this->addOption( 'ORDER BY', 'img_timestamp' . $sortFlag );
212 if ( !is_null( $params['user'] ) ) {
213 $this->addOption( 'USE INDEX', array( 'image' => 'img_usertext_timestamp' ) );
214 } else {
215 $this->addOption( 'USE INDEX', array( 'image' => 'img_timestamp' ) );
216 }
217 } else {
218 $this->addOption( 'ORDER BY', 'img_name' . $sortFlag );
219 }
220
221 $res = $this->select( __METHOD__ );
222
223 $titles = array();
224 $count = 0;
225 $result = $this->getResult();
226 foreach ( $res as $row ) {
227 if ( ++ $count > $limit ) {
228 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
229 if ( $params['sort'] == 'name' ) {
230 $this->setContinueEnumParameter( 'continue', $row->img_name );
231 } else {
232 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->img_timestamp ) );
233 }
234 break;
235 }
236
237 if ( is_null( $resultPageSet ) ) {
238 $file = $repo->newFileFromRow( $row );
239 $info = array_merge( array( 'name' => $row->img_name ),
240 ApiQueryImageInfo::getInfo( $file, $prop, $result ) );
241 self::addTitleInfo( $info, $file->getTitle() );
242
243 $fit = $result->addValue( array( 'query', $this->getModuleName() ), null, $info );
244 if ( !$fit ) {
245 if ( $params['sort'] == 'name' ) {
246 $this->setContinueEnumParameter( 'continue', $row->img_name );
247 } else {
248 $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->img_timestamp ) );
249 }
250 break;
251 }
252 } else {
253 $titles[] = Title::makeTitle( NS_FILE, $row->img_name );
254 }
255 }
256
257 if ( is_null( $resultPageSet ) ) {
258 $result->setIndexedTagName_internal( array( 'query', $this->getModuleName() ), 'img' );
259 } else {
260 $resultPageSet->populateFromTitles( $titles );
261 }
262 }
263
264 public function getAllowedParams() {
265 return array (
266 'sort' => array(
267 ApiBase::PARAM_DFLT => 'name',
268 ApiBase::PARAM_TYPE => array(
269 'name',
270 'timestamp'
271 )
272 ),
273 'dir' => array(
274 ApiBase::PARAM_DFLT => 'ascending',
275 ApiBase::PARAM_TYPE => array(
276 // sort=name
277 'ascending',
278 'descending',
279 // sort=timestamp
280 'newer',
281 'older'
282 )
283 ),
284 'from' => null,
285 'to' => null,
286 'continue' => null,
287 'start' => array(
288 ApiBase::PARAM_TYPE => 'timestamp'
289 ),
290 'end' => array(
291 ApiBase::PARAM_TYPE => 'timestamp'
292 ),
293 'prop' => array(
294 ApiBase::PARAM_TYPE => ApiQueryImageInfo::getPropertyNames( $this->propertyFilter ),
295 ApiBase::PARAM_DFLT => 'timestamp|url',
296 ApiBase::PARAM_ISMULTI => true
297 ),
298 'prefix' => null,
299 'minsize' => array(
300 ApiBase::PARAM_TYPE => 'integer',
301 ),
302 'maxsize' => array(
303 ApiBase::PARAM_TYPE => 'integer',
304 ),
305 'sha1' => null,
306 'sha1base36' => null,
307 'user' => array(
308 ApiBase::PARAM_TYPE => 'user'
309 ),
310 'filterbots' => array(
311 ApiBase::PARAM_DFLT => 'all',
312 ApiBase::PARAM_TYPE => array(
313 'all',
314 'bots',
315 'nobots'
316 )
317 ),
318 'mime' => null,
319 'limit' => array(
320 ApiBase::PARAM_DFLT => 10,
321 ApiBase::PARAM_TYPE => 'limit',
322 ApiBase::PARAM_MIN => 1,
323 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
324 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
325 ),
326 );
327 }
328
329 public function getParamDescription() {
330 $p = $this->getModulePrefix();
331 return array(
332 'sort' => 'Property to sort by',
333 'dir' => 'The direction in which to list',
334 'from' => "The image title to start enumerating from. Can only be used with {$p}sort=name",
335 'to' => "The image title to stop enumerating at. Can only be used with {$p}sort=name",
336 'continue' => 'When more results are available, use this to continue',
337 'start' => "The timestamp to start enumerating from. Can only be used with {$p}sort=timestamp",
338 'end' => "The timestamp to end enumerating. Can only be used with {$p}sort=timestamp",
339 'prop' => ApiQueryImageInfo::getPropertyDescriptions( $this->propertyFilter ),
340 'prefix' => "Search for all image titles that begin with this value. Can only be used with {$p}sort=name",
341 'minsize' => 'Limit to images with at least this many bytes',
342 'maxsize' => 'Limit to images with at most this many bytes',
343 'sha1' => "SHA1 hash of image. Overrides {$p}sha1base36",
344 'sha1base36' => 'SHA1 hash of image in base 36 (used in MediaWiki)',
345 'user' => "Only return files uploaded by this user. Can only be used with {$p}sort=timestamp. Cannot be used together with {$p}filterbots",
346 'filterbots' => "How to filter files uploaded by bots. Can only be used with {$p}sort=timestamp. Cannot be used together with {$p}user",
347 'mime' => 'What MIME type to search for. e.g. image/jpeg. Disabled in Miser Mode',
348 'limit' => 'How many images in total to return',
349 );
350 }
351
352 private $propertyFilter = array( 'archivename', 'thumbmime' );
353
354 public function getResultProperties() {
355 return array_merge(
356 array(
357 '' => array(
358 'name' => 'string',
359 'ns' => 'namespace',
360 'title' => 'string'
361 )
362 ),
363 ApiQueryImageInfo::getResultPropertiesFiltered( $this->propertyFilter )
364 );
365 }
366
367 public function getDescription() {
368 return 'Enumerate all images sequentially';
369 }
370
371 public function getPossibleErrors() {
372 $p = $this->getModulePrefix();
373 return array_merge( parent::getPossibleErrors(), array(
374 array( 'code' => 'params', 'info' => 'Use "gaifilterredir=nonredirects" option instead of "redirects" when using allimages as a generator' ),
375 array( 'code' => 'badparams', 'info' => "Parameter'{$p}start' can only be used with {$p}sort=timestamp" ),
376 array( 'code' => 'badparams', 'info' => "Parameter'{$p}end' can only be used with {$p}sort=timestamp" ),
377 array( 'code' => 'badparams', 'info' => "Parameter'{$p}user' can only be used with {$p}sort=timestamp" ),
378 array( 'code' => 'badparams', 'info' => "Parameter'{$p}filterbots' can only be used with {$p}sort=timestamp" ),
379 array( 'code' => 'badparams', 'info' => "Parameter'{$p}from' can only be used with {$p}sort=name" ),
380 array( 'code' => 'badparams', 'info' => "Parameter'{$p}to' can only be used with {$p}sort=name" ),
381 array( 'code' => 'badparams', 'info' => "Parameter'{$p}prefix' can only be used with {$p}sort=name" ),
382 array( 'code' => 'badparams', 'info' => "Parameters '{$p}user' and '{$p}filterbots' cannot be used together" ),
383 array( 'code' => 'unsupportedrepo', 'info' => 'Local file repository does not support querying all images' ),
384 array( 'code' => 'mimesearchdisabled', 'info' => 'MIME search disabled in Miser Mode' ),
385 array( 'code' => 'invalidsha1hash', 'info' => 'The SHA1 hash provided is not valid' ),
386 array( 'code' => 'invalidsha1base36hash', 'info' => 'The SHA1Base36 hash provided is not valid' ),
387 array( 'code' => '_badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
388 ) );
389 }
390
391 public function getExamples() {
392 return array(
393 'api.php?action=query&list=allimages&aifrom=B' => array(
394 'Simple Use',
395 'Show a list of files starting at the letter "B"',
396 ),
397 'api.php?action=query&list=allimages&aiprop=user|timestamp|url&aisort=timestamp&aidir=older' => array(
398 'Simple Use',
399 'Show a list of recently uploaded files similar to Special:NewFiles',
400 ),
401 'api.php?action=query&generator=allimages&gailimit=4&gaifrom=T&prop=imageinfo' => array(
402 'Using as Generator',
403 'Show info about 4 files starting at the letter "T"',
404 ),
405 );
406 }
407
408 public function getHelpUrls() {
409 return 'https://www.mediawiki.org/wiki/API:Allimages';
410 }
411
412 public function getVersion() {
413 return __CLASS__ . ': $Id$';
414 }
415 }