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