MediaWiki master
ApiQueryCategories.php
Go to the documentation of this file.
1<?php
23namespace MediaWiki\Api;
24
29
36
37 private int $migrationStage;
38
39 public function __construct( ApiQuery $query, string $moduleName ) {
40 parent::__construct( $query, $moduleName, 'cl' );
41 $this->migrationStage = $query->getConfig()->get(
43 );
44 }
45
46 public function execute() {
47 $this->run();
48 }
49
50 public function getCacheMode( $params ) {
51 return 'public';
52 }
53
54 public function executeGenerator( $resultPageSet ) {
55 $this->run( $resultPageSet );
56 }
57
61 private function run( $resultPageSet = null ) {
62 $pages = $this->getPageSet()->getGoodPages();
63 if ( $pages === [] ) {
64 return; // nothing to do
65 }
66
67 $params = $this->extractRequestParams();
68 $prop = array_fill_keys( (array)$params['prop'], true );
69 $show = array_fill_keys( (array)$params['show'], true );
70
71 $this->addFieldsIf( [ 'cl_sortkey', 'cl_sortkey_prefix' ], isset( $prop['sortkey'] ) );
72 $this->addFieldsIf( 'cl_timestamp', isset( $prop['timestamp'] ) );
73
74 $this->addTables( 'categorylinks' );
75 if ( $this->migrationStage & SCHEMA_COMPAT_READ_OLD ) {
76 $titleField = 'cl_to';
77 } else {
78 $this->addTables( 'linktarget' );
79 $this->addJoinConds( [ 'linktarget' => [ 'JOIN', 'cl_target_id = lt_id ' ] ] );
80 $this->addWhere( [ 'lt_namespace' => NS_CATEGORY ] );
81 $titleField = 'lt_title';
82 }
83 $this->addFields( [
84 'cl_from',
85 $titleField
86 ] );
87 $this->addWhereFld( 'cl_from', array_keys( $pages ) );
88 if ( $params['categories'] ) {
89 $cats = [];
90 foreach ( $params['categories'] as $cat ) {
91 $title = Title::newFromText( $cat );
92 if ( !$title || $title->getNamespace() !== NS_CATEGORY ) {
93 $this->addWarning( [ 'apiwarn-invalidcategory', wfEscapeWikiText( $cat ) ] );
94 } else {
95 $cats[] = $title->getDBkey();
96 }
97 }
98 if ( !$cats ) {
99 // No titles so no results
100 return;
101 }
102 $this->addWhereFld( $titleField, $cats );
103 }
104
105 if ( $params['continue'] !== null ) {
106 $db = $this->getDB();
107 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'string' ] );
108 $op = $params['dir'] == 'descending' ? '<=' : '>=';
109 $this->addWhere( $db->buildComparison( $op, [
110 'cl_from' => $cont[0],
111 $titleField => $cont[1],
112 ] ) );
113 }
114
115 if ( isset( $show['hidden'] ) && isset( $show['!hidden'] ) ) {
116 $this->dieWithError( 'apierror-show' );
117 }
118 if ( isset( $show['hidden'] ) || isset( $show['!hidden'] ) || isset( $prop['hidden'] ) ) {
119 $this->addOption( 'STRAIGHT_JOIN' );
120 $this->addTables( [ 'page', 'page_props' ] );
121 $this->addFieldsIf( 'pp_propname', isset( $prop['hidden'] ) );
122 $this->addJoinConds( [
123 'page' => [ 'LEFT JOIN', [
124 'page_namespace' => NS_CATEGORY,
125 'page_title = ' . $titleField ] ],
126 'page_props' => [ 'LEFT JOIN', [
127 'pp_page=page_id',
128 'pp_propname' => 'hiddencat' ] ]
129 ] );
130 if ( isset( $show['hidden'] ) ) {
131 $this->addWhere( $this->getDB()->expr( 'pp_propname', '!=', null ) );
132 } elseif ( isset( $show['!hidden'] ) ) {
133 $this->addWhere( [ 'pp_propname' => null ] );
134 }
135 }
136
137 $sort = ( $params['dir'] == 'descending' ? ' DESC' : '' );
138 // Don't order by cl_from if it's constant in the WHERE clause
139 if ( count( $pages ) === 1 ) {
140 $this->addOption( 'ORDER BY', $titleField . $sort );
141 } else {
142 $this->addOption( 'ORDER BY', [
143 'cl_from' . $sort,
144 $titleField . $sort
145 ] );
146 }
147 $this->addOption( 'LIMIT', $params['limit'] + 1 );
148
149 $res = $this->select( __METHOD__ );
150
151 $count = 0;
152 if ( $resultPageSet === null ) {
153 foreach ( $res as $row ) {
154 if ( ++$count > $params['limit'] ) {
155 // We've reached the one extra which shows that
156 // there are additional pages to be had. Stop here...
157 $this->setContinueEnumParameter( 'continue', $row->cl_from . '|' . $row->$titleField );
158 break;
159 }
160
161 $title = Title::makeTitle( NS_CATEGORY, $row->$titleField );
162 $vals = [];
163 ApiQueryBase::addTitleInfo( $vals, $title );
164 if ( isset( $prop['sortkey'] ) ) {
165 $vals['sortkey'] = bin2hex( $row->cl_sortkey );
166 $vals['sortkeyprefix'] = $row->cl_sortkey_prefix;
167 }
168 if ( isset( $prop['timestamp'] ) ) {
169 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $row->cl_timestamp );
170 }
171 if ( isset( $prop['hidden'] ) ) {
172 $vals['hidden'] = $row->pp_propname !== null;
173 }
174
175 $fit = $this->addPageSubItem( $row->cl_from, $vals );
176 if ( !$fit ) {
177 $this->setContinueEnumParameter( 'continue', $row->cl_from . '|' . $row->$titleField );
178 break;
179 }
180 }
181 } else {
182 $titles = [];
183 foreach ( $res as $row ) {
184 if ( ++$count > $params['limit'] ) {
185 // We've reached the one extra which shows that
186 // there are additional pages to be had. Stop here...
187 $this->setContinueEnumParameter( 'continue', $row->cl_from . '|' . $row->$titleField );
188 break;
189 }
190
191 $titles[] = Title::makeTitle( NS_CATEGORY, $row->$titleField );
192 }
193 $resultPageSet->populateFromTitles( $titles );
194 }
195 }
196
197 public function getAllowedParams() {
198 return [
199 'prop' => [
200 ParamValidator::PARAM_ISMULTI => true,
201 ParamValidator::PARAM_TYPE => [
202 'sortkey',
203 'timestamp',
204 'hidden',
205 ],
207 ],
208 'show' => [
209 ParamValidator::PARAM_ISMULTI => true,
210 ParamValidator::PARAM_TYPE => [
211 'hidden',
212 '!hidden',
213 ]
214 ],
215 'limit' => [
216 ParamValidator::PARAM_DEFAULT => 10,
217 ParamValidator::PARAM_TYPE => 'limit',
218 IntegerDef::PARAM_MIN => 1,
219 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
220 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
221 ],
222 'continue' => [
223 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
224 ],
225 'categories' => [
226 ParamValidator::PARAM_ISMULTI => true,
227 ],
228 'dir' => [
229 ParamValidator::PARAM_DEFAULT => 'ascending',
230 ParamValidator::PARAM_TYPE => [
231 'ascending',
232 'descending'
233 ]
234 ],
235 ];
236 }
237
238 protected function getExamplesMessages() {
239 return [
240 'action=query&prop=categories&titles=Albert%20Einstein'
241 => 'apihelp-query+categories-example-simple',
242 'action=query&generator=categories&titles=Albert%20Einstein&prop=info'
243 => 'apihelp-query+categories-example-generator',
244 ];
245 }
246
247 public function getHelpUrls() {
248 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Categories';
249 }
250}
251
253class_alias( ApiQueryCategories::class, 'ApiQueryCategories' );
const SCHEMA_COMPAT_READ_OLD
Definition Defines.php:304
const NS_CATEGORY
Definition Defines.php:79
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1522
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1707
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:221
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1440
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:181
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:248
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:837
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:246
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
addPageSubItem( $pageId, $item, $elemname=null)
Same as addPageSubItems(), but one element of $data at a time.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
getDB()
Get the Query database connection (read-only)
select( $method, $extraQuery=[], ?array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addFields( $value)
Add a set of fields to select to the internal array.
A query module to enumerate categories the set of pages belong to.
getHelpUrls()
Return links to more detailed help pages about the module.
executeGenerator( $resultPageSet)
Execute this module as a generator.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getExamplesMessages()
Returns usage examples for this module.
__construct(ApiQuery $query, string $moduleName)
getCacheMode( $params)
Get the cache mode for the data generated by this module.
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
getPageSet()
Get the PageSet object to work on.
This is the main query class.
Definition ApiQuery.php:50
A class containing constants representing the names of configuration variables.
const CategoryLinksSchemaMigrationStage
Name constant for the CategoryLinksSchemaMigrationStage setting, for use with Config::get()
Represents a title within MediaWiki.
Definition Title.php:78
Service for formatting and validating API parameters.
Type definition for integer types.
array $params
The job parameters.