ApiQueryCategoryMembers.php 12 KB

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