ApiQueryCategoryMembers.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. <?php
  2. /**
  3. *
  4. *
  5. * Created on June 14, 2007
  6. *
  7. * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License along
  20. * with this program; if not, write to the Free Software Foundation, Inc.,
  21. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  22. * http://www.gnu.org/copyleft/gpl.html
  23. *
  24. * @file
  25. */
  26. /**
  27. * A query module to enumerate pages that belong to a category.
  28. *
  29. * @ingroup API
  30. */
  31. class ApiQueryCategoryMembers extends ApiQueryGeneratorBase {
  32. public function __construct( ApiQuery $query, $moduleName ) {
  33. parent::__construct( $query, $moduleName, 'cm' );
  34. }
  35. public function execute() {
  36. $this->run();
  37. }
  38. public function getCacheMode( $params ) {
  39. return 'public';
  40. }
  41. public function executeGenerator( $resultPageSet ) {
  42. $this->run( $resultPageSet );
  43. }
  44. /**
  45. * @param string $hexSortkey
  46. * @return bool
  47. */
  48. private function validateHexSortkey( $hexSortkey ) {
  49. // A hex sortkey has an unbound number of 2 letter pairs
  50. return (bool)preg_match( '/^(?:[a-fA-F0-9]{2})*$/D', $hexSortkey );
  51. }
  52. /**
  53. * @param ApiPageSet $resultPageSet
  54. * @return void
  55. */
  56. private function run( $resultPageSet = null ) {
  57. $params = $this->extractRequestParams();
  58. $categoryTitle = $this->getTitleOrPageId( $params )->getTitle();
  59. if ( $categoryTitle->getNamespace() != NS_CATEGORY ) {
  60. $this->dieWithError( 'apierror-invalidcategory' );
  61. }
  62. $prop = array_flip( $params['prop'] );
  63. $fld_ids = isset( $prop['ids'] );
  64. $fld_title = isset( $prop['title'] );
  65. $fld_sortkey = isset( $prop['sortkey'] );
  66. $fld_sortkeyprefix = isset( $prop['sortkeyprefix'] );
  67. $fld_timestamp = isset( $prop['timestamp'] );
  68. $fld_type = isset( $prop['type'] );
  69. if ( is_null( $resultPageSet ) ) {
  70. $this->addFields( [ 'cl_from', 'cl_sortkey', 'cl_type', 'page_namespace', 'page_title' ] );
  71. $this->addFieldsIf( 'page_id', $fld_ids );
  72. $this->addFieldsIf( 'cl_sortkey_prefix', $fld_sortkeyprefix );
  73. } else {
  74. $this->addFields( $resultPageSet->getPageTableFields() ); // will include page_ id, ns, title
  75. $this->addFields( [ 'cl_from', 'cl_sortkey', 'cl_type' ] );
  76. }
  77. $this->addFieldsIf( 'cl_timestamp', $fld_timestamp || $params['sort'] == 'timestamp' );
  78. $this->addTables( [ 'page', 'categorylinks' ] ); // must be in this order for 'USE INDEX'
  79. $this->addWhereFld( 'cl_to', $categoryTitle->getDBkey() );
  80. $queryTypes = $params['type'];
  81. $contWhere = false;
  82. // Scanning large datasets for rare categories sucks, and I already told
  83. // how to have efficient subcategory access :-) ~~~~ (oh well, domas)
  84. $miser_ns = [];
  85. if ( $this->getConfig()->get( 'MiserMode' ) ) {
  86. $miser_ns = $params['namespace'];
  87. } else {
  88. $this->addWhereFld( 'page_namespace', $params['namespace'] );
  89. }
  90. $dir = in_array( $params['dir'], [ 'asc', 'ascending', 'newer' ] ) ? 'newer' : 'older';
  91. if ( $params['sort'] == 'timestamp' ) {
  92. $this->addTimestampWhereRange( 'cl_timestamp',
  93. $dir,
  94. $params['start'],
  95. $params['end'] );
  96. // Include in ORDER BY for uniqueness
  97. $this->addWhereRange( 'cl_from', $dir, null, null );
  98. if ( !is_null( $params['continue'] ) ) {
  99. $cont = explode( '|', $params['continue'] );
  100. $this->dieContinueUsageIf( count( $cont ) != 2 );
  101. $op = ( $dir === 'newer' ? '>' : '<' );
  102. $db = $this->getDB();
  103. $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
  104. $continueFrom = (int)$cont[1];
  105. $this->dieContinueUsageIf( $continueFrom != $cont[1] );
  106. $this->addWhere( "cl_timestamp $op $continueTimestamp OR " .
  107. "(cl_timestamp = $continueTimestamp AND " .
  108. "cl_from $op= $continueFrom)"
  109. );
  110. }
  111. $this->addOption( 'USE INDEX', 'cl_timestamp' );
  112. } else {
  113. if ( $params['continue'] ) {
  114. $cont = explode( '|', $params['continue'], 3 );
  115. $this->dieContinueUsageIf( count( $cont ) != 3 );
  116. // Remove the types to skip from $queryTypes
  117. $contTypeIndex = array_search( $cont[0], $queryTypes );
  118. $queryTypes = array_slice( $queryTypes, $contTypeIndex );
  119. // Add a WHERE clause for sortkey and from
  120. $this->dieContinueUsageIf( !$this->validateHexSortkey( $cont[1] ) );
  121. $escSortkey = $this->getDB()->addQuotes( hex2bin( $cont[1] ) );
  122. $from = intval( $cont[2] );
  123. $op = $dir == 'newer' ? '>' : '<';
  124. // $contWhere is used further down
  125. $contWhere = "cl_sortkey $op $escSortkey OR " .
  126. "(cl_sortkey = $escSortkey AND " .
  127. "cl_from $op= $from)";
  128. // The below produces ORDER BY cl_sortkey, cl_from, possibly with DESC added to each of them
  129. $this->addWhereRange( 'cl_sortkey', $dir, null, null );
  130. $this->addWhereRange( 'cl_from', $dir, null, null );
  131. } else {
  132. if ( $params['startsortkeyprefix'] !== null ) {
  133. $startsortkey = Collation::singleton()->getSortKey( $params['startsortkeyprefix'] );
  134. } elseif ( $params['starthexsortkey'] !== null ) {
  135. if ( !$this->validateHexSortkey( $params['starthexsortkey'] ) ) {
  136. $encParamName = $this->encodeParamName( 'starthexsortkey' );
  137. $this->dieWithError( [ 'apierror-badparameter', $encParamName ], "badvalue_$encParamName" );
  138. }
  139. $startsortkey = hex2bin( $params['starthexsortkey'] );
  140. } else {
  141. $startsortkey = $params['startsortkey'];
  142. }
  143. if ( $params['endsortkeyprefix'] !== null ) {
  144. $endsortkey = Collation::singleton()->getSortKey( $params['endsortkeyprefix'] );
  145. } elseif ( $params['endhexsortkey'] !== null ) {
  146. if ( !$this->validateHexSortkey( $params['endhexsortkey'] ) ) {
  147. $encParamName = $this->encodeParamName( 'endhexsortkey' );
  148. $this->dieWithError( [ 'apierror-badparameter', $encParamName ], "badvalue_$encParamName" );
  149. }
  150. $endsortkey = hex2bin( $params['endhexsortkey'] );
  151. } else {
  152. $endsortkey = $params['endsortkey'];
  153. }
  154. // The below produces ORDER BY cl_sortkey, cl_from, possibly with DESC added to each of them
  155. $this->addWhereRange( 'cl_sortkey',
  156. $dir,
  157. $startsortkey,
  158. $endsortkey );
  159. $this->addWhereRange( 'cl_from', $dir, null, null );
  160. }
  161. $this->addOption( 'USE INDEX', 'cl_sortkey' );
  162. }
  163. $this->addWhere( 'cl_from=page_id' );
  164. $limit = $params['limit'];
  165. $this->addOption( 'LIMIT', $limit + 1 );
  166. if ( $params['sort'] == 'sortkey' ) {
  167. // Run a separate SELECT query for each value of cl_type.
  168. // This is needed because cl_type is an enum, and MySQL has
  169. // inconsistencies between ORDER BY cl_type and
  170. // WHERE cl_type >= 'foo' making proper paging impossible
  171. // and unindexed.
  172. $rows = [];
  173. $first = true;
  174. foreach ( $queryTypes as $type ) {
  175. $extraConds = [ 'cl_type' => $type ];
  176. if ( $first && $contWhere ) {
  177. // Continuation condition. Only added to the
  178. // first query, otherwise we'll skip things
  179. $extraConds[] = $contWhere;
  180. }
  181. $res = $this->select( __METHOD__, [ 'where' => $extraConds ] );
  182. $rows = array_merge( $rows, iterator_to_array( $res ) );
  183. if ( count( $rows ) >= $limit + 1 ) {
  184. break;
  185. }
  186. $first = false;
  187. }
  188. } else {
  189. // Sorting by timestamp
  190. // No need to worry about per-type queries because we
  191. // aren't sorting or filtering by type anyway
  192. $res = $this->select( __METHOD__ );
  193. $rows = iterator_to_array( $res );
  194. }
  195. $result = $this->getResult();
  196. $count = 0;
  197. foreach ( $rows as $row ) {
  198. if ( ++$count > $limit ) {
  199. // We've reached the one extra which shows that there are
  200. // additional pages to be had. Stop here...
  201. // @todo Security issue - if the user has no right to view next
  202. // title, it will still be shown
  203. if ( $params['sort'] == 'timestamp' ) {
  204. $this->setContinueEnumParameter( 'continue', "$row->cl_timestamp|$row->cl_from" );
  205. } else {
  206. $sortkey = bin2hex( $row->cl_sortkey );
  207. $this->setContinueEnumParameter( 'continue',
  208. "{$row->cl_type}|$sortkey|{$row->cl_from}"
  209. );
  210. }
  211. break;
  212. }
  213. // Since domas won't tell anyone what he told long ago, apply
  214. // cmnamespace here. This means the query may return 0 actual
  215. // results, but on the other hand it could save returning 5000
  216. // useless results to the client. ~~~~
  217. if ( count( $miser_ns ) && !in_array( $row->page_namespace, $miser_ns ) ) {
  218. continue;
  219. }
  220. if ( is_null( $resultPageSet ) ) {
  221. $vals = [
  222. ApiResult::META_TYPE => 'assoc',
  223. ];
  224. if ( $fld_ids ) {
  225. $vals['pageid'] = intval( $row->page_id );
  226. }
  227. if ( $fld_title ) {
  228. $title = Title::makeTitle( $row->page_namespace, $row->page_title );
  229. ApiQueryBase::addTitleInfo( $vals, $title );
  230. }
  231. if ( $fld_sortkey ) {
  232. $vals['sortkey'] = bin2hex( $row->cl_sortkey );
  233. }
  234. if ( $fld_sortkeyprefix ) {
  235. $vals['sortkeyprefix'] = $row->cl_sortkey_prefix;
  236. }
  237. if ( $fld_type ) {
  238. $vals['type'] = $row->cl_type;
  239. }
  240. if ( $fld_timestamp ) {
  241. $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->cl_timestamp );
  242. }
  243. $fit = $result->addValue( [ 'query', $this->getModuleName() ],
  244. null, $vals );
  245. if ( !$fit ) {
  246. if ( $params['sort'] == 'timestamp' ) {
  247. $this->setContinueEnumParameter( 'continue', "$row->cl_timestamp|$row->cl_from" );
  248. } else {
  249. $sortkey = bin2hex( $row->cl_sortkey );
  250. $this->setContinueEnumParameter( 'continue',
  251. "{$row->cl_type}|$sortkey|{$row->cl_from}"
  252. );
  253. }
  254. break;
  255. }
  256. } else {
  257. $resultPageSet->processDbRow( $row );
  258. }
  259. }
  260. if ( is_null( $resultPageSet ) ) {
  261. $result->addIndexedTagName(
  262. [ 'query', $this->getModuleName() ], 'cm' );
  263. }
  264. }
  265. public function getAllowedParams() {
  266. $ret = [
  267. 'title' => [
  268. ApiBase::PARAM_TYPE => 'string',
  269. ],
  270. 'pageid' => [
  271. ApiBase::PARAM_TYPE => 'integer'
  272. ],
  273. 'prop' => [
  274. ApiBase::PARAM_DFLT => 'ids|title',
  275. ApiBase::PARAM_ISMULTI => true,
  276. ApiBase::PARAM_TYPE => [
  277. 'ids',
  278. 'title',
  279. 'sortkey',
  280. 'sortkeyprefix',
  281. 'type',
  282. 'timestamp',
  283. ],
  284. ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
  285. ],
  286. 'namespace' => [
  287. ApiBase::PARAM_ISMULTI => true,
  288. ApiBase::PARAM_TYPE => 'namespace',
  289. ],
  290. 'type' => [
  291. ApiBase::PARAM_ISMULTI => true,
  292. ApiBase::PARAM_DFLT => 'page|subcat|file',
  293. ApiBase::PARAM_TYPE => [
  294. 'page',
  295. 'subcat',
  296. 'file'
  297. ]
  298. ],
  299. 'continue' => [
  300. ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
  301. ],
  302. 'limit' => [
  303. ApiBase::PARAM_TYPE => 'limit',
  304. ApiBase::PARAM_DFLT => 10,
  305. ApiBase::PARAM_MIN => 1,
  306. ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
  307. ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
  308. ],
  309. 'sort' => [
  310. ApiBase::PARAM_DFLT => 'sortkey',
  311. ApiBase::PARAM_TYPE => [
  312. 'sortkey',
  313. 'timestamp'
  314. ]
  315. ],
  316. 'dir' => [
  317. ApiBase::PARAM_DFLT => 'ascending',
  318. ApiBase::PARAM_TYPE => [
  319. 'asc',
  320. 'desc',
  321. // Normalising with other modules
  322. 'ascending',
  323. 'descending',
  324. 'newer',
  325. 'older',
  326. ]
  327. ],
  328. 'start' => [
  329. ApiBase::PARAM_TYPE => 'timestamp'
  330. ],
  331. 'end' => [
  332. ApiBase::PARAM_TYPE => 'timestamp'
  333. ],
  334. 'starthexsortkey' => null,
  335. 'endhexsortkey' => null,
  336. 'startsortkeyprefix' => null,
  337. 'endsortkeyprefix' => null,
  338. 'startsortkey' => [
  339. ApiBase::PARAM_DEPRECATED => true,
  340. ],
  341. 'endsortkey' => [
  342. ApiBase::PARAM_DEPRECATED => true,
  343. ],
  344. ];
  345. if ( $this->getConfig()->get( 'MiserMode' ) ) {
  346. $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
  347. 'api-help-param-limited-in-miser-mode',
  348. ];
  349. }
  350. return $ret;
  351. }
  352. protected function getExamplesMessages() {
  353. return [
  354. 'action=query&list=categorymembers&cmtitle=Category:Physics'
  355. => 'apihelp-query+categorymembers-example-simple',
  356. 'action=query&generator=categorymembers&gcmtitle=Category:Physics&prop=info'
  357. => 'apihelp-query+categorymembers-example-generator',
  358. ];
  359. }
  360. public function getHelpUrls() {
  361. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Categorymembers';
  362. }
  363. }