ApiQueryAllImages.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. /**
  3. * API for MediaWiki 1.12+
  4. *
  5. * Copyright © 2008 Vasiliev Victor vasilvv@gmail.com,
  6. * based on ApiQueryAllPages.php
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. * http://www.gnu.org/copyleft/gpl.html
  22. *
  23. * @file
  24. */
  25. use Wikimedia\Rdbms\IDatabase;
  26. /**
  27. * Query module to enumerate all available pages.
  28. *
  29. * @ingroup API
  30. */
  31. class ApiQueryAllImages extends ApiQueryGeneratorBase {
  32. protected $mRepo;
  33. public function __construct( ApiQuery $query, $moduleName ) {
  34. parent::__construct( $query, $moduleName, 'ai' );
  35. $this->mRepo = RepoGroup::singleton()->getLocalRepo();
  36. }
  37. /**
  38. * Override parent method to make sure the repo's DB is used
  39. * which may not necessarily be the same as the local DB.
  40. *
  41. * TODO: allow querying non-local repos.
  42. * @return IDatabase
  43. */
  44. protected function getDB() {
  45. return $this->mRepo->getReplicaDB();
  46. }
  47. public function execute() {
  48. $this->run();
  49. }
  50. public function getCacheMode( $params ) {
  51. return 'public';
  52. }
  53. /**
  54. * @param ApiPageSet $resultPageSet
  55. * @return void
  56. */
  57. public function executeGenerator( $resultPageSet ) {
  58. if ( $resultPageSet->isResolvingRedirects() ) {
  59. $this->dieWithError( 'apierror-allimages-redirect', 'invalidparammix' );
  60. }
  61. $this->run( $resultPageSet );
  62. }
  63. /**
  64. * @param ApiPageSet $resultPageSet
  65. * @return void
  66. */
  67. private function run( $resultPageSet = null ) {
  68. $repo = $this->mRepo;
  69. if ( !$repo instanceof LocalRepo ) {
  70. $this->dieWithError( 'apierror-unsupportedrepo' );
  71. }
  72. $prefix = $this->getModulePrefix();
  73. $db = $this->getDB();
  74. $params = $this->extractRequestParams();
  75. // Table and return fields
  76. $prop = array_flip( $params['prop'] );
  77. $fileQuery = LocalFile::getQueryInfo();
  78. $this->addTables( $fileQuery['tables'] );
  79. $this->addFields( $fileQuery['fields'] );
  80. $this->addJoinConds( $fileQuery['joins'] );
  81. $ascendingOrder = true;
  82. if ( $params['dir'] == 'descending' || $params['dir'] == 'older' ) {
  83. $ascendingOrder = false;
  84. }
  85. if ( $params['sort'] == 'name' ) {
  86. // Check mutually exclusive params
  87. $disallowed = [ 'start', 'end', 'user' ];
  88. foreach ( $disallowed as $pname ) {
  89. if ( isset( $params[$pname] ) ) {
  90. $this->dieWithError(
  91. [
  92. 'apierror-invalidparammix-mustusewith',
  93. "{$prefix}{$pname}",
  94. "{$prefix}sort=timestamp"
  95. ],
  96. 'invalidparammix'
  97. );
  98. }
  99. }
  100. if ( $params['filterbots'] != 'all' ) {
  101. $this->dieWithError(
  102. [
  103. 'apierror-invalidparammix-mustusewith',
  104. "{$prefix}filterbots",
  105. "{$prefix}sort=timestamp"
  106. ],
  107. 'invalidparammix'
  108. );
  109. }
  110. // Pagination
  111. if ( !is_null( $params['continue'] ) ) {
  112. $cont = explode( '|', $params['continue'] );
  113. $this->dieContinueUsageIf( count( $cont ) != 1 );
  114. $op = $ascendingOrder ? '>' : '<';
  115. $continueFrom = $db->addQuotes( $cont[0] );
  116. $this->addWhere( "img_name $op= $continueFrom" );
  117. }
  118. // Image filters
  119. $from = $params['from'] === null ? null : $this->titlePartToKey( $params['from'], NS_FILE );
  120. $to = $params['to'] === null ? null : $this->titlePartToKey( $params['to'], NS_FILE );
  121. $this->addWhereRange( 'img_name', $ascendingOrder ? 'newer' : 'older', $from, $to );
  122. if ( isset( $params['prefix'] ) ) {
  123. $this->addWhere( 'img_name' . $db->buildLike(
  124. $this->titlePartToKey( $params['prefix'], NS_FILE ),
  125. $db->anyString() ) );
  126. }
  127. } else {
  128. // Check mutually exclusive params
  129. $disallowed = [ 'from', 'to', 'prefix' ];
  130. foreach ( $disallowed as $pname ) {
  131. if ( isset( $params[$pname] ) ) {
  132. $this->dieWithError(
  133. [
  134. 'apierror-invalidparammix-mustusewith',
  135. "{$prefix}{$pname}",
  136. "{$prefix}sort=name"
  137. ],
  138. 'invalidparammix'
  139. );
  140. }
  141. }
  142. if ( !is_null( $params['user'] ) && $params['filterbots'] != 'all' ) {
  143. // Since filterbots checks if each user has the bot right, it
  144. // doesn't make sense to use it with user
  145. $this->dieWithError(
  146. [ 'apierror-invalidparammix-cannotusewith', "{$prefix}user", "{$prefix}filterbots" ]
  147. );
  148. }
  149. // Pagination
  150. $this->addTimestampWhereRange(
  151. 'img_timestamp',
  152. $ascendingOrder ? 'newer' : 'older',
  153. $params['start'],
  154. $params['end']
  155. );
  156. // Include in ORDER BY for uniqueness
  157. $this->addWhereRange( 'img_name', $ascendingOrder ? 'newer' : 'older', null, null );
  158. if ( !is_null( $params['continue'] ) ) {
  159. $cont = explode( '|', $params['continue'] );
  160. $this->dieContinueUsageIf( count( $cont ) != 2 );
  161. $op = ( $ascendingOrder ? '>' : '<' );
  162. $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
  163. $continueName = $db->addQuotes( $cont[1] );
  164. $this->addWhere( "img_timestamp $op $continueTimestamp OR " .
  165. "(img_timestamp = $continueTimestamp AND " .
  166. "img_name $op= $continueName)"
  167. );
  168. }
  169. // Image filters
  170. if ( !is_null( $params['user'] ) ) {
  171. $actorQuery = ActorMigration::newMigration()
  172. ->getWhere( $db, 'img_user', User::newFromName( $params['user'], false ) );
  173. $this->addTables( $actorQuery['tables'] );
  174. $this->addJoinConds( $actorQuery['joins'] );
  175. $this->addWhere( $actorQuery['conds'] );
  176. }
  177. if ( $params['filterbots'] != 'all' ) {
  178. $actorQuery = ActorMigration::newMigration()->getJoin( 'img_user' );
  179. $this->addTables( $actorQuery['tables'] );
  180. $this->addTables( 'user_groups' );
  181. $this->addJoinConds( $actorQuery['joins'] );
  182. $this->addJoinConds( [ 'user_groups' => [
  183. 'LEFT JOIN',
  184. [
  185. 'ug_group' => $this->getPermissionManager()->getGroupsWithPermission( 'bot' ),
  186. 'ug_user = ' . $actorQuery['fields']['img_user'],
  187. 'ug_expiry IS NULL OR ug_expiry >= ' . $db->addQuotes( $db->timestamp() )
  188. ]
  189. ] ] );
  190. $groupCond = $params['filterbots'] == 'nobots' ? 'NULL' : 'NOT NULL';
  191. $this->addWhere( "ug_group IS $groupCond" );
  192. }
  193. }
  194. // Filters not depending on sort
  195. if ( isset( $params['minsize'] ) ) {
  196. $this->addWhere( 'img_size>=' . (int)$params['minsize'] );
  197. }
  198. if ( isset( $params['maxsize'] ) ) {
  199. $this->addWhere( 'img_size<=' . (int)$params['maxsize'] );
  200. }
  201. $sha1 = false;
  202. if ( isset( $params['sha1'] ) ) {
  203. $sha1 = strtolower( $params['sha1'] );
  204. if ( !$this->validateSha1Hash( $sha1 ) ) {
  205. $this->dieWithError( 'apierror-invalidsha1hash' );
  206. }
  207. $sha1 = Wikimedia\base_convert( $sha1, 16, 36, 31 );
  208. } elseif ( isset( $params['sha1base36'] ) ) {
  209. $sha1 = strtolower( $params['sha1base36'] );
  210. if ( !$this->validateSha1Base36Hash( $sha1 ) ) {
  211. $this->dieWithError( 'apierror-invalidsha1base36hash' );
  212. }
  213. }
  214. if ( $sha1 ) {
  215. $this->addWhereFld( 'img_sha1', $sha1 );
  216. }
  217. if ( !is_null( $params['mime'] ) ) {
  218. if ( $this->getConfig()->get( 'MiserMode' ) ) {
  219. $this->dieWithError( 'apierror-mimesearchdisabled' );
  220. }
  221. $mimeConds = [];
  222. foreach ( $params['mime'] as $mime ) {
  223. list( $major, $minor ) = File::splitMime( $mime );
  224. $mimeConds[] = $db->makeList(
  225. [
  226. 'img_major_mime' => $major,
  227. 'img_minor_mime' => $minor,
  228. ],
  229. LIST_AND
  230. );
  231. }
  232. // safeguard against internal_api_error_DBQueryError
  233. if ( count( $mimeConds ) > 0 ) {
  234. $this->addWhere( $db->makeList( $mimeConds, LIST_OR ) );
  235. } else {
  236. // no MIME types, no files
  237. $this->getResult()->addValue( 'query', $this->getModuleName(), [] );
  238. return;
  239. }
  240. }
  241. $limit = $params['limit'];
  242. $this->addOption( 'LIMIT', $limit + 1 );
  243. $sortFlag = '';
  244. if ( !$ascendingOrder ) {
  245. $sortFlag = ' DESC';
  246. }
  247. if ( $params['sort'] == 'timestamp' ) {
  248. $this->addOption( 'ORDER BY', 'img_timestamp' . $sortFlag );
  249. } else {
  250. $this->addOption( 'ORDER BY', 'img_name' . $sortFlag );
  251. }
  252. $res = $this->select( __METHOD__ );
  253. $titles = [];
  254. $count = 0;
  255. $result = $this->getResult();
  256. foreach ( $res as $row ) {
  257. if ( ++$count > $limit ) {
  258. // We've reached the one extra which shows that there are
  259. // additional pages to be had. Stop here...
  260. if ( $params['sort'] == 'name' ) {
  261. $this->setContinueEnumParameter( 'continue', $row->img_name );
  262. } else {
  263. $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
  264. }
  265. break;
  266. }
  267. if ( is_null( $resultPageSet ) ) {
  268. $file = $repo->newFileFromRow( $row );
  269. $info = array_merge( [ 'name' => $row->img_name ],
  270. ApiQueryImageInfo::getInfo( $file, $prop, $result ) );
  271. self::addTitleInfo( $info, $file->getTitle() );
  272. $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $info );
  273. if ( !$fit ) {
  274. if ( $params['sort'] == 'name' ) {
  275. $this->setContinueEnumParameter( 'continue', $row->img_name );
  276. } else {
  277. $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
  278. }
  279. break;
  280. }
  281. } else {
  282. $titles[] = Title::makeTitle( NS_FILE, $row->img_name );
  283. }
  284. }
  285. if ( is_null( $resultPageSet ) ) {
  286. $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'img' );
  287. } else {
  288. $resultPageSet->populateFromTitles( $titles );
  289. }
  290. }
  291. public function getAllowedParams() {
  292. $ret = [
  293. 'sort' => [
  294. ApiBase::PARAM_DFLT => 'name',
  295. ApiBase::PARAM_TYPE => [
  296. 'name',
  297. 'timestamp'
  298. ]
  299. ],
  300. 'dir' => [
  301. ApiBase::PARAM_DFLT => 'ascending',
  302. ApiBase::PARAM_TYPE => [
  303. // sort=name
  304. 'ascending',
  305. 'descending',
  306. // sort=timestamp
  307. 'newer',
  308. 'older'
  309. ]
  310. ],
  311. 'from' => null,
  312. 'to' => null,
  313. 'continue' => [
  314. ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
  315. ],
  316. 'start' => [
  317. ApiBase::PARAM_TYPE => 'timestamp'
  318. ],
  319. 'end' => [
  320. ApiBase::PARAM_TYPE => 'timestamp'
  321. ],
  322. 'prop' => [
  323. ApiBase::PARAM_TYPE => ApiQueryImageInfo::getPropertyNames( $this->propertyFilter ),
  324. ApiBase::PARAM_DFLT => 'timestamp|url',
  325. ApiBase::PARAM_ISMULTI => true,
  326. ApiBase::PARAM_HELP_MSG => 'apihelp-query+imageinfo-param-prop',
  327. ApiBase::PARAM_HELP_MSG_PER_VALUE =>
  328. ApiQueryImageInfo::getPropertyMessages( $this->propertyFilter ),
  329. ],
  330. 'prefix' => null,
  331. 'minsize' => [
  332. ApiBase::PARAM_TYPE => 'integer',
  333. ],
  334. 'maxsize' => [
  335. ApiBase::PARAM_TYPE => 'integer',
  336. ],
  337. 'sha1' => null,
  338. 'sha1base36' => null,
  339. 'user' => [
  340. ApiBase::PARAM_TYPE => 'user'
  341. ],
  342. 'filterbots' => [
  343. ApiBase::PARAM_DFLT => 'all',
  344. ApiBase::PARAM_TYPE => [
  345. 'all',
  346. 'bots',
  347. 'nobots'
  348. ]
  349. ],
  350. 'mime' => [
  351. ApiBase::PARAM_ISMULTI => true,
  352. ],
  353. 'limit' => [
  354. ApiBase::PARAM_DFLT => 10,
  355. ApiBase::PARAM_TYPE => 'limit',
  356. ApiBase::PARAM_MIN => 1,
  357. ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
  358. ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
  359. ],
  360. ];
  361. if ( $this->getConfig()->get( 'MiserMode' ) ) {
  362. $ret['mime'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
  363. }
  364. return $ret;
  365. }
  366. private $propertyFilter = [ 'archivename', 'thumbmime', 'uploadwarning' ];
  367. protected function getExamplesMessages() {
  368. return [
  369. 'action=query&list=allimages&aifrom=B'
  370. => 'apihelp-query+allimages-example-b',
  371. 'action=query&list=allimages&aiprop=user|timestamp|url&' .
  372. 'aisort=timestamp&aidir=older'
  373. => 'apihelp-query+allimages-example-recent',
  374. 'action=query&list=allimages&aimime=image/png|image/gif'
  375. => 'apihelp-query+allimages-example-mimetypes',
  376. 'action=query&generator=allimages&gailimit=4&' .
  377. 'gaifrom=T&prop=imageinfo'
  378. => 'apihelp-query+allimages-example-generator',
  379. ];
  380. }
  381. public function getHelpUrls() {
  382. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allimages';
  383. }
  384. }