MediaWiki 1.41.2
ApiQueryAllLinks.php
Go to the documentation of this file.
1<?php
29
36
37 private $table, $tablePrefix, $indexTag;
38 private $fieldTitle = 'title';
39 private $dfltNamespace = NS_MAIN;
40 private $hasNamespace = true;
41 private $useIndex = null;
42 private $props = [];
43
44 private NamespaceInfo $namespaceInfo;
45 private GenderCache $genderCache;
46 private LinksMigration $linksMigration;
47
55 public function __construct(
56 ApiQuery $query,
57 $moduleName,
58 NamespaceInfo $namespaceInfo,
59 GenderCache $genderCache,
60 LinksMigration $linksMigration
61 ) {
62 switch ( $moduleName ) {
63 case 'alllinks':
64 $prefix = 'al';
65 $this->table = 'pagelinks';
66 $this->tablePrefix = 'pl_';
67 $this->useIndex = 'pl_namespace';
68 $this->indexTag = 'l';
69 break;
70 case 'alltransclusions':
71 $prefix = 'at';
72 $this->table = 'templatelinks';
73 $this->tablePrefix = 'tl_';
74 $this->dfltNamespace = NS_TEMPLATE;
75 $this->useIndex = 'tl_namespace';
76 $this->indexTag = 't';
77 break;
78 case 'allfileusages':
79 $prefix = 'af';
80 $this->table = 'imagelinks';
81 $this->tablePrefix = 'il_';
82 $this->fieldTitle = 'to';
83 $this->dfltNamespace = NS_FILE;
84 $this->hasNamespace = false;
85 $this->indexTag = 'f';
86 break;
87 case 'allredirects':
88 $prefix = 'ar';
89 $this->table = 'redirect';
90 $this->tablePrefix = 'rd_';
91 $this->indexTag = 'r';
92 $this->props = [
93 'fragment' => 'rd_fragment',
94 'interwiki' => 'rd_interwiki',
95 ];
96 break;
97 default:
98 ApiBase::dieDebug( __METHOD__, 'Unknown module name' );
99 }
100
101 parent::__construct( $query, $moduleName, $prefix );
102 $this->namespaceInfo = $namespaceInfo;
103 $this->genderCache = $genderCache;
104 $this->linksMigration = $linksMigration;
105 }
106
107 public function execute() {
108 $this->run();
109 }
110
111 public function getCacheMode( $params ) {
112 return 'public';
113 }
114
115 public function executeGenerator( $resultPageSet ) {
116 $this->run( $resultPageSet );
117 }
118
123 private function run( $resultPageSet = null ) {
124 $db = $this->getDB();
125 $params = $this->extractRequestParams();
126
127 $pfx = $this->tablePrefix;
128
129 $nsField = $pfx . 'namespace';
130 $titleField = $pfx . $this->fieldTitle;
131 if ( isset( $this->linksMigration::$mapping[$this->table] ) ) {
132 [ $nsField, $titleField ] = $this->linksMigration->getTitleFields( $this->table );
133 $queryInfo = $this->linksMigration->getQueryInfo( $this->table );
134 $this->addTables( $queryInfo['tables'] );
135 $this->addJoinConds( $queryInfo['joins'] );
136 } else {
137 if ( $this->useIndex ) {
138 $this->addOption( 'USE INDEX', $this->useIndex );
139 }
140 $this->addTables( $this->table );
141 }
142
143 $prop = array_fill_keys( $params['prop'], true );
144 $fld_ids = isset( $prop['ids'] );
145 $fld_title = isset( $prop['title'] );
146 if ( $this->hasNamespace ) {
147 $namespace = $params['namespace'];
148 } else {
149 $namespace = $this->dfltNamespace;
150 }
151
152 if ( $params['unique'] ) {
153 $matches = array_intersect_key( $prop, $this->props + [ 'ids' => 1 ] );
154 if ( $matches ) {
155 $p = $this->getModulePrefix();
156 $this->dieWithError(
157 [
158 'apierror-invalidparammix-cannotusewith',
159 "{$p}prop=" . implode( '|', array_keys( $matches ) ),
160 "{$p}unique"
161 ],
162 'invalidparammix'
163 );
164 }
165 $this->addOption( 'DISTINCT' );
166 }
167
168 if ( $this->hasNamespace ) {
169 $this->addWhereFld( $nsField, $namespace );
170 }
171
172 $continue = $params['continue'] !== null;
173 if ( $continue ) {
174 $op = $params['dir'] == 'descending' ? '<=' : '>=';
175 if ( $params['unique'] ) {
176 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string' ] );
177 $this->addWhere( $db->buildComparison( $op, [ $titleField => $cont[0] ] ) );
178 } else {
179 $cont = $this->parseContinueParamOrDie( $params['continue'], [ 'string', 'int' ] );
180 $this->addWhere( $db->buildComparison( $op, [
181 $titleField => $cont[0],
182 "{$pfx}from" => $cont[1],
183 ] ) );
184 }
185 }
186
187 // 'continue' always overrides 'from'
188 $from = $continue || $params['from'] === null ? null :
189 $this->titlePartToKey( $params['from'], $namespace );
190 $to = $params['to'] === null ? null :
191 $this->titlePartToKey( $params['to'], $namespace );
192 $this->addWhereRange( $titleField, 'newer', $from, $to );
193
194 if ( isset( $params['prefix'] ) ) {
195 $this->addWhere( $titleField . $db->buildLike( $this->titlePartToKey(
196 $params['prefix'], $namespace ), $db->anyString() ) );
197 }
198
199 $this->addFields( [ 'pl_title' => $titleField ] );
200 $this->addFieldsIf( [ 'pl_from' => $pfx . 'from' ], !$params['unique'] );
201 foreach ( $this->props as $name => $field ) {
202 $this->addFieldsIf( $field, isset( $prop[$name] ) );
203 }
204
205 $limit = $params['limit'];
206 $this->addOption( 'LIMIT', $limit + 1 );
207
208 $sort = ( $params['dir'] == 'descending' ? ' DESC' : '' );
209 $orderBy = [];
210 $orderBy[] = $titleField . $sort;
211 if ( !$params['unique'] ) {
212 $orderBy[] = $pfx . 'from' . $sort;
213 }
214 $this->addOption( 'ORDER BY', $orderBy );
215
216 $res = $this->select( __METHOD__ );
217
218 // Get gender information
219 if ( $resultPageSet === null && $res->numRows() && $this->namespaceInfo->hasGenderDistinction( $namespace ) ) {
220 $users = [];
221 foreach ( $res as $row ) {
222 $users[] = $row->pl_title;
223 }
224 if ( $users !== [] ) {
225 $this->genderCache->doQuery( $users, __METHOD__ );
226 }
227 }
228
229 $pageids = [];
230 $titles = [];
231 $count = 0;
232 $result = $this->getResult();
233 foreach ( $res as $row ) {
234 if ( ++$count > $limit ) {
235 // We've reached the one extra which shows that there are
236 // additional pages to be had. Stop here...
237 if ( $params['unique'] ) {
238 $this->setContinueEnumParameter( 'continue', $row->pl_title );
239 } else {
240 $this->setContinueEnumParameter( 'continue', $row->pl_title . '|' . $row->pl_from );
241 }
242 break;
243 }
244
245 if ( $resultPageSet === null ) {
246 $vals = [
247 ApiResult::META_TYPE => 'assoc',
248 ];
249 if ( $fld_ids ) {
250 $vals['fromid'] = (int)$row->pl_from;
251 }
252 if ( $fld_title ) {
253 $title = Title::makeTitle( $namespace, $row->pl_title );
254 ApiQueryBase::addTitleInfo( $vals, $title );
255 }
256 foreach ( $this->props as $name => $field ) {
257 if ( isset( $prop[$name] ) && $row->$field !== null && $row->$field !== '' ) {
258 $vals[$name] = $row->$field;
259 }
260 }
261 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $vals );
262 if ( !$fit ) {
263 if ( $params['unique'] ) {
264 $this->setContinueEnumParameter( 'continue', $row->pl_title );
265 } else {
266 $this->setContinueEnumParameter( 'continue', $row->pl_title . '|' . $row->pl_from );
267 }
268 break;
269 }
270 } elseif ( $params['unique'] ) {
271 $titles[] = Title::makeTitle( $namespace, $row->pl_title );
272 } else {
273 $pageids[] = $row->pl_from;
274 }
275 }
276
277 if ( $resultPageSet === null ) {
278 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], $this->indexTag );
279 } elseif ( $params['unique'] ) {
280 $resultPageSet->populateFromTitles( $titles );
281 } else {
282 $resultPageSet->populateFromPageIDs( $pageids );
283 }
284 }
285
286 public function getAllowedParams() {
287 $allowedParams = [
288 'continue' => [
289 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
290 ],
291 'from' => null,
292 'to' => null,
293 'prefix' => null,
294 'unique' => false,
295 'prop' => [
296 ParamValidator::PARAM_ISMULTI => true,
297 ParamValidator::PARAM_DEFAULT => 'title',
298 ParamValidator::PARAM_TYPE => array_merge(
299 [ 'ids', 'title' ], array_keys( $this->props )
300 ),
302 ],
303 'namespace' => [
304 ParamValidator::PARAM_DEFAULT => $this->dfltNamespace,
305 ParamValidator::PARAM_TYPE => 'namespace',
306 NamespaceDef::PARAM_EXTRA_NAMESPACES => [ NS_MEDIA, NS_SPECIAL ],
307 ],
308 'limit' => [
309 ParamValidator::PARAM_DEFAULT => 10,
310 ParamValidator::PARAM_TYPE => 'limit',
311 IntegerDef::PARAM_MIN => 1,
312 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
313 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
314 ],
315 'dir' => [
316 ParamValidator::PARAM_DEFAULT => 'ascending',
317 ParamValidator::PARAM_TYPE => [
318 'ascending',
319 'descending'
320 ]
321 ],
322 ];
323 if ( !$this->hasNamespace ) {
324 unset( $allowedParams['namespace'] );
325 }
326
327 return $allowedParams;
328 }
329
330 protected function getExamplesMessages() {
331 $p = $this->getModulePrefix();
332 $name = $this->getModuleName();
333 $path = $this->getModulePath();
334
335 return [
336 "action=query&list={$name}&{$p}from=B&{$p}prop=ids|title"
337 => "apihelp-$path-example-b",
338 "action=query&list={$name}&{$p}unique=&{$p}from=B"
339 => "apihelp-$path-example-unique",
340 "action=query&generator={$name}&g{$p}unique=&g{$p}from=B"
341 => "apihelp-$path-example-unique-generator",
342 "action=query&generator={$name}&g{$p}from=B"
343 => "apihelp-$path-example-generator",
344 ];
345 }
346
347 public function getHelpUrls() {
348 $name = ucfirst( $this->getModuleName() );
349
350 return "https://www.mediawiki.org/wiki/Special:MyLanguage/API:{$name}";
351 }
352}
const NS_FILE
Definition Defines.php:70
const NS_MAIN
Definition Defines.php:64
const NS_TEMPLATE
Definition Defines.php:74
const NS_SPECIAL
Definition Defines.php:53
const NS_MEDIA
Definition Defines.php:52
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1515
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition ApiBase.php:537
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1759
parseContinueParamOrDie(string $continue, array $types)
Parse the 'continue' parameter in the usual format and validate the types of each part,...
Definition ApiBase.php:1706
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:209
const LIMIT_BIG1
Fast query, standard limit.
Definition ApiBase.php:234
getResult()
Get the result object.
Definition ApiBase.php:667
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:807
getModulePath()
Get the path to this module.
Definition ApiBase.php:607
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:169
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:236
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:528
static addTitleInfo(&$arr, $title, $prefix='')
Add information (title and namespace) about a Title object to a result array.
addWhereRange( $field, $dir, $start, $end, $sort=true)
Add a WHERE clause corresponding to a range, and an ORDER BY clause to sort in the right direction.
addFields( $value)
Add a set of fields to select to the internal array.
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
addTables( $tables, $alias=null)
Add a set of tables 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.
addFieldsIf( $value, $condition)
Same as addFields(), but add the fields only if a condition is met.
addJoinConds( $join_conds)
Add a set of JOIN conditions to the internal array.
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
titlePartToKey( $titlePart, $namespace=NS_MAIN)
Convert an input title or title prefix into a dbkey.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
setContinueEnumParameter( $paramName, $paramValue)
Overridden to set the generator param if in generator mode.
This is the main query class.
Definition ApiQuery.php:43
const META_TYPE
Key for the 'type' metadata item.
Look up "gender" user preference.
Service for compat reading of links tables.
Type definition for namespace types.
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
Represents a title within MediaWiki.
Definition Title.php:76
Service for formatting and validating API parameters.
Type definition for integer types.