MediaWiki master
ApiQueryCategories.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Api;
10
14use Wikimedia\Timestamp\TimestampFormat as TS;
15
22
23 public function __construct( ApiQuery $query, string $moduleName ) {
24 parent::__construct( $query, $moduleName, 'cl' );
25 }
26
27 public function execute() {
28 $this->run();
29 }
30
32 public function getCacheMode( $params ) {
33 return 'public';
34 }
35
37 public function executeGenerator( $resultPageSet ) {
38 $this->run( $resultPageSet );
39 }
40
44 private function run( $resultPageSet = null ) {
45 $pages = $this->getPageSet()->getGoodPages();
46 if ( $pages === [] ) {
47 return; // nothing to do
48 }
49
50 $params = $this->extractRequestParams();
51 $prop = array_fill_keys( (array)$params['prop'], true );
52 $show = array_fill_keys( (array)$params['show'], true );
53
54 $this->addFields( [ 'cl_from', 'lt_title' ] );
55 $this->addFieldsIf( [ 'cl_sortkey', 'cl_sortkey_prefix' ], isset( $prop['sortkey'] ) );
56 $this->addFieldsIf( 'cl_timestamp', isset( $prop['timestamp'] ) );
57
58 $this->addTables( 'categorylinks' );
59 $this->addTables( 'linktarget' );
60 $this->addJoinConds( [ 'linktarget' => [ 'JOIN', 'cl_target_id = lt_id ' ] ] );
61 $this->addWhere( [ 'lt_namespace' => NS_CATEGORY ] );
62 $this->addWhereFld( 'cl_from', array_keys( $pages ) );
63
64 if ( $params['categories'] ) {
65 $cats = [];
66 foreach ( $params['categories'] as $cat ) {
67 $title = Title::newFromText( $cat );
68 if ( !$title || $title->getNamespace() !== NS_CATEGORY ) {
69 $this->addWarning( [ 'apiwarn-invalidcategory', wfEscapeWikiText( $cat ) ] );
70 } else {
71 $cats[] = $title->getDBkey();
72 }
73 }
74 if ( !$cats ) {
75 // No titles so no results
76 return;
77 }
78 $this->addWhereFld( 'lt_title', $cats );
79 }
80
81 if ( $params['continue'] !== null ) {
82 $db = $this->getDB();
83 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'int', 'string' ] );
84 $op = $params['dir'] == 'descending' ? '<=' : '>=';
85 $this->addWhere( $db->buildComparison( $op, [
86 'cl_from' => $cont[0],
87 'lt_title' => $cont[1],
88 ] ) );
89 }
90
91 if ( isset( $show['hidden'] ) && isset( $show['!hidden'] ) ) {
92 $this->dieWithError( 'apierror-show' );
93 }
94 if ( isset( $show['hidden'] ) || isset( $show['!hidden'] ) || isset( $prop['hidden'] ) ) {
95 $this->addOption( 'STRAIGHT_JOIN' );
96 $this->addTables( [ 'page', 'page_props' ] );
97 $this->addFieldsIf( 'pp_propname', isset( $prop['hidden'] ) );
98 $this->addJoinConds( [
99 'page' => [ 'LEFT JOIN', [
100 'page_namespace' => NS_CATEGORY,
101 'page_title = lt_title' ] ],
102 'page_props' => [ 'LEFT JOIN', [
103 'pp_page=page_id',
104 'pp_propname' => 'hiddencat' ] ]
105 ] );
106 if ( isset( $show['hidden'] ) ) {
107 $this->addWhere( $this->getDB()->expr( 'pp_propname', '!=', null ) );
108 } elseif ( isset( $show['!hidden'] ) ) {
109 $this->addWhere( [ 'pp_propname' => null ] );
110 }
111 }
112
113 $sort = ( $params['dir'] == 'descending' ? ' DESC' : '' );
114 // Don't order by cl_from if it's constant in the WHERE clause
115 if ( count( $pages ) === 1 ) {
116 $this->addOption( 'ORDER BY', 'lt_title' . $sort );
117 } else {
118 $this->addOption( 'ORDER BY', [
119 'cl_from' . $sort,
120 'lt_title' . $sort
121 ] );
122 }
123 $this->addOption( 'LIMIT', $params['limit'] + 1 );
124
125 $res = $this->select( __METHOD__ );
126
127 $count = 0;
128 if ( $resultPageSet === null ) {
129 foreach ( $res as $row ) {
130 if ( ++$count > $params['limit'] ) {
131 // We've reached the one extra which shows that
132 // there are additional pages to be had. Stop here...
133 $this->setContinueEnumParameter( 'continue', $row->cl_from . '|' . $row->lt_title );
134 break;
135 }
136
137 $title = Title::makeTitle( NS_CATEGORY, $row->lt_title );
138 $vals = [];
139 ApiQueryBase::addTitleInfo( $vals, $title );
140 if ( isset( $prop['sortkey'] ) ) {
141 $vals['sortkey'] = bin2hex( $row->cl_sortkey );
142 $vals['sortkeyprefix'] = $row->cl_sortkey_prefix;
143 }
144 if ( isset( $prop['timestamp'] ) ) {
145 $vals['timestamp'] = wfTimestamp( TS::ISO_8601, $row->cl_timestamp );
146 }
147 if ( isset( $prop['hidden'] ) ) {
148 $vals['hidden'] = $row->pp_propname !== null;
149 }
150
151 $fit = $this->addPageSubItem( $row->cl_from, $vals );
152 if ( !$fit ) {
153 $this->setContinueEnumParameter( 'continue', $row->cl_from . '|' . $row->lt_title );
154 break;
155 }
156 }
157 } else {
158 $titles = [];
159 foreach ( $res as $row ) {
160 if ( ++$count > $params['limit'] ) {
161 // We've reached the one extra which shows that
162 // there are additional pages to be had. Stop here...
163 $this->setContinueEnumParameter( 'continue', $row->cl_from . '|' . $row->lt_title );
164 break;
165 }
166
167 $titles[] = Title::makeTitle( NS_CATEGORY, $row->lt_title );
168 }
169 $resultPageSet->populateFromTitles( $titles );
170 }
171 }
172
174 public function getAllowedParams() {
175 return [
176 'prop' => [
177 ParamValidator::PARAM_ISMULTI => true,
178 ParamValidator::PARAM_TYPE => [
179 'sortkey',
180 'timestamp',
181 'hidden',
182 ],
184 ],
185 'show' => [
186 ParamValidator::PARAM_ISMULTI => true,
187 ParamValidator::PARAM_TYPE => [
188 'hidden',
189 '!hidden',
190 ]
191 ],
192 'limit' => [
193 ParamValidator::PARAM_DEFAULT => 10,
194 ParamValidator::PARAM_TYPE => 'limit',
195 IntegerDef::PARAM_MIN => 1,
196 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
197 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
198 ],
199 'continue' => [
200 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
201 ],
202 'categories' => [
203 ParamValidator::PARAM_ISMULTI => true,
204 ],
205 'dir' => [
206 ParamValidator::PARAM_DEFAULT => 'ascending',
207 ParamValidator::PARAM_TYPE => [
208 'ascending',
209 'descending'
210 ]
211 ],
212 ];
213 }
214
216 protected function getExamplesMessages() {
217 return [
218 'action=query&prop=categories&titles=Albert%20Einstein'
219 => 'apihelp-query+categories-example-simple',
220 'action=query&generator=categories&titles=Albert%20Einstein&prop=info'
221 => 'apihelp-query+categories-example-generator',
222 ];
223 }
224
226 public function getHelpUrls() {
227 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Categories';
228 }
229}
230
232class_alias( ApiQueryCategories::class, 'ApiQueryCategories' );
const NS_CATEGORY
Definition Defines.php:65
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:1511
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1696
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:207
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1429
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:167
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:234
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:823
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:232
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.1.25, returning boolean false is deprecated...
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.Return value has query strings as keys, with values being eith...
__construct(ApiQuery $query, string $moduleName)
getCacheMode( $params)
Get the cache mode for the data generated by this module.Override this in the module subclass....
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:36
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
Represents a title within MediaWiki.
Definition Title.php:70
Service for formatting and validating API parameters.
Type definition for integer types.
Language name search API.
array $params
The job parameters.