Merge "Add support for PHP7 random_bytes in favor of mcrypt_create_iv"
[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 protected $mRepo;
36
37 public function __construct( ApiQuery $query, $moduleName ) {
38 parent::__construct( $query, $moduleName, 'ai' );
39 $this->mRepo = RepoGroup::singleton()->getLocalRepo();
40 }
41
42 /**
43 * Override parent method to make sure the repo's DB is used
44 * which may not necessarily be the same as the local DB.
45 *
46 * TODO: allow querying non-local repos.
47 * @return IDatabase
48 */
49 protected function getDB() {
50 return $this->mRepo->getReplicaDB();
51 }
52
53 public function execute() {
54 $this->run();
55 }
56
57 public function getCacheMode( $params ) {
58 return 'public';
59 }
60
61 /**
62 * @param ApiPageSet $resultPageSet
63 * @return void
64 */
65 public function executeGenerator( $resultPageSet ) {
66 if ( $resultPageSet->isResolvingRedirects() ) {
67 $this->dieWithError( 'apierror-allimages-redirect', 'invalidparammix' );
68 }
69
70 $this->run( $resultPageSet );
71 }
72
73 /**
74 * @param ApiPageSet $resultPageSet
75 * @return void
76 */
77 private function run( $resultPageSet = null ) {
78 $repo = $this->mRepo;
79 if ( !$repo instanceof LocalRepo ) {
80 $this->dieWithError( 'apierror-unsupportedrepo' );
81 }
82
83 $prefix = $this->getModulePrefix();
84
85 $db = $this->getDB();
86
87 $params = $this->extractRequestParams();
88
89 // Table and return fields
90 $this->addTables( 'image' );
91
92 $prop = array_flip( $params['prop'] );
93 $this->addFields( LocalFile::selectFields() );
94
95 $ascendingOrder = true;
96 if ( $params['dir'] == 'descending' || $params['dir'] == 'older' ) {
97 $ascendingOrder = false;
98 }
99
100 if ( $params['sort'] == 'name' ) {
101 // Check mutually exclusive params
102 $disallowed = [ 'start', 'end', 'user' ];
103 foreach ( $disallowed as $pname ) {
104 if ( isset( $params[$pname] ) ) {
105 $this->dieWithError(
106 [
107 'apierror-invalidparammix-mustusewith',
108 "{$prefix}{$pname}",
109 "{$prefix}sort=timestamp"
110 ],
111 'invalidparammix'
112 );
113 }
114 }
115 if ( $params['filterbots'] != 'all' ) {
116 $this->dieWithError(
117 [
118 'apierror-invalidparammix-mustusewith',
119 "{$prefix}filterbots",
120 "{$prefix}sort=timestamp"
121 ],
122 'invalidparammix'
123 );
124 }
125
126 // Pagination
127 if ( !is_null( $params['continue'] ) ) {
128 $cont = explode( '|', $params['continue'] );
129 $this->dieContinueUsageIf( count( $cont ) != 1 );
130 $op = ( $ascendingOrder ? '>' : '<' );
131 $continueFrom = $db->addQuotes( $cont[0] );
132 $this->addWhere( "img_name $op= $continueFrom" );
133 }
134
135 // Image filters
136 $from = ( $params['from'] === null ? null : $this->titlePartToKey( $params['from'], NS_FILE ) );
137 $to = ( $params['to'] === null ? null : $this->titlePartToKey( $params['to'], NS_FILE ) );
138 $this->addWhereRange( 'img_name', ( $ascendingOrder ? 'newer' : 'older' ), $from, $to );
139
140 if ( isset( $params['prefix'] ) ) {
141 $this->addWhere( 'img_name' . $db->buildLike(
142 $this->titlePartToKey( $params['prefix'], NS_FILE ),
143 $db->anyString() ) );
144 }
145 } else {
146 // Check mutually exclusive params
147 $disallowed = [ 'from', 'to', 'prefix' ];
148 foreach ( $disallowed as $pname ) {
149 if ( isset( $params[$pname] ) ) {
150 $this->dieWithError(
151 [
152 'apierror-invalidparammix-mustusewith',
153 "{$prefix}{$pname}",
154 "{$prefix}sort=name"
155 ],
156 'invalidparammix'
157 );
158 }
159 }
160 if ( !is_null( $params['user'] ) && $params['filterbots'] != 'all' ) {
161 // Since filterbots checks if each user has the bot right, it
162 // doesn't make sense to use it with user
163 $this->dieWithError(
164 [ 'apierror-invalidparammix-cannotusewith', "{$prefix}user", "{$prefix}filterbots" ]
165 );
166 }
167
168 // Pagination
169 $this->addTimestampWhereRange(
170 'img_timestamp',
171 $ascendingOrder ? 'newer' : 'older',
172 $params['start'],
173 $params['end']
174 );
175 // Include in ORDER BY for uniqueness
176 $this->addWhereRange( 'img_name', $ascendingOrder ? 'newer' : 'older', null, null );
177
178 if ( !is_null( $params['continue'] ) ) {
179 $cont = explode( '|', $params['continue'] );
180 $this->dieContinueUsageIf( count( $cont ) != 2 );
181 $op = ( $ascendingOrder ? '>' : '<' );
182 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
183 $continueName = $db->addQuotes( $cont[1] );
184 $this->addWhere( "img_timestamp $op $continueTimestamp OR " .
185 "(img_timestamp = $continueTimestamp AND " .
186 "img_name $op= $continueName)"
187 );
188 }
189
190 // Image filters
191 if ( !is_null( $params['user'] ) ) {
192 $this->addWhereFld( 'img_user_text', $params['user'] );
193 }
194 if ( $params['filterbots'] != 'all' ) {
195 $this->addTables( 'user_groups' );
196 $this->addJoinConds( [ 'user_groups' => [
197 'LEFT JOIN',
198 [
199 'ug_group' => User::getGroupsWithPermission( 'bot' ),
200 'ug_user = img_user',
201 $this->getConfig()->get( 'DisableUserGroupExpiry' ) ?
202 '1' :
203 'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
204 ]
205 ] ] );
206 $groupCond = ( $params['filterbots'] == 'nobots' ? 'NULL' : 'NOT NULL' );
207 $this->addWhere( "ug_group IS $groupCond" );
208 }
209 }
210
211 // Filters not depending on sort
212 if ( isset( $params['minsize'] ) ) {
213 $this->addWhere( 'img_size>=' . intval( $params['minsize'] ) );
214 }
215
216 if ( isset( $params['maxsize'] ) ) {
217 $this->addWhere( 'img_size<=' . intval( $params['maxsize'] ) );
218 }
219
220 $sha1 = false;
221 if ( isset( $params['sha1'] ) ) {
222 $sha1 = strtolower( $params['sha1'] );
223 if ( !$this->validateSha1Hash( $sha1 ) ) {
224 $this->dieWithError( 'apierror-invalidsha1hash' );
225 }
226 $sha1 = Wikimedia\base_convert( $sha1, 16, 36, 31 );
227 } elseif ( isset( $params['sha1base36'] ) ) {
228 $sha1 = strtolower( $params['sha1base36'] );
229 if ( !$this->validateSha1Base36Hash( $sha1 ) ) {
230 $this->dieWithError( 'apierror-invalidsha1base36hash' );
231 }
232 }
233 if ( $sha1 ) {
234 $this->addWhereFld( 'img_sha1', $sha1 );
235 }
236
237 if ( !is_null( $params['mime'] ) ) {
238 if ( $this->getConfig()->get( 'MiserMode' ) ) {
239 $this->dieWithError( 'apierror-mimesearchdisabled' );
240 }
241
242 $mimeConds = [];
243 foreach ( $params['mime'] as $mime ) {
244 list( $major, $minor ) = File::splitMime( $mime );
245 $mimeConds[] = $db->makeList(
246 [
247 'img_major_mime' => $major,
248 'img_minor_mime' => $minor,
249 ],
250 LIST_AND
251 );
252 }
253 // safeguard against internal_api_error_DBQueryError
254 if ( count( $mimeConds ) > 0 ) {
255 $this->addWhere( $db->makeList( $mimeConds, LIST_OR ) );
256 } else {
257 // no MIME types, no files
258 $this->getResult()->addValue( 'query', $this->getModuleName(), [] );
259 return;
260 }
261 }
262
263 $limit = $params['limit'];
264 $this->addOption( 'LIMIT', $limit + 1 );
265 $sortFlag = '';
266 if ( !$ascendingOrder ) {
267 $sortFlag = ' DESC';
268 }
269 if ( $params['sort'] == 'timestamp' ) {
270 $this->addOption( 'ORDER BY', 'img_timestamp' . $sortFlag );
271 if ( !is_null( $params['user'] ) ) {
272 $this->addOption( 'USE INDEX', [ 'image' => 'img_usertext_timestamp' ] );
273 } else {
274 $this->addOption( 'USE INDEX', [ 'image' => 'img_timestamp' ] );
275 }
276 } else {
277 $this->addOption( 'ORDER BY', 'img_name' . $sortFlag );
278 }
279
280 $res = $this->select( __METHOD__ );
281
282 $titles = [];
283 $count = 0;
284 $result = $this->getResult();
285 foreach ( $res as $row ) {
286 if ( ++$count > $limit ) {
287 // We've reached the one extra which shows that there are
288 // additional pages to be had. Stop here...
289 if ( $params['sort'] == 'name' ) {
290 $this->setContinueEnumParameter( 'continue', $row->img_name );
291 } else {
292 $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
293 }
294 break;
295 }
296
297 if ( is_null( $resultPageSet ) ) {
298 $file = $repo->newFileFromRow( $row );
299 $info = array_merge( [ 'name' => $row->img_name ],
300 ApiQueryImageInfo::getInfo( $file, $prop, $result ) );
301 self::addTitleInfo( $info, $file->getTitle() );
302
303 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $info );
304 if ( !$fit ) {
305 if ( $params['sort'] == 'name' ) {
306 $this->setContinueEnumParameter( 'continue', $row->img_name );
307 } else {
308 $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
309 }
310 break;
311 }
312 } else {
313 $titles[] = Title::makeTitle( NS_FILE, $row->img_name );
314 }
315 }
316
317 if ( is_null( $resultPageSet ) ) {
318 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'img' );
319 } else {
320 $resultPageSet->populateFromTitles( $titles );
321 }
322 }
323
324 public function getAllowedParams() {
325 $ret = [
326 'sort' => [
327 ApiBase::PARAM_DFLT => 'name',
328 ApiBase::PARAM_TYPE => [
329 'name',
330 'timestamp'
331 ]
332 ],
333 'dir' => [
334 ApiBase::PARAM_DFLT => 'ascending',
335 ApiBase::PARAM_TYPE => [
336 // sort=name
337 'ascending',
338 'descending',
339 // sort=timestamp
340 'newer',
341 'older'
342 ]
343 ],
344 'from' => null,
345 'to' => null,
346 'continue' => [
347 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
348 ],
349 'start' => [
350 ApiBase::PARAM_TYPE => 'timestamp'
351 ],
352 'end' => [
353 ApiBase::PARAM_TYPE => 'timestamp'
354 ],
355 'prop' => [
356 ApiBase::PARAM_TYPE => ApiQueryImageInfo::getPropertyNames( $this->propertyFilter ),
357 ApiBase::PARAM_DFLT => 'timestamp|url',
358 ApiBase::PARAM_ISMULTI => true,
359 ApiBase::PARAM_HELP_MSG => 'apihelp-query+imageinfo-param-prop',
360 ApiBase::PARAM_HELP_MSG_PER_VALUE =>
361 ApiQueryImageInfo::getPropertyMessages( $this->propertyFilter ),
362 ],
363 'prefix' => null,
364 'minsize' => [
365 ApiBase::PARAM_TYPE => 'integer',
366 ],
367 'maxsize' => [
368 ApiBase::PARAM_TYPE => 'integer',
369 ],
370 'sha1' => null,
371 'sha1base36' => null,
372 'user' => [
373 ApiBase::PARAM_TYPE => 'user'
374 ],
375 'filterbots' => [
376 ApiBase::PARAM_DFLT => 'all',
377 ApiBase::PARAM_TYPE => [
378 'all',
379 'bots',
380 'nobots'
381 ]
382 ],
383 'mime' => [
384 ApiBase::PARAM_ISMULTI => true,
385 ],
386 'limit' => [
387 ApiBase::PARAM_DFLT => 10,
388 ApiBase::PARAM_TYPE => 'limit',
389 ApiBase::PARAM_MIN => 1,
390 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
391 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
392 ],
393 ];
394
395 if ( $this->getConfig()->get( 'MiserMode' ) ) {
396 $ret['mime'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
397 }
398
399 return $ret;
400 }
401
402 private $propertyFilter = [ 'archivename', 'thumbmime', 'uploadwarning' ];
403
404 protected function getExamplesMessages() {
405 return [
406 'action=query&list=allimages&aifrom=B'
407 => 'apihelp-query+allimages-example-B',
408 'action=query&list=allimages&aiprop=user|timestamp|url&' .
409 'aisort=timestamp&aidir=older'
410 => 'apihelp-query+allimages-example-recent',
411 'action=query&list=allimages&aimime=image/png|image/gif'
412 => 'apihelp-query+allimages-example-mimetypes',
413 'action=query&generator=allimages&gailimit=4&' .
414 'gaifrom=T&prop=imageinfo'
415 => 'apihelp-query+allimages-example-generator',
416 ];
417 }
418
419 public function getHelpUrls() {
420 return 'https://www.mediawiki.org/wiki/API:Allimages';
421 }
422 }