MediaWiki master
ApiQueryBacklinksprop.php
Go to the documentation of this file.
1<?php
12namespace MediaWiki\Api;
13
22
31
33 private static $settings = [
34 'redirects' => [
35 'code' => 'rd',
36 'prefix' => 'rd',
37 'linktable' => 'redirect',
38 'props' => [
39 'fragment',
40 ],
41 'showredirects' => false,
42 'show' => [
43 'fragment',
44 '!fragment',
45 ],
46 ],
47 'linkshere' => [
48 'code' => 'lh',
49 'prefix' => 'pl',
50 'linktable' => 'pagelinks',
51 'index' => 'pl_backlinks_namespace_target_id',
52 'from_namespace' => true,
53 'showredirects' => true,
54 'virtualdomain' => PageLinksTable::VIRTUAL_DOMAIN,
55 ],
56 'transcludedin' => [
57 'code' => 'ti',
58 'prefix' => 'tl',
59 'linktable' => 'templatelinks',
60 'from_namespace' => true,
61 'showredirects' => true,
62 'virtualdomain' => TemplateLinksTable::VIRTUAL_DOMAIN,
63 ],
64 'fileusage' => [
65 'code' => 'fu',
66 'prefix' => 'il',
67 'linktable' => 'imagelinks',
68 'index' => 'il_backlinks_namespace_target_id',
69 'from_namespace' => true,
70 'exampletitle' => 'File:Example.jpg',
71 'showredirects' => true,
72 'virtualdomain' => ImageLinksTable::VIRTUAL_DOMAIN,
73 ],
74 ];
75
76 public function __construct(
77 ApiQuery $query,
78 string $moduleName,
79 private readonly LinksMigration $linksMigration,
80 ) {
81 parent::__construct( $query, $moduleName, self::$settings[$moduleName]['code'] );
82 }
83
84 public function execute() {
85 $this->run();
86 }
87
89 public function executeGenerator( $resultPageSet ) {
90 $this->run( $resultPageSet );
91 }
92
96 private function run( ?ApiPageSet $resultPageSet = null ) {
97 $settings = self::$settings[$this->getModuleName()];
98
99 $domain = $settings['virtualdomain'] ?? false;
100 $this->setVirtualDomain( $domain );
101 $db = $this->getDB();
102
103 $params = $this->extractRequestParams();
104 $prop = array_fill_keys( $params['prop'], true );
105
106 $pageSet = $this->getPageSet();
107 $titles = $pageSet->getGoodAndMissingPages();
108 $map = $pageSet->getGoodAndMissingTitlesByNamespace();
109
110 // Add in special pages, they can theoretically have backlinks too.
111 // (although currently they only do for prop=redirects)
112 foreach ( $pageSet->getSpecialPages() as $id => $title ) {
113 $titles[] = $title;
114 $map[$title->getNamespace()][$title->getDBkey()] = $id;
115 }
116
117 // Determine our fields to query on
118 $p = $settings['prefix'];
119
120 if ( isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
121 [ $bl_namespace, $bl_title ] = $this->linksMigration->getTitleFields( $settings['linktable'] );
122 } else {
123 $bl_namespace = "{$p}_namespace";
124 $bl_title = "{$p}_title";
125 }
126 $bl_from = "{$p}_from";
127
128 $hasNS = !is_int( $bl_namespace );
129 if ( !$hasNS ) {
130 $titles = array_filter( $titles, static function ( $t ) use ( $bl_namespace ) {
131 return $t->getNamespace() === $bl_namespace;
132 } );
133 $map = array_intersect_key( $map, [ $bl_namespace => true ] );
134 }
135
136 if ( !$titles ) {
137 return; // nothing to do
138 }
139 if ( $params['namespace'] !== null && count( $params['namespace'] ) === 0 ) {
140 return; // nothing to do
141 }
142
143 // Figure out what we're sorting by, and add associated WHERE clauses.
144 // MySQL's query planner screws up if we include a field in ORDER BY
145 // when it's constant in WHERE, so we have to test that for each field.
146 $sortby = [];
147 if ( $hasNS && count( $map ) > 1 ) {
148 $sortby[$bl_namespace] = 'int';
149 }
150 $theTitle = null;
151 foreach ( $map as $nsTitles ) {
152 $key = array_key_first( $nsTitles );
153 $theTitle ??= $key;
154 if ( count( $nsTitles ) > 1 || $key !== $theTitle ) {
155 $sortby[$bl_title] = 'string';
156 break;
157 }
158 }
159 $miser_ns = null;
160 if ( $params['namespace'] !== null ) {
161 if ( empty( $settings['from_namespace'] ) ) {
162 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
163 $miser_ns = $params['namespace'];
164 } else {
165 $this->addWhereFld( 'page_namespace', $params['namespace'] );
166 }
167 } else {
168 $this->addWhereFld( "{$p}_from_namespace", $params['namespace'] );
169 if ( !empty( $settings['from_namespace'] )
170 && $params['namespace'] !== null && count( $params['namespace'] ) > 1
171 ) {
172 $sortby["{$p}_from_namespace"] = 'int';
173 }
174 }
175 }
176 $sortby[$bl_from] = 'int';
177
178 // Now use the $sortby to figure out the continuation
179 $continueFields = array_keys( $sortby );
180 $continueTypes = array_values( $sortby );
181 if ( $params['continue'] !== null ) {
182 $continueValues = $this->parseContinueParamOrDie( $params['continue'], $continueTypes );
183 $conds = array_combine( $continueFields, $continueValues );
184 $this->addWhere( $db->buildComparison( '>=', $conds ) );
185 }
186
187 // Populate the rest of the query
188 if ( isset( $this->linksMigration::$mapping[$settings['linktable']] ) ) {
189 $queryInfo = $this->linksMigration->getQueryInfo( $settings['linktable'] );
190 $this->addTables( [ 'page', ...$queryInfo['tables'] ] );
191 $this->addJoinConds( $queryInfo['joins'] );
192 } else {
193 $this->addTables( [ $settings['linktable'], 'page' ] );
194 }
195 $this->addWhere( "$bl_from = page_id" );
196
197 if ( $this->getModuleName() === 'redirects' ) {
198 $this->addWhereFld( 'rd_interwiki', '' );
199 }
200
201 $this->addFields( array_keys( $sortby ) );
202 $this->addFields( [ 'bl_namespace' => $bl_namespace, 'bl_title' => $bl_title ] );
203 if ( $resultPageSet === null ) {
204 $fld_pageid = isset( $prop['pageid'] );
205 $fld_title = isset( $prop['title'] );
206 $fld_redirect = isset( $prop['redirect'] );
207
208 $this->addFieldsIf( 'page_id', $fld_pageid );
209 $this->addFieldsIf( [ 'page_title', 'page_namespace' ], $fld_title );
210 $this->addFieldsIf( 'page_is_redirect', $fld_redirect );
211
212 // prop=redirects
213 $fld_fragment = isset( $prop['fragment'] );
214 $this->addFieldsIf( 'rd_fragment', $fld_fragment );
215 } else {
216 $this->addFields( $resultPageSet->getPageTableFields() );
217 }
218
219 $this->addFieldsIf( 'page_namespace', $miser_ns !== null );
220
221 if ( $hasNS && $map ) {
222 // Can't use LinkBatch because it throws away Special titles.
223 // And we already have the needed data structure anyway.
224 $this->addWhere( $db->makeWhereFrom2d( $map, $bl_namespace, $bl_title ) );
225 } else {
226 $where = [];
227 foreach ( $titles as $t ) {
228 if ( $t->getNamespace() == $bl_namespace ) {
229 $where[] = $db->expr( $bl_title, '=', $t->getDBkey() );
230 }
231 }
232 $this->addWhere( $db->orExpr( $where ) );
233 }
234
235 if ( $params['show'] !== null ) {
236 // prop=redirects only
237 $show = array_fill_keys( $params['show'], true );
238 if ( ( isset( $show['fragment'] ) && isset( $show['!fragment'] ) ) ||
239 ( isset( $show['redirect'] ) && isset( $show['!redirect'] ) )
240 ) {
241 $this->dieWithError( 'apierror-show' );
242 }
243 $this->addWhereIf( $db->expr( 'rd_fragment', '!=', '' ), isset( $show['fragment'] ) );
244 $this->addWhereIf( [ 'rd_fragment' => '' ], isset( $show['!fragment'] ) );
245 $this->addWhereIf( [ 'page_is_redirect' => 1 ], isset( $show['redirect'] ) );
246 $this->addWhereIf( [ 'page_is_redirect' => 0 ], isset( $show['!redirect'] ) );
247 }
248
249 // Override any ORDER BY from above with what we calculated earlier.
250 $this->addOption( 'ORDER BY', array_keys( $sortby ) );
251
252 // MySQL's optimizer chokes if we have too many values in "$bl_title IN
253 // (...)" and chooses the wrong index, so specify the correct index to
254 // use for the query. See T139056 for details.
255 if ( array_key_exists( 'index', $settings ) &&
256 $params['namespace'] !== null &&
257 count( $params['namespace'] ) == 1 &&
258 !empty( $settings['from_namespace'] )
259 ) {
260 $this->addOption( 'USE INDEX', [ $settings['linktable'] => $settings['index'] ] );
261 }
262
263 $this->addOption( 'LIMIT', $params['limit'] + 1 );
264
265 $res = $this->select( __METHOD__ );
266
267 if ( $resultPageSet === null ) {
268 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
269 if ( $fld_title ) {
270 $this->executeGenderCacheFromResultWrapper( $res, __METHOD__ );
271 }
272
273 $count = 0;
274 foreach ( $res as $row ) {
275 if ( ++$count > $params['limit'] ) {
276 // We've reached the one extra which shows that
277 // there are additional pages to be had. Stop here...
278 $this->setContinue( $row, $sortby );
279 break;
280 }
281
282 if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
283 // Miser mode namespace check
284 continue;
285 }
286
287 // Get the ID of the current page
288 $id = $map[$row->bl_namespace][$row->bl_title];
289
290 $vals = [];
291 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
292 if ( $fld_pageid ) {
293 $vals['pageid'] = (int)$row->page_id;
294 }
295 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
296 if ( $fld_title ) {
298 Title::makeTitle( $row->page_namespace, $row->page_title )
299 );
300 }
301 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
302 if ( $fld_fragment && $row->rd_fragment !== '' ) {
303 $vals['fragment'] = $row->rd_fragment;
304 }
305 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable set when used
306 if ( $fld_redirect ) {
307 $vals['redirect'] = (bool)$row->page_is_redirect;
308 }
309 $fit = $this->addPageSubItem( $id, $vals );
310 if ( !$fit ) {
311 $this->setContinue( $row, $sortby );
312 break;
313 }
314 }
315 } else {
316 $titles = [];
317 $count = 0;
318 foreach ( $res as $row ) {
319 if ( ++$count > $params['limit'] ) {
320 // We've reached the one extra which shows that
321 // there are additional pages to be had. Stop here...
322 $this->setContinue( $row, $sortby );
323 break;
324 }
325
326 if ( $miser_ns !== null && !in_array( $row->page_namespace, $miser_ns ) ) {
327 // Miser mode namespace check
328 continue;
329 }
330
331 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
332 }
333 $resultPageSet->populateFromTitles( $titles );
334 }
335 }
336
337 private function setContinue( \stdClass $row, array $sortby ) {
338 $cont = [];
339 foreach ( $sortby as $field => $v ) {
340 $cont[] = $row->$field;
341 }
342 $this->setContinueEnumParameter( 'continue', implode( '|', $cont ) );
343 }
344
346 public function getCacheMode( $params ) {
347 return 'public';
348 }
349
351 public function getAllowedParams() {
352 $settings = self::$settings[$this->getModuleName()];
353
354 $ret = [
355 'prop' => [
356 ParamValidator::PARAM_TYPE => [
357 'pageid',
358 'title',
359 ],
360 ParamValidator::PARAM_ISMULTI => true,
361 ParamValidator::PARAM_DEFAULT => 'pageid|title',
363 ],
364 'namespace' => [
365 ParamValidator::PARAM_ISMULTI => true,
366 ParamValidator::PARAM_TYPE => 'namespace',
367 ],
368 'show' => null, // Will be filled/removed below
369 'limit' => [
370 ParamValidator::PARAM_DEFAULT => 10,
371 ParamValidator::PARAM_TYPE => 'limit',
372 IntegerDef::PARAM_MIN => 1,
373 IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
374 IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2
375 ],
376 'continue' => [
377 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
378 ],
379 ];
380
381 if ( empty( $settings['from_namespace'] ) &&
382 $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
383 $ret['namespace'][ApiBase::PARAM_HELP_MSG_APPEND] = [
384 'api-help-param-limited-in-miser-mode',
385 ];
386 }
387
388 if ( !empty( $settings['showredirects'] ) ) {
389 $ret['prop'][ParamValidator::PARAM_TYPE][] = 'redirect';
390 $ret['prop'][ParamValidator::PARAM_DEFAULT] .= '|redirect';
391 }
392 if ( isset( $settings['props'] ) ) {
393 $ret['prop'][ParamValidator::PARAM_TYPE] = array_merge(
394 $ret['prop'][ParamValidator::PARAM_TYPE], $settings['props']
395 );
396 }
397
398 $show = [];
399 if ( !empty( $settings['showredirects'] ) ) {
400 $show[] = 'redirect';
401 $show[] = '!redirect';
402 }
403 if ( isset( $settings['show'] ) ) {
404 $show = array_merge( $show, $settings['show'] );
405 }
406 if ( $show ) {
407 $ret['show'] = [
408 ParamValidator::PARAM_TYPE => $show,
409 ParamValidator::PARAM_ISMULTI => true,
411 ];
412 } else {
413 unset( $ret['show'] );
414 }
415
416 return $ret;
417 }
418
420 protected function getExamplesMessages() {
421 $settings = self::$settings[$this->getModuleName()];
422 $name = $this->getModuleName();
423 $path = $this->getModulePath();
424 $title = $settings['exampletitle'] ?? Title::newMainPage()->getPrefixedText();
425 $etitle = rawurlencode( $title );
426
427 return [
428 "action=query&prop={$name}&titles={$etitle}"
429 => "apihelp-$path-example-simple",
430 "action=query&generator={$name}&titles={$etitle}&prop=info"
431 => "apihelp-$path-example-generator",
432 ];
433 }
434
436 public function getHelpUrls() {
437 $name = ucfirst( $this->getModuleName() );
438 return "https://www.mediawiki.org/wiki/Special:MyLanguage/API:{$name}";
439 }
440}
441
443class_alias( ApiQueryBacklinksprop::class, 'ApiQueryBacklinksprop' );
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1522
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:557
getModulePath()
Get the path to this module.
Definition ApiBase.php:636
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:206
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition ApiBase.php:174
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:166
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition ApiBase.php:233
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:231
This class contains a list of pages that the client has requested.
This implements prop=redirects, prop=linkshere, prop=catmembers, prop=transcludedin,...
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.
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.
__construct(ApiQuery $query, string $moduleName, private readonly LinksMigration $linksMigration,)
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
getCacheMode( $params)
Get the cache mode for the data generated by this module.Override this in the module subclass....
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.
addWhereIf( $value, $condition)
Same as addWhere(), but add the WHERE clauses only if a condition is met.
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.
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.
addWhere( $value)
Add a set of WHERE clauses to the internal array.
executeGenderCacheFromResultWrapper(IResultWrapper $res, $fname=__METHOD__, $fieldPrefix='page')
Preprocess the result set to fill the GenderCache with the necessary information before using self::a...
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
addFields( $value)
Add a set of fields to select to the internal array.
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
Service for compat reading of links tables.
A class containing constants representing the names of configuration variables.
const MiserMode
Name constant for the MiserMode setting, for use with Config::get()
Represents a title within MediaWiki.
Definition Title.php:69
Service for formatting and validating API parameters.
Type definition for integer types.
array $params
The job parameters.