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