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